@@ -146,30 +155,89 @@
android:name=".services.DataService"
android:exported="false" />
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+ android:label="@string/title_activity_setup_wizard"
+ android:theme="@style/AppTheme.NoActionBar" />
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
\ No newline at end of file
+
diff --git a/app/src/main/assets/OpenAPSAMA/loggerhelper.js b/app/src/main/assets/OpenAPSAMA/loggerhelper.js
index e790f465c8..81c19b5a38 100644
--- a/app/src/main/assets/OpenAPSAMA/loggerhelper.js
+++ b/app/src/main/assets/OpenAPSAMA/loggerhelper.js
@@ -1,12 +1,33 @@
var console = { };
console.error = function error(){
+ var s = '';
for (var i = 0, len = arguments.length; i < len; i++) {
- console2.log(arguments[i]);
+ if (i > 0) s = s + ' ';
+ if (typeof arguments[i] === 'undefined') {
+ s = s + 'undefined';
+ } else if (typeof arguments[i] === 'object') {
+ s = s + JSON.stringify(arguments[i]);
+ } else {
+ s = s + arguments[i].toString();
+ }
}
+ s = s + "\n";
+ console2.log(s);
};
console.log = function log(){
+ var s = '';
for (var i = 0, len = arguments.length; i < len; i++) {
- console2.log(arguments[i]);
+ if (i > 0) s = s + ' ';
+ if (typeof arguments[i] === 'undefined') {
+ s = s + 'undefined';
+ } else if (typeof arguments[i] === 'object') {
+ s = s + JSON.stringify(arguments[i]);
+ } else {
+ s = s + arguments[i].toString();
+ }
+ //console2.log(arguments[i]);
}
+ s = s + "\n";
+ console2.log(s);
};
diff --git a/app/src/main/assets/revoked_certs.txt b/app/src/main/assets/revoked_certs.txt
new file mode 100644
index 0000000000..59a55d9e42
--- /dev/null
+++ b/app/src/main/assets/revoked_certs.txt
@@ -0,0 +1,2 @@
+#Demo certificate
+51:6D:12:67:4C:27:F4:9B:9F:E5:42:9B:01:B3:98:E4:66:2B:85:B7:A8:DD:70:32:B7:6A:D7:97:9A:0D:97:10
\ No newline at end of file
diff --git a/app/src/main/java/com/squareup/otto/LoggingBus.java b/app/src/main/java/com/squareup/otto/LoggingBus.java
deleted file mode 100644
index d9758a9a24..0000000000
--- a/app/src/main/java/com/squareup/otto/LoggingBus.java
+++ /dev/null
@@ -1,96 +0,0 @@
-package com.squareup.otto;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ConcurrentModificationException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import info.nightscout.androidaps.events.Event;
-import info.nightscout.androidaps.logging.L;
-
-/**
- * Logs events has they're being posted to and dispatched from the event bus.
- *
- * A summary of event-receiver calls that occurred so far is logged
- * after 10s (after startup) and then again every 60s.
- */
-public class LoggingBus extends Bus {
- private static Logger log = LoggerFactory.getLogger(L.EVENTS);
-
- private static long everyMinute = System.currentTimeMillis() + 10 * 1000;
- private Map> event2Receiver = new HashMap<>();
-
- public LoggingBus(ThreadEnforcer enforcer) {
- super(enforcer);
- }
-
- @Override
- public void post(Object event) {
- if (event instanceof DeadEvent) {
- log.debug("Event has no receiver: " + ((DeadEvent) event).event + ", source: " + ((DeadEvent) event).source);
- return;
- }
-
- if (!(event instanceof Event)) {
- log.error("Posted event not an event class: " + event.getClass());
- }
-
- log.debug("<<< " + event);
- try {
- StackTraceElement caller = new Throwable().getStackTrace()[1];
- String className = caller.getClassName();
- className = className.substring(className.lastIndexOf(".") + 1);
- log.debug(" source: " + className + "." + caller.getMethodName() + ":" + caller.getLineNumber());
- } catch (RuntimeException e) {
- log.debug(" source: ");
- }
-
- try {
- super.post(event);
- } catch (IllegalStateException ignored) {
- }
- }
-
- @Override
- protected void dispatch(Object event, EventHandler wrapper) {
- try {
- log.debug(">>> " + event);
- Field methodField = wrapper.getClass().getDeclaredField("method");
- methodField.setAccessible(true);
- Method targetMethod = (Method) methodField.get(wrapper);
- String className = targetMethod.getDeclaringClass().getSimpleName();
- String methodName = targetMethod.getName();
- String receiverMethod = className + "." + methodName;
- log.debug(" receiver: " + receiverMethod);
-
- String key = event.getClass().getSimpleName();
- if (!event2Receiver.containsKey(key)) event2Receiver.put(key, new HashSet());
- event2Receiver.get(key).add(receiverMethod);
- } catch (ReflectiveOperationException e) {
- log.debug(" receiver: ");
- }
-
- try {
- if (everyMinute < System.currentTimeMillis()) {
- log.debug("***************** Event -> receiver pairings seen so far ****************");
- for (Map.Entry> stringSetEntry : event2Receiver.entrySet()) {
- log.debug(" " + stringSetEntry.getKey());
- for (String s : stringSetEntry.getValue()) {
- log.debug(" -> " + s);
- }
- }
- log.debug("*************************************************************************");
- everyMinute = System.currentTimeMillis() + 60 * 1000;
- }
- } catch (ConcurrentModificationException ignored) {
- }
-
- super.dispatch(event, wrapper);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java
index ae0e14c9b6..bb967cdeb6 100644
--- a/app/src/main/java/info/nightscout/androidaps/Config.java
+++ b/app/src/main/java/info/nightscout/androidaps/Config.java
@@ -12,13 +12,4 @@ public class Config {
public static final boolean PUMPCONTROL = BuildConfig.FLAVOR.equals("pumpcontrol");
public static final boolean PUMPDRIVERS = BuildConfig.FLAVOR.equals("full") || BuildConfig.FLAVOR.equals("pumpcontrol");
-
- public static final boolean ACTION = !NSCLIENT;
- public static final boolean MDI = !NSCLIENT;
- public static final boolean OTHERPROFILES = !NSCLIENT;
- public static final boolean SAFETY = !NSCLIENT;
-
- public static final boolean SMSCOMMUNICATORENABLED = !NSCLIENT;
-
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/Constants.java b/app/src/main/java/info/nightscout/androidaps/Constants.java
index ffe227dc1b..21a89d8920 100644
--- a/app/src/main/java/info/nightscout/androidaps/Constants.java
+++ b/app/src/main/java/info/nightscout/androidaps/Constants.java
@@ -1,6 +1,6 @@
package info.nightscout.androidaps;
-import info.nightscout.utils.T;
+import info.nightscout.androidaps.utils.T;
/**
* Created by mike on 07.06.2016.
@@ -31,11 +31,13 @@ public class Constants {
public static final long remoteBolusMinDistance = 15 * 60 * 1000L;
// Circadian Percentage Profile
- public static final int CPP_MIN_PERCENTAGE = 50;
+ public static final int CPP_MIN_PERCENTAGE = 30;
public static final int CPP_MAX_PERCENTAGE = 200;
public static final int CPP_MIN_TIMESHIFT = -6;
public static final int CPP_MAX_TIMESHIFT = 23;
+ public static final double MAX_PROFILE_SWITCH_DURATION = 7 * 24 * 60; // [min] ~ 7 days
+
//DanaR
public static final double dailyLimitWarning = 0.95d;
@@ -50,6 +52,11 @@ public class Constants {
public static final double defaultHypoTTmgdl = 120d;
public static final double defaultHypoTTmmol = 6.5d;
+ public static final double MIN_TT_MGDL = 72d;
+ public static final double MAX_TT_MGDL = 180d;
+ public static final double MIN_TT_MMOL = 4d;
+ public static final double MAX_TT_MMOL = 10d;
+
//NSClientInternal
public static final int MAX_LOG_LINES = 100;
@@ -68,4 +75,7 @@ public class Constants {
//SMS Communicator
public static final long SMS_CONFIRM_TIMEOUT = T.mins(5).msecs();
+ //Storage [MB]
+ public static final long MINIMUM_FREE_SPACE = 200;
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java
index 844f218803..64c2656086 100644
--- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java
@@ -6,17 +6,6 @@ import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.PersistableBundle;
-import android.os.PowerManager;
-import android.support.annotation.Nullable;
-import android.support.design.widget.NavigationView;
-import android.support.design.widget.TabLayout;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.view.ViewPager;
-import android.support.v4.widget.DrawerLayout;
-import android.support.v7.app.ActionBarDrawerToggle;
-import android.support.v7.app.AlertDialog;
-import android.support.v7.app.AppCompatActivity;
-import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
@@ -31,53 +20,65 @@ import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.ActionBarDrawerToggle;
+import androidx.appcompat.app.AlertDialog;
+import androidx.appcompat.widget.Toolbar;
+import androidx.core.app.ActivityCompat;
+import androidx.drawerlayout.widget.DrawerLayout;
+import androidx.viewpager.widget.ViewPager;
+
+import com.google.android.material.navigation.NavigationView;
+import com.google.android.material.tabs.TabLayout;
import com.joanzapata.iconify.Iconify;
import com.joanzapata.iconify.fonts.FontAwesomeModule;
-import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.activities.AgreementActivity;
import info.nightscout.androidaps.activities.HistoryBrowseActivity;
+import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.activities.SingleFragmentActivity;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventAppExit;
-import info.nightscout.androidaps.events.EventFeatureRunning;
import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginBase;
+import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSettingsStatus;
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt;
+import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.setupwizard.SetupWizardActivity;
import info.nightscout.androidaps.tabs.TabPageAdapter;
-import info.nightscout.utils.AndroidPermission;
-import info.nightscout.utils.LocaleHelper;
-import info.nightscout.utils.OKDialog;
-import info.nightscout.utils.PasswordProtection;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.VersionChecker;
+import info.nightscout.androidaps.utils.AndroidPermission;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.LocaleHelper;
+import info.nightscout.androidaps.utils.OKDialog;
+import info.nightscout.androidaps.utils.PasswordProtection;
+import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class MainActivity extends AppCompatActivity {
+public class MainActivity extends NoSplashAppCompatActivity {
private static Logger log = LoggerFactory.getLogger(L.CORE);
-
- protected PowerManager.WakeLock mWakeLock;
+ private CompositeDisposable disposable = new CompositeDisposable();
private ActionBarDrawerToggle actionBarDrawerToggle;
private MenuItem pluginPreferencesMenuItem;
@Override
- protected void onCreate(Bundle savedInstanceState) {
+ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- if (L.isEnabled(L.CORE))
- log.debug("onCreate");
-
Iconify.with(new FontAwesomeModule());
- LocaleHelper.onCreate(this, "en");
+ LocaleHelper.INSTANCE.update(getApplicationContext());
setContentView(R.layout.activity_main);
setSupportActionBar(findViewById(R.id.toolbar));
@@ -91,14 +92,10 @@ public class MainActivity extends AppCompatActivity {
actionBarDrawerToggle.syncState();
// initialize screen wake lock
- onEventPreferenceChange(new EventPreferenceChange(R.string.key_keep_screen_on));
+ processPreferenceChange(new EventPreferenceChange(R.string.key_keep_screen_on));
doMigrations();
- registerBus();
- setupTabs();
- setupViews(false);
-
final ViewPager viewPager = findViewById(R.id.pager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
@@ -114,7 +111,49 @@ public class MainActivity extends AppCompatActivity {
public void onPageScrollStateChanged(int state) {
}
});
- VersionChecker.check();
+
+ //Check here if loop plugin is disabled. Else check via constraints
+ if (!LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))
+ VersionCheckerUtilsKt.triggerCheckVersion();
+
+ FabricPrivacy.setUserStats();
+
+ setupTabs();
+ setupViews();
+
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventRebuildTabs.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ LocaleHelper.INSTANCE.update(getApplicationContext());
+ if (event.getRecreate()) {
+ recreate();
+ } else {
+ setupTabs();
+ setupViews();
+ }
+ setWakeLock();
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(this::processPreferenceChange, FabricPrivacy::logException)
+ );
+
+ if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) {
+ Intent intent = new Intent(this, SetupWizardActivity.class);
+ startActivity(intent);
+ } else {
+ checkEula();
+ }
+
+ AndroidPermission.notifyForStoragePermission(this);
+ AndroidPermission.notifyForBatteryOptimizationPermission(this);
+ if (Config.PUMPDRIVERS) {
+ AndroidPermission.notifyForLocationPermissions(this);
+ AndroidPermission.notifyForSMSPermissions(this);
+ }
}
private void checkPluginPreferences(ViewPager viewPager) {
@@ -130,86 +169,29 @@ public class MainActivity extends AppCompatActivity {
actionBarDrawerToggle.syncState();
}
- @Override
- protected void onResume() {
- super.onResume();
-
- if (L.isEnabled(L.CORE))
- log.debug("onResume");
-
- if (!SP.getBoolean(R.string.key_setupwizard_processed, false)) {
- Intent intent = new Intent(this, SetupWizardActivity.class);
- startActivity(intent);
- } else {
- checkEula();
- }
-
- AndroidPermission.notifyForStoragePermission(this);
- AndroidPermission.notifyForBatteryOptimizationPermission(this);
- if (Config.PUMPDRIVERS) {
- AndroidPermission.notifyForLocationPermissions(this);
- AndroidPermission.notifyForSMSPermissions(this);
- }
-
- MainApp.bus().post(new EventFeatureRunning(EventFeatureRunning.Feature.MAIN));
- }
-
@Override
public void onDestroy() {
- if (L.isEnabled(L.CORE))
- log.debug("onDestroy");
- if (mWakeLock != null)
- if (mWakeLock.isHeld())
- mWakeLock.release();
super.onDestroy();
+ disposable.clear();
}
- @Subscribe
- public void onEventPreferenceChange(final EventPreferenceChange ev) {
- if (ev.isChanged(R.string.key_keep_screen_on)) {
- boolean keepScreenOn = SP.getBoolean(R.string.key_keep_screen_on, false);
- final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
- if (keepScreenOn) {
- mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "AAPS");
- if (!mWakeLock.isHeld())
- mWakeLock.acquire();
- } else {
- if (mWakeLock != null && mWakeLock.isHeld())
- mWakeLock.release();
- }
- }
+ private void setWakeLock() {
+ boolean keepScreenOn = SP.getBoolean(R.string.key_keep_screen_on, false);
+ if (keepScreenOn)
+ getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
+ else
+ getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
- @Subscribe
- public void onStatusEvent(final EventRefreshGui ev) {
- String lang = SP.getString(R.string.key_language, "en");
- LocaleHelper.setLocale(getApplicationContext(), lang);
- runOnUiThread(() -> {
- if (ev.recreate) {
- recreate();
- } else {
- try { // activity may be destroyed
- setupTabs();
- setupViews(true);
- } catch (IllegalStateException e) {
- log.error("Unhandled exception", e);
- }
- }
-
- boolean keepScreenOn = Config.NSCLIENT && SP.getBoolean(R.string.key_keep_screen_on, false);
- if (keepScreenOn)
- getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- else
- getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
- });
+ public void processPreferenceChange(final EventPreferenceChange ev) {
+ if (ev.isChanged(R.string.key_keep_screen_on))
+ setWakeLock();
}
- private void setupViews(boolean switchToLast) {
+ private void setupViews() {
TabPageAdapter pageAdapter = new TabPageAdapter(getSupportFragmentManager(), this);
NavigationView navigationView = findViewById(R.id.navigation_view);
- navigationView.setNavigationItemSelectedListener(menuItem -> {
- return true;
- });
+ navigationView.setNavigationItemSelectedListener(menuItem -> true);
Menu menu = navigationView.getMenu();
menu.clear();
for (PluginBase p : MainApp.getPluginsList()) {
@@ -228,8 +210,8 @@ public class MainActivity extends AppCompatActivity {
}
ViewPager mPager = findViewById(R.id.pager);
mPager.setAdapter(pageAdapter);
- if (switchToLast)
- mPager.setCurrentItem(pageAdapter.getCount() - 1, false);
+ //if (switchToLast)
+ // mPager.setCurrentItem(pageAdapter.getCount() - 1, false);
checkPluginPreferences(mPager);
}
@@ -255,15 +237,6 @@ public class MainActivity extends AppCompatActivity {
}
}
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
- }
-
private void checkEula() {
//SP.removeBoolean(R.string.key_i_understand);
boolean IUnderstand = SP.getBoolean(R.string.key_i_understand, false);
@@ -280,10 +253,10 @@ public class MainActivity extends AppCompatActivity {
// guarantee that the unreachable threshold is at least 30 and of type String
// Added in 1.57 at 21.01.2018
- Integer unreachable_threshold = SP.getInt(R.string.key_pump_unreachable_threshold, 30);
+ int unreachable_threshold = SP.getInt(R.string.key_pump_unreachable_threshold, 30);
SP.remove(R.string.key_pump_unreachable_threshold);
if (unreachable_threshold < 30) unreachable_threshold = 30;
- SP.putString(R.string.key_pump_unreachable_threshold, unreachable_threshold.toString());
+ SP.putString(R.string.key_pump_unreachable_threshold, Integer.toString(unreachable_threshold));
}
@@ -299,19 +272,16 @@ public class MainActivity extends AppCompatActivity {
String message = "Target range is changed in current version.\n\nIt's not taken from preferences but from profile.\n\n!!! REVIEW YOUR SETTINGS !!!";
message += "\n\nOld settings: " + oldRange;
message += "\nProfile settings: " + newRange;
- OKDialog.show(this, "Target range change", message, new Runnable() {
- @Override
- public void run() {
- SP.remove("openapsma_min_bg");
- SP.remove("openapsma_max_bg");
- SP.remove("openapsma_target_bg");
- }
+ OKDialog.show(this, "Target range change", message, () -> {
+ SP.remove("openapsma_min_bg");
+ SP.remove("openapsma_max_bg");
+ SP.remove("openapsma_target_bg");
});
}
}
@Override
- public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
+ public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissions.length != 0) {
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
@@ -326,7 +296,7 @@ public class MainActivity extends AppCompatActivity {
case AndroidPermission.CASE_LOCATION:
case AndroidPermission.CASE_SMS:
case AndroidPermission.CASE_BATTERY:
- case AndroidPermission.CASE_PHONESTATE:
+ case AndroidPermission.CASE_PHONE_STATE:
break;
}
}
@@ -378,10 +348,7 @@ public class MainActivity extends AppCompatActivity {
case R.id.nav_about:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(MainApp.gs(R.string.app_name) + " " + BuildConfig.VERSION);
- if (Config.NSCLIENT)
- builder.setIcon(R.mipmap.yellowowl);
- else
- builder.setIcon(R.mipmap.blueowl);
+ builder.setIcon(MainApp.getIcon());
String message = "Build: " + BuildConfig.BUILDVERSION + "\n";
message += "Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + "\n";
message += MainApp.gs(R.string.configbuilder_nightscoutversion_label) + " " + NSSettingsStatus.getInstance().nightscoutVersionName;
@@ -399,7 +366,7 @@ public class MainActivity extends AppCompatActivity {
case R.id.nav_exit:
log.debug("Exiting");
MainApp.instance().stopKeepAliveService();
- MainApp.bus().post(new EventAppExit());
+ RxBus.INSTANCE.send(new EventAppExit());
MainApp.closeDbHelper();
finish();
System.runFinalization();
diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java
index 327e451225..379afabddf 100644
--- a/app/src/main/java/info/nightscout/androidaps/MainApp.java
+++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java
@@ -1,19 +1,17 @@
package info.nightscout.androidaps;
import android.app.Application;
+import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.os.SystemClock;
-import android.support.annotation.Nullable;
-import android.support.annotation.PluralsRes;
-import android.support.v4.content.LocalBroadcastManager;
+
+import androidx.annotation.PluralsRes;
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import com.crashlytics.android.Crashlytics;
-import com.crashlytics.android.answers.Answers;
+import com.google.firebase.analytics.FirebaseAnalytics;
import com.j256.ormlite.android.apptools.OpenHelperManager;
-import com.squareup.otto.Bus;
-import com.squareup.otto.LoggingBus;
-import com.squareup.otto.ThreadEnforcer;
import net.danlew.android.joda.JodaTimeAndroid;
@@ -29,69 +27,82 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Actions.ActionsFragment;
-import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
-import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
-import info.nightscout.androidaps.plugins.Food.FoodPlugin;
-import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
-import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
-import info.nightscout.androidaps.plugins.Insulin.InsulinOrefUltraRapidActingPlugin;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Maintenance.MaintenancePlugin;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.NSClientInternal.receivers.AckAlarmReceiver;
-import info.nightscout.androidaps.plugins.NSClientInternal.receivers.DBAccessReceiver;
-import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
-import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.Persistentnotification.PersistentNotificationPlugin;
-import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin;
-import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
-import info.nightscout.androidaps.plugins.ProfileSimple.SimpleProfilePlugin;
-import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
-import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
-import info.nightscout.androidaps.plugins.PumpMDI.MDIPlugin;
-import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin;
-import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
-import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
-import info.nightscout.androidaps.plugins.Source.SourceGlimpPlugin;
-import info.nightscout.androidaps.plugins.Source.SourceMM640gPlugin;
-import info.nightscout.androidaps.plugins.Source.SourceNSClientPlugin;
-import info.nightscout.androidaps.plugins.Source.SourcePoctechPlugin;
-import info.nightscout.androidaps.plugins.Source.SourceXdripPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.plugins.Wear.WearPlugin;
-import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.constraints.dstHelper.DstHelperPlugin;
+import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
+import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
+import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin;
+import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintPlugin;
+import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin;
+import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin;
+import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
+import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
+import info.nightscout.androidaps.plugins.general.food.FoodPlugin;
+import info.nightscout.androidaps.plugins.general.maintenance.LoggerUtils;
+import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin;
+import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
+import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.plugins.general.nsclient.receivers.AckAlarmReceiver;
+import info.nightscout.androidaps.plugins.general.nsclient.receivers.DBAccessReceiver;
+import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
+import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
+import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
+import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
+import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
+import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
+import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin;
+import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
+import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
+import info.nightscout.androidaps.plugins.profile.simple.SimpleProfilePlugin;
+import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
+import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
+import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
+import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin;
+import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
+import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
+import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
+import info.nightscout.androidaps.plugins.source.SourceEversensePlugin;
+import info.nightscout.androidaps.plugins.source.SourceGlimpPlugin;
+import info.nightscout.androidaps.plugins.source.SourceMM640gPlugin;
+import info.nightscout.androidaps.plugins.source.SourceNSClientPlugin;
+import info.nightscout.androidaps.plugins.source.SourcePoctechPlugin;
+import info.nightscout.androidaps.plugins.source.SourceTomatoPlugin;
+import info.nightscout.androidaps.plugins.source.SourceXdripPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.receivers.DataReceiver;
import info.nightscout.androidaps.receivers.KeepAliveReceiver;
import info.nightscout.androidaps.receivers.NSAlarmReceiver;
+import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver;
import info.nightscout.androidaps.services.Intents;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.androidaps.plugins.Maintenance.LoggerUtils;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.LocaleHelper;
import io.fabric.sdk.android.Fabric;
+import static info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion;
+
public class MainApp extends Application {
private static Logger log = LoggerFactory.getLogger(L.CORE);
private static KeepAliveReceiver keepAliveReceiver;
- private static Bus sBus;
private static MainApp sInstance;
public static Resources sResources;
+ private static FirebaseAnalytics mFirebaseAnalytics;
+
private static DatabaseHelper sDatabaseHelper = null;
private static ConstraintChecker sConstraintsChecker = null;
@@ -102,6 +113,8 @@ public class MainApp extends Application {
private static AckAlarmReceiver ackAlarmReciever = new AckAlarmReceiver();
private static DBAccessReceiver dbAccessReciever = new DBAccessReceiver();
private LocalBroadcastManager lbm;
+ BroadcastReceiver btReceiver;
+ TimeDateOrTZChangeReceiver timeDateOrTZChangeReceiver;
public static boolean devBranch;
public static boolean engineeringMode;
@@ -112,40 +125,47 @@ public class MainApp extends Application {
log.debug("onCreate");
sInstance = this;
sResources = getResources();
- sConstraintsChecker = new ConstraintChecker(this);
+ LocaleHelper.INSTANCE.update(this);
+ sConstraintsChecker = new ConstraintChecker();
sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class);
+ Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> log.error("Uncaught exception crashing app", ex));
+
try {
if (FabricPrivacy.fabricEnabled()) {
Fabric.with(this, new Crashlytics());
- Fabric.with(this, new Answers());
- Crashlytics.setString("BUILDVERSION", BuildConfig.BUILDVERSION);
}
} catch (Exception e) {
log.error("Error with Fabric init! " + e);
}
+ mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
+ mFirebaseAnalytics.setAnalyticsCollectionEnabled(!Boolean.getBoolean("disableFirebase"));
+
JodaTimeAndroid.init(this);
log.info("Version: " + BuildConfig.VERSION_NAME);
log.info("BuildVersion: " + BuildConfig.BUILDVERSION);
+ log.info("Remote: " + BuildConfig.REMOTE);
String extFilesDir = LoggerUtils.getLogDirectory();
File engineeringModeSemaphore = new File(extFilesDir, "engineering_mode");
engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile();
- devBranch = BuildConfig.VERSION.contains("dev");
-
- sBus = L.isEnabled(L.EVENTS) && devBranch ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY);
+ devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*");
registerLocalBroadcastReceiver();
+ //trigger here to see the new version on app start after an update
+ triggerCheckVersion();
+ //setBTReceiver();
+
if (pluginsList == null) {
pluginsList = new ArrayList<>();
// Register all tabs in app here
- pluginsList.add(OverviewPlugin.getPlugin());
+ pluginsList.add(OverviewPlugin.INSTANCE);
pluginsList.add(IobCobCalculatorPlugin.getPlugin());
- if (Config.ACTION) pluginsList.add(ActionsFragment.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE);
pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin());
pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin());
@@ -157,39 +177,49 @@ public class MainApp extends Application {
if (Config.PUMPDRIVERS) pluginsList.add(DanaRKoreanPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin());
- pluginsList.add(CareportalPlugin.getPlugin());
- if (Config.PUMPDRIVERS && engineeringMode)
- pluginsList.add(InsightPlugin.getPlugin()); // <-- Enable Insight plugin here
+ if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin());
if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin());
- if (Config.MDI) pluginsList.add(MDIPlugin.getPlugin());
+ if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin());
+ pluginsList.add(CareportalPlugin.getPlugin());
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin());
pluginsList.add(NSProfilePlugin.getPlugin());
- if (Config.OTHERPROFILES) pluginsList.add(SimpleProfilePlugin.getPlugin());
- if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(SimpleProfilePlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.getPlugin());
pluginsList.add(TreatmentsPlugin.getPlugin());
- if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
- if (Config.APS) pluginsList.add(ObjectivesPlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(SafetyPlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(VersionCheckerPlugin.INSTANCE);
+ if (Config.APS) pluginsList.add(StorageConstraintPlugin.getPlugin());
+ if (Config.APS) pluginsList.add(SignatureVerifierPlugin.getPlugin());
+ if (Config.APS) pluginsList.add(ObjectivesPlugin.INSTANCE);
pluginsList.add(SourceXdripPlugin.getPlugin());
pluginsList.add(SourceNSClientPlugin.getPlugin());
pluginsList.add(SourceMM640gPlugin.getPlugin());
pluginsList.add(SourceGlimpPlugin.getPlugin());
- pluginsList.add(SourceDexcomG5Plugin.getPlugin());
+ pluginsList.add(SourceDexcomPlugin.INSTANCE);
pluginsList.add(SourcePoctechPlugin.getPlugin());
- if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
+ pluginsList.add(SourceTomatoPlugin.getPlugin());
+ pluginsList.add(SourceEversensePlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(SmsCommunicatorPlugin.getPlugin());
pluginsList.add(FoodPlugin.getPlugin());
pluginsList.add(WearPlugin.initPlugin(this));
pluginsList.add(StatuslinePlugin.initPlugin(this));
pluginsList.add(PersistentNotificationPlugin.getPlugin());
pluginsList.add(NSClientPlugin.getPlugin());
+// if (engineeringMode) pluginsList.add(TidepoolPlugin.INSTANCE);
pluginsList.add(MaintenancePlugin.initPlugin(this));
+ pluginsList.add(AutomationPlugin.INSTANCE);
pluginsList.add(ConfigBuilderPlugin.getPlugin());
+ pluginsList.add(DstHelperPlugin.getPlugin());
+
+
ConfigBuilderPlugin.getPlugin().initialize();
}
@@ -231,6 +261,10 @@ public class MainApp extends Application {
//register dbaccess
lbm.registerReceiver(dbAccessReciever, new IntentFilter(Intents.ACTION_DATABASE));
+
+ this.timeDateOrTZChangeReceiver = new TimeDateOrTZChangeReceiver();
+ this.timeDateOrTZChangeReceiver.registerBroadcasts(this);
+
}
private void startKeepAliveService() {
@@ -245,26 +279,6 @@ public class MainApp extends Application {
KeepAliveReceiver.cancelAlarm(this);
}
- public static void subscribe(Object subscriber) {
- try {
- bus().register(subscriber);
- } catch (IllegalArgumentException e) {
- // already registered
- }
- }
-
- public static void unsubscribe(Object subscriber) {
- try {
- bus().unregister(subscriber);
- } catch (IllegalArgumentException e) {
- // already unregistered
- }
- }
-
- public static Bus bus() {
- return sBus;
- }
-
public static String gs(int id) {
return sResources.getString(id);
}
@@ -296,6 +310,10 @@ public class MainApp extends Application {
}
}
+ public static FirebaseAnalytics getFirebaseAnalytics() {
+ return mFirebaseAnalytics;
+ }
+
public static ConstraintChecker getConstraintChecker() {
return sConstraintsChecker;
}
@@ -362,19 +380,6 @@ public class MainApp extends Application {
return newList;
}
- @Nullable
- public static T getSpecificPlugin(Class pluginClass) {
- if (pluginsList != null) {
- for (PluginBase p : pluginsList) {
- if (pluginClass.isAssignableFrom(p.getClass()))
- return (T) p;
- }
- } else {
- log.error("pluginsList=null");
- }
- return null;
- }
-
public static boolean isEngineeringModeOrRelease() {
if (!Config.APS)
return true;
@@ -385,6 +390,24 @@ public class MainApp extends Application {
return devBranch;
}
+ public static int getIcon() {
+ if (Config.NSCLIENT)
+ return R.mipmap.ic_yellowowl;
+ else if (Config.PUMPCONTROL)
+ return R.mipmap.ic_pumpcontrol;
+ else
+ return R.mipmap.ic_launcher;
+ }
+
+ public static int getNotificationIcon() {
+ if (Config.NSCLIENT)
+ return R.drawable.ic_notif_nsclient;
+ else if (Config.PUMPCONTROL)
+ return R.drawable.ic_notif_pumpcontrol;
+ else
+ return R.drawable.ic_notif_aaps;
+ }
+
@Override
public void onTerminate() {
if (L.isEnabled(L.CORE))
@@ -394,5 +417,19 @@ public class MainApp extends Application {
sDatabaseHelper.close();
sDatabaseHelper = null;
}
+
+ if (btReceiver != null) {
+ unregisterReceiver(btReceiver);
+ }
+
+ if (timeDateOrTZChangeReceiver != null) {
+ unregisterReceiver(timeDateOrTZChangeReceiver);
+ }
+
+ }
+
+ public static int dpToPx(int dp) {
+ float scale = sResources.getDisplayMetrics().density;
+ return (int) (dp * scale + 0.5f);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java
index 582b10d57d..d3792bbad5 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/AgreementActivity.java
@@ -2,24 +2,22 @@ package info.nightscout.androidaps.activities;
import android.app.Activity;
import android.content.Intent;
-import android.content.SharedPreferences;
import android.os.Bundle;
-import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.R;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.utils.SP;
-public class AgreementActivity extends Activity {
+public class AgreementActivity extends NoSplashActivity {
boolean IUnderstand;
CheckBox agreeCheckBox;
Button saveButton;
@Override
- protected void onCreate(Bundle savedInstanceState) {
+ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agreement);
IUnderstand = SP.getBoolean(R.string.key_i_understand, false);
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java
index 7303eb9d97..79f3fbf4d4 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java
@@ -2,9 +2,6 @@ package info.nightscout.androidaps.activities;
import android.os.Bundle;
import android.os.SystemClock;
-import android.support.v4.content.res.ResourcesCompat;
-import android.support.v7.app.AppCompatActivity;
-import android.support.v7.widget.PopupMenu;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.Menu;
@@ -15,8 +12,10 @@ import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
+import androidx.appcompat.widget.PopupMenu;
+import androidx.core.content.res.ResourcesCompat;
+
import com.jjoe64.graphview.GraphView;
-import com.squareup.otto.Subscribe;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import org.slf4j.Logger;
@@ -25,49 +24,43 @@ import org.slf4j.LoggerFactory;
import java.util.Calendar;
import java.util.Date;
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import butterknife.OnLongClick;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventCustomCalculationFinished;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
-import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventIobCalculationProgress;
-import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
-import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.Overview.graphData.GraphData;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.T;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
+import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
+import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.utils.T;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class HistoryBrowseActivity extends AppCompatActivity {
+public class HistoryBrowseActivity extends NoSplashActivity {
private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class);
-
+ private CompositeDisposable disposable = new CompositeDisposable();
ImageButton chartButton;
boolean showBasal = true;
- boolean showIob, showCob, showDev, showRat, showDevslope;
+ boolean showIob, showCob, showDev, showRat, showActPrim, showActSec, showDevslope;
- @BindView(R.id.historybrowse_date)
Button buttonDate;
- @BindView(R.id.historybrowse_zoom)
Button buttonZoom;
- @BindView(R.id.historyybrowse_bggraph)
GraphView bgGraph;
- @BindView(R.id.historybrowse_iobgraph)
GraphView iobGraph;
- @BindView(R.id.historybrowse_seekBar)
SeekBar seekBar;
- @BindView(R.id.historybrowse_noprofile)
TextView noProfile;
- @BindView(R.id.overview_iobcalculationprogess)
TextView iobCalculationProgressView;
private int rangeToDisplay = 24; // for graph
@@ -82,11 +75,83 @@ public class HistoryBrowseActivity extends AppCompatActivity {
}
@Override
- protected void onCreate(Bundle savedInstanceState) {
+ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historybrowse);
- ButterKnife.bind(this);
+ buttonDate = findViewById(R.id.historybrowse_date);
+ buttonZoom = findViewById(R.id.historybrowse_zoom);
+ bgGraph = findViewById(R.id.historyybrowse_bggraph);
+ iobGraph = findViewById(R.id.historybrowse_iobgraph);
+ seekBar = findViewById(R.id.historybrowse_seekBar);
+ noProfile = findViewById(R.id.historybrowse_noprofile);
+ iobCalculationProgressView = findViewById(R.id.overview_iobcalculationprogess);
+
+ findViewById(R.id.historybrowse_left).setOnClickListener(v -> {
+ start -= T.hours(rangeToDisplay).msecs();
+ updateGUI("onClickLeft");
+ runCalculation("onClickLeft");
+ });
+
+ findViewById(R.id.historybrowse_right).setOnClickListener(v -> {
+ start += T.hours(rangeToDisplay).msecs();
+ updateGUI("onClickRight");
+ runCalculation("onClickRight");
+ });
+
+ findViewById(R.id.historybrowse_end).setOnClickListener(v -> {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTimeInMillis(System.currentTimeMillis());
+ calendar.set(Calendar.MILLISECOND, 0);
+ calendar.set(Calendar.SECOND, 0);
+ calendar.set(Calendar.MINUTE, 0);
+ calendar.set(Calendar.HOUR_OF_DAY, 0);
+ start = calendar.getTimeInMillis();
+ updateGUI("onClickEnd");
+ runCalculation("onClickEnd");
+ });
+
+ findViewById(R.id.historybrowse_zoom).setOnClickListener(v -> {
+ rangeToDisplay += 6;
+ rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
+ updateGUI("rangeChange");
+ });
+
+ findViewById(R.id.historybrowse_zoom).setOnLongClickListener(v -> {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTimeInMillis(start);
+ calendar.set(Calendar.MILLISECOND, 0);
+ calendar.set(Calendar.SECOND, 0);
+ calendar.set(Calendar.MINUTE, 0);
+ calendar.set(Calendar.HOUR_OF_DAY, 0);
+ start = calendar.getTimeInMillis();
+ updateGUI("resetToMidnight");
+ runCalculation("onLongClickZoom");
+ return true;
+ });
+
+ findViewById(R.id.historybrowse_date).setOnClickListener(v -> {
+ Calendar calendar = Calendar.getInstance();
+ calendar.setTime(new Date(start));
+ DatePickerDialog dpd = DatePickerDialog.newInstance(
+ (view, year, monthOfYear, dayOfMonth) -> {
+ Date date = new Date(0);
+ date.setYear(year - 1900);
+ date.setMonth(monthOfYear);
+ date.setDate(dayOfMonth);
+ date.setHours(0);
+ start = date.getTime();
+ updateGUI("onClickDate");
+ runCalculation("onClickDate");
+ },
+ calendar.get(Calendar.YEAR),
+ calendar.get(Calendar.MONTH),
+ calendar.get(Calendar.DAY_OF_MONTH)
+ );
+ dpd.setThemeDark(true);
+ dpd.dismissOnPause(true);
+ dpd.show(getFragmentManager(), "Datepickerdialog");
+ });
bgGraph.getGridLabelRenderer().setGridColor(MainApp.gc(R.color.graphgrid));
bgGraph.getGridLabelRenderer().reloadStyles();
@@ -103,14 +168,33 @@ public class HistoryBrowseActivity extends AppCompatActivity {
@Override
public void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
+ disposable.clear();
iobCobCalculatorPlugin.stopCalculation("onPause");
}
@Override
public void onResume() {
super.onResume();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (event.getCause() == eventCustomCalculationFinished) {
+ log.debug("EventAutosensCalculationFinished");
+ synchronized (HistoryBrowseActivity.this) {
+ updateGUI("EventAutosensCalculationFinished");
+ }
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventIobCalculationProgress.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (iobCalculationProgressView != null)
+ iobCalculationProgressView.setText(event.getProgress());
+ }, FabricPrivacy::logException)
+ );
// set start of current day
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
@@ -124,78 +208,6 @@ public class HistoryBrowseActivity extends AppCompatActivity {
updateGUI("onResume");
}
- @OnClick(R.id.historybrowse_left)
- void onClickLeft() {
- start -= T.hours(rangeToDisplay).msecs();
- updateGUI("onClickLeft");
- runCalculation("onClickLeft");
- }
-
- @OnClick(R.id.historybrowse_right)
- void onClickRight() {
- start += T.hours(rangeToDisplay).msecs();
- updateGUI("onClickRight");
- runCalculation("onClickRight");
- }
-
- @OnClick(R.id.historybrowse_end)
- void onClickEnd() {
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(System.currentTimeMillis());
- calendar.set(Calendar.MILLISECOND, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- start = calendar.getTimeInMillis();
- updateGUI("onClickEnd");
- runCalculation("onClickEnd");
- }
-
- @OnClick(R.id.historybrowse_zoom)
- void onClickZoom() {
- rangeToDisplay += 6;
- rangeToDisplay = rangeToDisplay > 24 ? 6 : rangeToDisplay;
- updateGUI("rangeChange");
- }
-
- @OnLongClick(R.id.historybrowse_zoom)
- boolean onLongClickZoom() {
- Calendar calendar = Calendar.getInstance();
- calendar.setTimeInMillis(start);
- calendar.set(Calendar.MILLISECOND, 0);
- calendar.set(Calendar.SECOND, 0);
- calendar.set(Calendar.MINUTE, 0);
- calendar.set(Calendar.HOUR_OF_DAY, 0);
- start = calendar.getTimeInMillis();
- updateGUI("resetToMidnight");
- runCalculation("onLongClickZoom");
- return true;
- }
-
- @OnClick(R.id.historybrowse_date)
- void onClickDate() {
- Calendar calendar = Calendar.getInstance();
- calendar.setTime(new Date(start));
- DatePickerDialog dpd = DatePickerDialog.newInstance(
- (view, year, monthOfYear, dayOfMonth) -> {
- Date date = new Date(0);
- date.setYear(year - 1900);
- date.setMonth(monthOfYear);
- date.setDate(dayOfMonth);
- date.setHours(0);
- start = date.getTime();
- updateGUI("onClickDate");
- runCalculation("onClickDate");
- },
- calendar.get(Calendar.YEAR),
- calendar.get(Calendar.MONTH),
- calendar.get(Calendar.DAY_OF_MONTH)
- );
- dpd.setThemeDark(true);
- dpd.dismissOnPause(true);
- dpd.show(getFragmentManager(), "Datepickerdialog");
- }
-
private void runCalculation(String from) {
long end = start + T.hours(rangeToDisplay).msecs();
iobCobCalculatorPlugin.stopCalculation(from);
@@ -203,26 +215,6 @@ public class HistoryBrowseActivity extends AppCompatActivity {
iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished);
}
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished e) {
- if (e.cause == eventCustomCalculationFinished) {
- log.debug("EventAutosensCalculationFinished");
- runOnUiThread(() -> {
- synchronized (HistoryBrowseActivity.this) {
- updateGUI("EventAutosensCalculationFinished");
- }
- });
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventIobCalculationProgress e) {
- runOnUiThread(() -> {
- if (iobCalculationProgressView != null)
- iobCalculationProgressView.setText(e.progress);
- });
- }
-
void updateGUI(String from) {
log.debug("updateGUI from: " + from);
@@ -240,14 +232,23 @@ public class HistoryBrowseActivity extends AppCompatActivity {
}
final String units = profile.getUnits();
- final double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
- final double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
+ final double lowLine = OverviewPlugin.INSTANCE.determineLowLine(units);
+ final double highLine = OverviewPlugin.INSTANCE.determineHighLine(units);
buttonDate.setText(DateUtil.dateAndTimeString(start));
buttonZoom.setText(String.valueOf(rangeToDisplay));
final boolean showPrediction = false;
+ showBasal = SP.getBoolean("hist_showbasals", true);
+ showIob = SP.getBoolean("hist_showiob", true);
+ showCob = SP.getBoolean("hist_showcob", true);
+ showDev = SP.getBoolean("hist_showdeviations", false);
+ showRat = SP.getBoolean("hist_showratios", false);
+ showActPrim = SP.getBoolean("hist_showactivityprimary", false);
+ showActSec = SP.getBoolean("hist_showactivitysecondary", false);
+ showDevslope = SP.getBoolean("hist_showdevslope", false);
+
int hoursToFetch;
final long toTime;
final long fromTime;
@@ -285,6 +286,10 @@ public class HistoryBrowseActivity extends AppCompatActivity {
// set manual x bounds to have nice steps
graphData.formatAxis(fromTime, toTime);
+ if (showActPrim) {
+ graphData.addActivity(fromTime, toTime, false, 1d);
+ }
+
// Treatments
graphData.addTreatments(fromTime, toTime);
@@ -305,6 +310,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
boolean useCobForScale = false;
boolean useDevForScale = false;
boolean useRatioForScale = false;
+ boolean useIAForScale = false;
boolean useDSForScale = false;
if (showIob) {
@@ -315,18 +321,22 @@ public class HistoryBrowseActivity extends AppCompatActivity {
useDevForScale = true;
} else if (showRat) {
useRatioForScale = true;
+ } else if (showActSec) {
+ useIAForScale = true;
} else if (showDevslope) {
useDSForScale = true;
}
if (showIob)
- secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d);
+ secondGraphData.addIob(fromTime, toTime, useIobForScale, 1d, showPrediction);
if (showCob)
secondGraphData.addCob(fromTime, toTime, useCobForScale, useCobForScale ? 1d : 0.5d);
if (showDev)
secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1d);
if (showRat)
secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1d);
+ if (showActSec)
+ secondGraphData.addActivity(fromTime, toTime, useIAForScale, useIAForScale ? 2d : 1d);
if (showDevslope)
secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1d);
@@ -337,14 +347,14 @@ public class HistoryBrowseActivity extends AppCompatActivity {
// do GUI update
runOnUiThread(() -> {
- if (showIob || showCob || showDev || showRat || showDevslope) {
+ if (showIob || showCob || showDev || showRat || showActSec || showDevslope) {
iobGraph.setVisibility(View.VISIBLE);
} else {
iobGraph.setVisibility(View.GONE);
}
// finally enforce drawing of graphs
graphData.performUpdate();
- if (showIob || showCob || showDev || showRat || showDevslope)
+ if (showIob || showCob || showDev || showRat || showActSec || showDevslope)
secondGraphData.performUpdate();
});
}).start();
@@ -353,22 +363,37 @@ public class HistoryBrowseActivity extends AppCompatActivity {
private void setupChartMenu() {
chartButton = (ImageButton) findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(v -> {
- MenuItem item;
+ MenuItem item, dividerItem;
CharSequence title;
+ int titleMaxChars = 0;
SpannableString s;
PopupMenu popup = new PopupMenu(v.getContext(), v);
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.BAS.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_basals));
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.basal, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showBasal);
+ item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.ACTPRIM.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_activity));
+ title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
+ s = new SpannableString(title);
+ s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.activity, null)), 0, s.length(), 0);
+ item.setTitle(s);
+ item.setCheckable(true);
+ item.setChecked(showActPrim);
+
+ dividerItem = popup.getMenu().add("");
+ dividerItem.setEnabled(false);
+
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.IOB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_iob));
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.iob, null)), 0, s.length(), 0);
item.setTitle(s);
@@ -377,6 +402,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.COB.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_cob));
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.cob, null)), 0, s.length(), 0);
item.setTitle(s);
@@ -385,6 +411,7 @@ public class HistoryBrowseActivity extends AppCompatActivity {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEV.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_deviations));
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.deviations, null)), 0, s.length(), 0);
item.setTitle(s);
@@ -393,15 +420,27 @@ public class HistoryBrowseActivity extends AppCompatActivity {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.SEN.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_sensitivity));
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.ratio, null)), 0, s.length(), 0);
item.setTitle(s);
item.setCheckable(true);
item.setChecked(showRat);
+ item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.ACTSEC.ordinal(), Menu.NONE, MainApp.gs(R.string.overview_show_activity));
+ title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
+ s = new SpannableString(title);
+ s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.activity, null)), 0, s.length(), 0);
+ item.setTitle(s);
+ item.setCheckable(true);
+ item.setChecked(showActSec);
+
+
if (MainApp.devBranch) {
item = popup.getMenu().add(Menu.NONE, OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal(), Menu.NONE, "Deviation slope");
title = item.getTitle();
+ if (titleMaxChars < title.length()) titleMaxChars = title.length();
s = new SpannableString(title);
s.setSpan(new ForegroundColorSpan(ResourcesCompat.getColor(getResources(), R.color.devslopepos, null)), 0, s.length(), 0);
item.setTitle(s);
@@ -409,19 +448,27 @@ public class HistoryBrowseActivity extends AppCompatActivity {
item.setChecked(showDevslope);
}
+ // Fairly good guestimate for required divider text size...
+ title = new String(new char[titleMaxChars + 10]).replace("\0", "_");
+ dividerItem.setTitle(title);
+
popup.setOnMenuItemClickListener(item1 -> {
if (item1.getItemId() == OverviewFragment.CHARTTYPE.BAS.ordinal()) {
- showBasal = !item1.isChecked();
+ SP.putBoolean("hist_showbasals", !item1.isChecked());
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.IOB.ordinal()) {
- showIob = !item1.isChecked();
+ SP.putBoolean("hist_showiob", !item1.isChecked());
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.COB.ordinal()) {
- showCob = !item1.isChecked();
+ SP.putBoolean("hist_showcob", !item1.isChecked());
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEV.ordinal()) {
- showDev = !item1.isChecked();
+ SP.putBoolean("hist_showdeviations", !item1.isChecked());
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.SEN.ordinal()) {
- showRat = !item1.isChecked();
+ SP.putBoolean("hist_showratios", !item1.isChecked());
+ } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.ACTPRIM.ordinal()) {
+ SP.putBoolean("hist_showactivityprimary", !item1.isChecked());
+ } else if (item1.getItemId() == OverviewFragment.CHARTTYPE.ACTSEC.ordinal()) {
+ SP.putBoolean("hist_showactivitysecondary", !item1.isChecked());
} else if (item1.getItemId() == OverviewFragment.CHARTTYPE.DEVSLOPE.ordinal()) {
- showDevslope = !item1.isChecked();
+ SP.putBoolean("hist_showdevslope", !item1.isChecked());
}
updateGUI("onGraphCheckboxesCheckedChanged");
return true;
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashActivity.kt
new file mode 100644
index 0000000000..0b7af2bd1d
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashActivity.kt
@@ -0,0 +1,13 @@
+package info.nightscout.androidaps.activities
+
+import android.app.Activity
+import android.os.Bundle
+
+import info.nightscout.androidaps.R
+
+open class NoSplashActivity : Activity() {
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ setTheme(R.style.AppTheme_NoActionBar)
+ super.onCreate(savedInstanceState)
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt
new file mode 100644
index 0000000000..e4c8027cd5
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/activities/NoSplashAppCompatActivity.kt
@@ -0,0 +1,12 @@
+package info.nightscout.androidaps.activities
+
+import android.os.Bundle
+import androidx.appcompat.app.AppCompatActivity
+import info.nightscout.androidaps.R
+
+open class NoSplashAppCompatActivity : AppCompatActivity() {
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ setTheme(R.style.AppTheme_NoActionBar)
+ super.onCreate(savedInstanceState)
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java
index 10a9487da0..367429dbbf 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java
@@ -9,47 +9,54 @@ import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
+import android.preference.PreferenceScreen;
import android.text.TextUtils;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.plugins.Careportal.CareportalPlugin;
-import info.nightscout.androidaps.plugins.ConstraintsSafety.SafetyPlugin;
-import info.nightscout.androidaps.plugins.Insulin.InsulinOrefFreePeakPlugin;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSClientPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSAMA.OpenAPSAMAPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSMA.OpenAPSMAPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSSMB.OpenAPSSMBPlugin;
-import info.nightscout.androidaps.plugins.PumpCombo.ComboPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
-import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
-import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityAAPSPlugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref1Plugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityWeightedAveragePlugin;
-import info.nightscout.androidaps.plugins.SmsCommunicator.SmsCommunicatorPlugin;
-import info.nightscout.androidaps.plugins.Source.SourceDexcomG5Plugin;
-import info.nightscout.androidaps.plugins.Wear.WearPlugin;
-import info.nightscout.androidaps.plugins.XDripStatusline.StatuslinePlugin;
-import info.nightscout.utils.LocaleHelper;
-import info.nightscout.utils.OKDialog;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
+import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
+import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin;
+import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader;
+import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
+import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
+import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
+import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
+import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
+import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
+import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin;
+import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
+import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
+import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
+import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
+import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
+import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
+import info.nightscout.androidaps.utils.LocaleHelper;
+import info.nightscout.androidaps.utils.OKDialog;
+import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
MyPreferenceFragment myPreferenceFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
+ setTheme(R.style.AppTheme_NoActionBar);
super.onCreate(savedInstanceState);
myPreferenceFragment = new MyPreferenceFragment();
Bundle args = new Bundle();
@@ -61,16 +68,14 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
- MainApp.bus().post(new EventPreferenceChange(key));
+ RxBus.INSTANCE.send(new EventPreferenceChange(key));
if (key.equals("language")) {
- String lang = sharedPreferences.getString("language", "en");
- LocaleHelper.setLocale(getApplicationContext(), lang);
- MainApp.bus().post(new EventRefreshGui(true));
+ RxBus.INSTANCE.send(new EventRebuildTabs(true));
//recreate() does not update language so better close settings
finish();
}
if (key.equals("short_tabtitles")) {
- MainApp.bus().post(new EventRefreshGui());
+ RxBus.INSTANCE.send(new EventRebuildTabs());
}
if (key.equals(MainApp.gs(R.string.key_openapsama_useautosens)) && SP.getBoolean(R.string.key_openapsama_useautosens, false)) {
OKDialog.show(this, MainApp.gs(R.string.configbuilder_sensitivity), MainApp.gs(R.string.sensitivity_warning), null);
@@ -92,7 +97,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
} else if (editTextPref.getText() != null) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
- } else if (pref.getKey().contains("smscommunicator_allowednumbers") && TextUtils.isEmpty(editTextPref.getText().trim())) {
+ } else if (pref.getKey().contains("smscommunicator_allowednumbers") && (editTextPref.getText() == null || TextUtils.isEmpty(editTextPref.getText().trim()))) {
pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary));
}
}
@@ -143,7 +148,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResource(R.xml.pref_overview);
- addPreferencesFromResourceIfEnabled(SourceDexcomG5Plugin.getPlugin(), PluginType.BGSOURCE);
+ addPreferencesFromResourceIfEnabled(SourceDexcomPlugin.INSTANCE, PluginType.BGSOURCE);
addPreferencesFromResourceIfEnabled(CareportalPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(SafetyPlugin.getPlugin(), PluginType.CONSTRAINTS);
if (Config.APS) {
@@ -163,8 +168,9 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(DanaRKoreanPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRv2Plugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(DanaRSPlugin.getPlugin(), PluginType.PUMP);
- addPreferencesFromResourceIfEnabled(InsightPlugin.getPlugin(), PluginType.PUMP);
+ addPreferencesFromResourceIfEnabled(LocalInsightPlugin.getPlugin(), PluginType.PUMP);
addPreferencesFromResourceIfEnabled(ComboPlugin.getPlugin(), PluginType.PUMP);
+ addPreferencesFromResourceIfEnabled(MedtronicPumpPlugin.getPlugin(), PluginType.PUMP);
if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)
|| DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)
@@ -181,7 +187,9 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(InsulinOrefFreePeakPlugin.getPlugin(), PluginType.INSULIN);
addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL);
+ addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.getPlugin(), PluginType.GENERAL);
+ addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResource(R.xml.pref_others);
addPreferencesFromResource(R.xml.pref_datachoices);
@@ -190,7 +198,26 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL);
}
+ if (Config.NSCLIENT) {
+ PreferenceScreen scrnAdvancedSettings = (PreferenceScreen) findPreference(getString(R.string.key_advancedsettings));
+ if (scrnAdvancedSettings != null) {
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_warning)));
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_critical)));
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights)));
+ scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights_extended)));
+ }
+ }
+
initSummary(getPreferenceScreen());
+
+ final Preference tidepoolTestLogin = findPreference(MainApp.gs(R.string.key_tidepool_test_login));
+ if (tidepoolTestLogin != null)
+ tidepoolTestLogin.setOnPreferenceClickListener(preference -> {
+ TidepoolUploader.INSTANCE.testLogin(getActivity());
+ return false;
+ });
}
@Override
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt
new file mode 100644
index 0000000000..96a399a299
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/activities/RequestDexcomPermissionActivity.kt
@@ -0,0 +1,19 @@
+package info.nightscout.androidaps.activities
+
+import android.os.Bundle
+import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin
+
+class RequestDexcomPermissionActivity : NoSplashAppCompatActivity() {
+
+ private val requestCode = "AndroidAPS <3".map { it.toInt() }.sum()
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ requestPermissions(arrayOf(SourceDexcomPlugin.PERMISSION), requestCode)
+ }
+
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
+ finish()
+ }
+
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java
index 04fd7a6be7..688ba82c6a 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.java
@@ -2,24 +2,24 @@ package info.nightscout.androidaps.activities;
import android.content.Intent;
import android.os.Bundle;
-import android.support.annotation.Nullable;
-import android.support.v4.app.Fragment;
-import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
+import androidx.annotation.Nullable;
+import androidx.appcompat.app.AppCompatActivity;
+import androidx.fragment.app.Fragment;
+
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.activities.PreferencesActivity;
import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.utils.PasswordProtection;
+import info.nightscout.androidaps.utils.PasswordProtection;
public class SingleFragmentActivity extends AppCompatActivity {
private PluginBase plugin;
@Override
- protected void onCreate(@Nullable Bundle savedInstanceState) {
+ public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_fragment);
diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java
index b46faec980..24cdceada6 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java
@@ -1,10 +1,8 @@
package info.nightscout.androidaps.activities;
-import android.app.Activity;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
-import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MotionEvent;
@@ -18,7 +16,7 @@ import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.recyclerview.widget.LinearLayoutManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -39,21 +37,26 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRSyncStatus;
-import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRS.DanaRSPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaRv2.DanaRv2Plugin;
-import info.nightscout.androidaps.plugins.PumpInsight.InsightPlugin;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
+import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus;
+import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
+import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
+import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin;
import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.utils.SafeParse;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class TDDStatsActivity extends Activity {
+public class TDDStatsActivity extends NoSplashActivity {
private static Logger log = LoggerFactory.getLogger(TDDStatsActivity.class);
+ private CompositeDisposable disposable = new CompositeDisposable();
TextView statusView, statsMessage, totalBaseBasal2;
EditText totalBaseBasal;
@@ -74,13 +77,25 @@ public class TDDStatsActivity extends Activity {
@Override
protected void onResume() {
super.onResume();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPumpStatusChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventDanaRSyncStatus.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ log.debug("EventDanaRSyncStatus: " + event.getMessage());
+ statusView.setText(event.getMessage());
+ }, FabricPrivacy::logException)
+ );
}
@Override
protected void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
+ disposable.clear();
}
@Override
@@ -99,7 +114,7 @@ public class TDDStatsActivity extends Activity {
}
@Override
- protected void onCreate(Bundle savedInstanceState) {
+ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.danar_statsactivity);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
@@ -239,7 +254,7 @@ public class TDDStatsActivity extends Activity {
statsMessage.setText(MainApp.gs(R.string.danar_stats_warning_Message));
}
});
- ConfigBuilderPlugin.getPlugin().getCommandQueue().loadTDDs( new Callback() {
+ ConfigBuilderPlugin.getPlugin().getCommandQueue().loadTDDs(new Callback() {
@Override
public void run() {
loadDataFromDB();
@@ -399,7 +414,7 @@ public class TDDStatsActivity extends Activity {
//cumulative TDDs
for (TDD record : historyList) {
- if(!historyList.isEmpty() && df.format(new Date(record.date)).equals(df.format(new Date()))) {
+ if (!historyList.isEmpty() && df.format(new Date(record.date)).equals(df.format(new Date()))) {
//Today should not be included
continue;
}
@@ -448,7 +463,7 @@ public class TDDStatsActivity extends Activity {
tl.setBackgroundColor(Color.TRANSPARENT);
}
- if(!historyList.isEmpty() && df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))) {
+ if (!historyList.isEmpty() && df.format(new Date(historyList.get(0).date)).equals(df.format(new Date()))) {
//Today should not be included
historyList.remove(0);
}
@@ -519,42 +534,17 @@ public class TDDStatsActivity extends Activity {
}
}
- @Subscribe
- public void onStatusEvent(final EventDanaRSyncStatus s) {
- log.debug("EventDanaRSyncStatus: " + s.message);
- runOnUiThread(
- new Runnable() {
- @Override
- public void run() {
- statusView.setText(s.message);
- }
- });
- }
-
- @Subscribe
- public void onStatusEvent(final EventPumpStatusChanged c) {
- runOnUiThread(
- new Runnable() {
- @Override
- public void run() {
- statusView.setText(c.textStatus());
- }
- }
- );
- }
-
-
public static boolean isOldData(List historyList) {
Object activePump = ConfigBuilderPlugin.getPlugin().getActivePump();
- PumpInterface dana = MainApp.getSpecificPlugin(DanaRPlugin.class);
- PumpInterface danaRS = MainApp.getSpecificPlugin(DanaRSPlugin.class);
- PumpInterface danaV2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class);
- PumpInterface danaKorean = MainApp.getSpecificPlugin(DanaRKoreanPlugin.class);
- PumpInterface insight = MainApp.getSpecificPlugin(InsightPlugin.class);
+ PumpInterface dana = DanaRPlugin.getPlugin();
+ PumpInterface danaRS = DanaRSPlugin.getPlugin();
+ PumpInterface danaV2 = DanaRv2Plugin.getPlugin();
+ PumpInterface danaKorean = DanaRKoreanPlugin.getPlugin();
+ PumpInterface insight = LocalInsightPlugin.getPlugin();
boolean startsYesterday = activePump == dana || activePump == danaRS || activePump == danaV2 || activePump == danaKorean || activePump == insight;
DateFormat df = new SimpleDateFormat("dd.MM.");
- return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday?1000 * 60 * 60 * 24:0))))));
+ return (historyList.size() < 3 || !(df.format(new Date(historyList.get(0).date)).equals(df.format(new Date(System.currentTimeMillis() - (startsYesterday ? 1000 * 60 * 60 * 24 : 0))))));
}
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java
index ceb85c6967..9d7a49493b 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/ConstraintChecker.java
@@ -1,5 +1,7 @@
package info.nightscout.androidaps.data;
+import androidx.annotation.NonNull;
+
import java.util.ArrayList;
import info.nightscout.androidaps.Constants;
@@ -15,13 +17,6 @@ import info.nightscout.androidaps.interfaces.PluginType;
public class ConstraintChecker implements ConstraintsInterface {
- private MainApp mainApp;
-
- public ConstraintChecker(MainApp mainApp) {
- this.mainApp = mainApp;
- }
-
-
public Constraint isLoopInvokationAllowed() {
return isLoopInvocationAllowed(new Constraint<>(true));
}
@@ -50,6 +45,10 @@ public class ConstraintChecker implements ConstraintsInterface {
return isAdvancedFilteringEnabled(new Constraint<>(true));
}
+ public Constraint isSuperBolusEnabled() {
+ return isSuperBolusEnabled(new Constraint<>(true));
+ }
+
public Constraint getMaxBasalAllowed(Profile profile) {
return applyBasalConstraints(new Constraint<>(Constants.REALLYHIGHBASALRATE), profile);
}
@@ -75,9 +74,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isLoopInvocationAllowed(Constraint value) {
+ public Constraint isLoopInvocationAllowed(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -87,9 +86,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isClosedLoopAllowed(Constraint value) {
+ public Constraint isClosedLoopAllowed(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -99,9 +98,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isAutosensModeEnabled(Constraint value) {
+ public Constraint isAutosensModeEnabled(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -111,9 +110,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isAMAModeEnabled(Constraint value) {
+ public Constraint isAMAModeEnabled(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -123,9 +122,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isSMBModeEnabled(Constraint value) {
+ public Constraint isSMBModeEnabled(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -135,9 +134,9 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isUAMEnabled(Constraint value) {
+ public Constraint isUAMEnabled(@NonNull Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -147,8 +146,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint isAdvancedFilteringEnabled(Constraint value) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint isAdvancedFilteringEnabled(@NonNull Constraint value) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -158,8 +157,19 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint isSuperBolusEnabled(@NonNull Constraint value) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ for (PluginBase p : constraintsPlugins) {
+ ConstraintsInterface constraint = (ConstraintsInterface) p;
+ if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
+ constraint.isSuperBolusEnabled(value);
+ }
+ return value;
+ }
+
+ @Override
+ public Constraint applyBasalConstraints(@NonNull Constraint absoluteRate, Profile profile) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constraint = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -169,8 +179,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint applyBasalPercentConstraints(@NonNull Constraint percentRate, Profile profile) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -180,8 +190,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyBolusConstraints(Constraint insulin) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint applyBolusConstraints(@NonNull Constraint insulin) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -191,8 +201,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyExtendedBolusConstraints(Constraint insulin) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint applyExtendedBolusConstraints(@NonNull Constraint insulin) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -202,8 +212,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyCarbsConstraints(Constraint carbs) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint applyCarbsConstraints(@NonNull Constraint carbs) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
@@ -213,8 +223,8 @@ public class ConstraintChecker implements ConstraintsInterface {
}
@Override
- public Constraint applyMaxIOBConstraints(Constraint maxIob) {
- ArrayList constraintsPlugins = mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
+ public Constraint applyMaxIOBConstraints(@NonNull Constraint maxIob) {
+ ArrayList constraintsPlugins = MainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class);
for (PluginBase p : constraintsPlugins) {
ConstraintsInterface constrain = (ConstraintsInterface) p;
if (!p.isEnabled(PluginType.CONSTRAINTS)) continue;
diff --git a/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java
index 51a1e18685..ef5cd69782 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/DetailedBolusInfo.java
@@ -2,15 +2,12 @@ package info.nightscout.androidaps.data;
import android.content.Context;
-import com.rits.cloning.Cloner;
-
import org.json.JSONObject;
import java.util.Date;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
/**
* Created by mike on 29.05.2017.
diff --git a/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java b/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java
deleted file mode 100644
index d8ee55b73a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/data/GlucoseStatus.java
+++ /dev/null
@@ -1,163 +0,0 @@
-package info.nightscout.androidaps.data;
-
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-import android.support.annotation.Nullable;
-import android.text.Html;
-import android.text.Spanned;
-
-import com.j256.ormlite.dao.Dao;
-import com.j256.ormlite.stmt.PreparedQuery;
-import com.j256.ormlite.stmt.QueryBuilder;
-
-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.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.Round;
-
-/**
- * Created by mike on 04.01.2017.
- */
-
-public class GlucoseStatus {
- private static Logger log = LoggerFactory.getLogger(GlucoseStatus.class);
- public double glucose = 0d;
- public double delta = 0d;
- public double avgdelta = 0d;
- public double short_avgdelta = 0d;
- public double long_avgdelta = 0d;
- public long date = 0L;
-
-
- @Override
- public String toString() {
- return MainApp.gs(R.string.glucose) + " " + DecimalFormatter.to0Decimal(glucose) + " mg/dl\n" +
- MainApp.gs(R.string.delta) + " " + DecimalFormatter.to0Decimal(delta) + " mg/dl\n" +
- MainApp.gs(R.string.short_avgdelta) + " " + DecimalFormatter.to2Decimal(short_avgdelta) + " mg/dl\n" +
- MainApp.gs(R.string.long_avgdelta) + " " + DecimalFormatter.to2Decimal(long_avgdelta) + " mg/dl";
- }
-
- public GlucoseStatus() {
- }
-
- public GlucoseStatus round() {
- this.glucose = Round.roundTo(this.glucose, 0.1);
- this.delta = Round.roundTo(this.delta, 0.01);
- this.avgdelta = Round.roundTo(this.avgdelta, 0.01);
- this.short_avgdelta = Round.roundTo(this.short_avgdelta, 0.01);
- this.long_avgdelta = Round.roundTo(this.long_avgdelta, 0.01);
- return this;
- }
-
-
-
- @Nullable
- public static GlucoseStatus getGlucoseStatusData(){
- return getGlucoseStatusData(false);
- }
-
- @Nullable
- public static GlucoseStatus getGlucoseStatusData(boolean allowOldData) {
- // load 45min
- long fromtime = DateUtil.now() - 60 * 1000L * 45;
- List data = MainApp.getDbHelper().getBgreadingsDataFromTime(fromtime, false);
-
- int sizeRecords = data.size();
- if (sizeRecords == 0) {
- return null;
- }
-
- if (data.get(0).date < DateUtil.now() - 7 * 60 * 1000L && !allowOldData) {
- return null;
- }
-
- BgReading now = data.get(0);
- long now_date = now.date;
- double change;
-
- if (sizeRecords == 1) {
- GlucoseStatus status = new GlucoseStatus();
- status.glucose = now.value;
- status.short_avgdelta = 0d;
- status.delta = 0d;
- status.long_avgdelta = 0d;
- status.avgdelta = 0d; // for OpenAPS MA
- status.date = now_date;
- return status.round();
- }
-
- ArrayList last_deltas = new ArrayList();
- ArrayList short_deltas = new ArrayList();
- ArrayList long_deltas = new ArrayList();
-
- for (int i = 1; i < data.size(); i++) {
- if (data.get(i).value > 38) {
- BgReading then = data.get(i);
- long then_date = then.date;
- double avgdelta = 0;
- long minutesago;
-
- minutesago = Math.round((now_date - then_date) / (1000d * 60));
- // multiply by 5 to get the same units as delta, i.e. mg/dL/5m
- change = now.value - then.value;
- avgdelta = change / minutesago * 5;
-
- // use the average of all data points in the last 2.5m for all further "now" calculations
- if (0 < minutesago && minutesago < 2.5) {
- now.value = (now.value + then.value) / 2;
- now_date = (now_date + then_date) / 2;
- // short_deltas are calculated from everything ~5-15 minutes ago
- } else if (2.5 < minutesago && minutesago < 17.5) {
- //console.error(minutesago, avgdelta);
- short_deltas.add(avgdelta);
- // last_deltas are calculated from everything ~5 minutes ago
- if (2.5 < minutesago && minutesago < 7.5) {
- last_deltas.add(avgdelta);
- }
- // long_deltas are calculated from everything ~20-40 minutes ago
- } else if (17.5 < minutesago && minutesago < 42.5) {
- long_deltas.add(avgdelta);
- }
- }
- }
-
- GlucoseStatus status = new GlucoseStatus();
- status.glucose = now.value;
- status.date = now_date;
-
- status.short_avgdelta = average(short_deltas);
-
- if (last_deltas.isEmpty()) {
- status.delta = status.short_avgdelta;
- } else {
- status.delta = average(last_deltas);
- }
-
- status.long_avgdelta = average(long_deltas);
- status.avgdelta = status.short_avgdelta; // for OpenAPS MA
-
- return status.round();
- }
-
- public static double average(ArrayList array) {
- double sum = 0d;
-
- if (array.size() == 0)
- return 0d;
-
- for (Double value : array) {
- sum += value;
- }
- return sum / array.size();
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/Intervals.java b/app/src/main/java/info/nightscout/androidaps/data/Intervals.java
index 66d567d9bd..efb3b76aea 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/Intervals.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/Intervals.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.data;
-import android.support.annotation.Nullable;
-import android.support.v4.util.LongSparseArray;
+import androidx.annotation.Nullable;
+import androidx.collection.LongSparseArray;
import java.util.ArrayList;
import java.util.List;
@@ -22,7 +22,7 @@ public abstract class Intervals {
rawData = new LongSparseArray();
}
- public synchronized Intervals reset() {
+ public synchronized Intervals reset() {
rawData = new LongSparseArray();
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java
index a87b77be07..79885e297f 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/IobTotal.java
@@ -9,10 +9,12 @@ import org.slf4j.LoggerFactory;
import java.util.Date;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.Round;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.Round;
-public class IobTotal {
+public class IobTotal implements DataPointWithLabelInterface {
private static Logger log = LoggerFactory.getLogger(IobTotal.class);
public double iob;
@@ -133,4 +135,52 @@ public class IobTotal {
return json;
}
+ // DataPoint interface
+
+ int color;
+
+ @Override
+ public double getX() {
+ return time;
+ }
+
+ @Override
+ public double getY() {
+ return iob;
+ }
+
+ @Override
+ public void setY(double y) {
+
+ }
+
+ @Override
+ public String getLabel() {
+ return null;
+ }
+
+ @Override
+ public long getDuration() {
+ return 0;
+ }
+
+ @Override
+ public PointsWithLabelGraphSeries.Shape getShape() {
+ return PointsWithLabelGraphSeries.Shape.IOBPREDICTION;
+ }
+
+ @Override
+ public float getSize() {
+ return 0.5f;
+ }
+
+ @Override
+ public int getColor() {
+ return color;
+ }
+
+ public IobTotal setColor(int color) {
+ this.color = color;
+ return this;
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.java
index 8e0c286e7e..c426aede40 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/NonOverlappingIntervals.java
@@ -1,10 +1,8 @@
package info.nightscout.androidaps.data;
-import android.support.annotation.Nullable;
-import android.support.v4.util.LongSparseArray;
+import androidx.annotation.Nullable;
-import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.Interval;
/**
@@ -21,7 +19,7 @@ public class NonOverlappingIntervals extends Intervals {
rawData = other.rawData.clone();
}
- protected synchronized void merge() {
+ public synchronized void merge() {
for (int index = 0; index < rawData.size() - 1; index++) {
Interval i = rawData.valueAt(index);
long startOfNewer = rawData.valueAt(index + 1).start();
diff --git a/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java
index 76c2ff3615..5515ea15e1 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/OverlappingIntervals.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.data;
-import android.support.annotation.Nullable;
+import androidx.annotation.Nullable;
import info.nightscout.androidaps.interfaces.Interval;
diff --git a/app/src/main/java/info/nightscout/androidaps/data/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java
index e6df495c40..6f18ba7af5 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java
@@ -1,6 +1,6 @@
package info.nightscout.androidaps.data;
-import android.support.v4.util.LongSparseArray;
+import androidx.collection.LongSparseArray;
import org.json.JSONArray;
import org.json.JSONException;
@@ -9,21 +9,22 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.DecimalFormat;
-import java.util.Calendar;
import java.util.TimeZone;
+import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.MidnightTime;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
+import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.MidnightTime;
public class Profile {
private static Logger log = LoggerFactory.getLogger(Profile.class);
@@ -166,17 +167,18 @@ public class Profile {
final JSONObject o = array.getJSONObject(index);
long tas = 0;
try {
- tas = getShitfTimeSecs((int) o.getLong("timeAsSeconds"));
- } catch (JSONException e) {
String time = o.getString("time");
tas = getShitfTimeSecs(DateUtil.toSeconds(time));
+ } catch (JSONException e) {
//log.debug(">>>>>>>>>>>> Used recalculated timeAsSecons: " + time + " " + tas);
+ tas = getShitfTimeSecs((int) o.getLong("timeAsSeconds"));
}
double value = o.getDouble("value") * multiplier;
sparse.put(tas, value);
- } catch (JSONException e) {
+ } catch (Exception e) {
log.error("Unhandled exception", e);
log.error(json.toString());
+ FabricPrivacy.logException(e);
}
}
@@ -227,8 +229,10 @@ public class Profile {
for (int index = 0; index < basal_v.size(); index++) {
long secondsFromMidnight = basal_v.keyAt(index);
if (notify && secondsFromMidnight % 3600 != 0) {
- Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL);
- MainApp.bus().post(new EventNewNotification(notification));
+ if (Config.APS) {
+ Notification notification = new Notification(Notification.BASAL_PROFILE_NOT_ALIGNED_TO_HOURS, String.format(MainApp.gs(R.string.basalprofilenotaligned), from), Notification.NORMAL);
+ RxBus.INSTANCE.send(new EventNewNotification(notification));
+ }
}
}
}
@@ -259,11 +263,11 @@ public class Profile {
}
protected void sendBelowMinimumNotification(String from) {
- MainApp.bus().post(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
+ RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MINIMAL_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.minimalbasalvaluereplaced), from), Notification.NORMAL)));
}
protected void sendAboveMaximumNotification(String from) {
- MainApp.bus().post(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
+ RxBus.INSTANCE.send(new EventNewNotification(new Notification(Notification.MAXIMUM_BASAL_VALUE_REPLACED, String.format(MainApp.gs(R.string.maximumbasalvaluereplaced), from), Notification.NORMAL)));
}
private void validate(LongSparseArray array) {
@@ -401,6 +405,19 @@ public class Profile {
return getValuesList(isf_v, null, new DecimalFormat("0.0"), getUnits() + MainApp.gs(R.string.profile_per_unit));
}
+ public ProfileValue[] getIsfs() {
+ if (isf_v == null)
+ isf_v = convertToSparseArray(ic);
+ ProfileValue[] ret = new ProfileValue[isf_v.size()];
+
+ for (Integer index = 0; index < isf_v.size(); index++) {
+ Integer tas = (int) isf_v.keyAt(index);
+ double value = isf_v.valueAt(index);
+ ret[index] = new ProfileValue(tas, value);
+ }
+ return ret;
+ }
+
public double getIc() {
return getIcTimeFromMidnight(secondsFromMidnight());
}
@@ -421,6 +438,19 @@ public class Profile {
return getValuesList(ic_v, null, new DecimalFormat("0.0"), MainApp.gs(R.string.profile_carbs_per_unit));
}
+ public ProfileValue[] getIcs() {
+ if (ic_v == null)
+ ic_v = convertToSparseArray(ic);
+ ProfileValue[] ret = new ProfileValue[ic_v.size()];
+
+ for (Integer index = 0; index < ic_v.size(); index++) {
+ Integer tas = (int) ic_v.keyAt(index);
+ double value = ic_v.valueAt(index);
+ ret[index] = new ProfileValue(tas, value);
+ }
+ return ret;
+ }
+
public double getBasal() {
return getBasalTimeFromMidnight(secondsFromMidnight());
}
@@ -439,11 +469,11 @@ public class Profile {
public String getBasalList() {
if (basal_v == null)
basal_v = convertToSparseArray(basal);
- return getValuesList(basal_v, null, new DecimalFormat("0.00"), MainApp.gs(R.string.profile_ins_units_per_hout));
+ return getValuesList(basal_v, null, new DecimalFormat("0.00"), MainApp.gs(R.string.profile_ins_units_per_hour));
}
- public class BasalValue {
- public BasalValue(int timeAsSeconds, double value) {
+ public class ProfileValue {
+ public ProfileValue(int timeAsSeconds, double value) {
this.timeAsSeconds = timeAsSeconds;
this.value = value;
}
@@ -452,15 +482,15 @@ public class Profile {
public double value;
}
- public synchronized BasalValue[] getBasalValues() {
+ public synchronized ProfileValue[] getBasalValues() {
if (basal_v == null)
basal_v = convertToSparseArray(basal);
- BasalValue[] ret = new BasalValue[basal_v.size()];
+ ProfileValue[] ret = new ProfileValue[basal_v.size()];
for (Integer index = 0; index < basal_v.size(); index++) {
Integer tas = (int) basal_v.keyAt(index);
double value = basal_v.valueAt(index);
- ret[index] = new BasalValue(tas, value);
+ ret[index] = new ProfileValue(tas, value);
}
return ret;
}
@@ -501,6 +531,49 @@ public class Profile {
return getValueToTime(targetHigh_v, timeAsSeconds);
}
+ public class TargetValue {
+ public TargetValue(int timeAsSeconds, double low, double high) {
+ this.timeAsSeconds = timeAsSeconds;
+ this.low = low;
+ this.high = high;
+ }
+
+ public int timeAsSeconds;
+ public double low;
+ public double high;
+ }
+
+ public TargetValue[] getTargets() {
+ if (targetLow_v == null)
+ targetLow_v = convertToSparseArray(targetLow);
+ if (targetHigh_v == null)
+ targetHigh_v = convertToSparseArray(targetHigh);
+ TargetValue[] ret = new TargetValue[targetLow_v.size()];
+
+ for (Integer index = 0; index < targetLow_v.size(); index++) {
+ Integer tas = (int) targetLow_v.keyAt(index);
+ double low = targetLow_v.valueAt(index);
+ double high = targetHigh_v.valueAt(index);
+ ret[index] = new TargetValue(tas, low, high);
+ }
+ return ret;
+ }
+
+ public ProfileValue[] getSingleTargets() {
+ if (targetLow_v == null)
+ targetLow_v = convertToSparseArray(targetLow);
+ if (targetHigh_v == null)
+ targetHigh_v = convertToSparseArray(targetHigh);
+ ProfileValue[] ret = new ProfileValue[targetLow_v.size()];
+
+ for (Integer index = 0; index < targetLow_v.size(); index++) {
+ Integer tas = (int) targetLow_v.keyAt(index);
+ double target = (targetLow_v.valueAt(index) + targetHigh_v.valueAt(index)) / 2;
+ ret[index] = new ProfileValue(tas, target);
+ }
+ return ret;
+ }
+
public String getTargetList() {
if (targetLow_v == null)
targetLow_v = convertToSparseArray(targetLow);
diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java
index 9343596eee..37be1dc6e9 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileIntervals.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.data;
-import android.support.annotation.Nullable;
-import android.support.v4.util.LongSparseArray;
+import androidx.annotation.Nullable;
+import androidx.collection.LongSparseArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -10,7 +10,6 @@ import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.interfaces.Interval;
-import info.nightscout.utils.DateUtil;
/**
* Created by mike on 09.05.2017.
@@ -32,7 +31,7 @@ public class ProfileIntervals {
rawData = other.rawData.clone();
}
- public synchronized ProfileIntervals reset() {
+ public synchronized ProfileIntervals reset() {
rawData = new LongSparseArray<>();
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java
index f97d8b5e02..a0b54ec0bb 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/ProfileStore.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.data;
-import android.support.annotation.Nullable;
-import android.support.v4.util.ArrayMap;
+import androidx.annotation.Nullable;
+import androidx.collection.ArrayMap;
import org.json.JSONException;
import org.json.JSONObject;
diff --git a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
index 404833b77c..461d8faa7b 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.java
@@ -1,8 +1,5 @@
package info.nightscout.androidaps.data;
-import android.text.Html;
-import android.text.Spanned;
-
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -11,8 +8,8 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.Round;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.Round;
public class PumpEnactResult {
private static Logger log = LoggerFactory.getLogger(L.APS);
@@ -48,6 +45,11 @@ public class PumpEnactResult {
return this;
}
+ public PumpEnactResult comment(int comment) {
+ this.comment = MainApp.gs(comment);
+ return this;
+ }
+
public PumpEnactResult duration(int duration) {
this.duration = duration;
return this;
diff --git a/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.java b/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.java
deleted file mode 100644
index 25c768cdda..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.java
+++ /dev/null
@@ -1,90 +0,0 @@
-package info.nightscout.androidaps.data;
-
-import android.content.SharedPreferences;
-import android.preference.PreferenceManager;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.utils.SP;
-
-/**
- * Created by mike on 12.10.2016.
- */
-
-public class QuickWizard {
- private static Logger log = LoggerFactory.getLogger(QuickWizard.class);
-
- private JSONArray storage = new JSONArray();
-
- public void setData(JSONArray newData) {
- storage = newData;
- }
-
- public void save() {
- SP.putString("QuickWizard", storage.toString());
- }
-
- public int size() {
- return storage.length();
- }
-
- public QuickWizardEntry get(int position) {
- try {
- return new QuickWizardEntry((JSONObject) storage.get(position), position);
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- return null;
- }
-
- public Boolean isActive() {
- for (int i = 0; i < storage.length(); i++) {
- try {
- if (new QuickWizardEntry((JSONObject) storage.get(i), i).isActive()) return true;
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
- return false;
- }
-
- public QuickWizardEntry getActive() {
- for (int i = 0; i < storage.length(); i++) {
- QuickWizardEntry entry;
- try {
- entry = new QuickWizardEntry((JSONObject) storage.get(i), i);
- } catch (JSONException e) {
- continue;
- }
- if (entry.isActive()) return entry;
- }
- return null;
- }
-
- public QuickWizardEntry newEmptyItem() {
- return new QuickWizardEntry();
- }
-
- public void addOrUpdate(QuickWizardEntry newItem) {
- if (newItem.position == -1)
- storage.put(newItem.storage);
- else {
- try {
- storage.put(newItem.position, newItem.storage);
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
- save();
- }
-
- public void remove(int position) {
- storage.remove(position);
- save();
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.kt b/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.kt
new file mode 100644
index 0000000000..f8bca8c450
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.kt
@@ -0,0 +1,52 @@
+package info.nightscout.androidaps.data
+
+import info.nightscout.androidaps.utils.SP
+import org.json.JSONArray
+import org.json.JSONObject
+
+object QuickWizard {
+ private var storage = JSONArray()
+
+ init {
+ setData(JSONArray(SP.getString("QuickWizard", "[]")))
+ }
+
+ fun getActive(): QuickWizardEntry? {
+ for (i in 0 until storage.length()) {
+ val entry = QuickWizardEntry(storage.get(i) as JSONObject, i)
+ if (entry.isActive) return entry
+ }
+ return null
+ }
+
+ fun setData(newData: JSONArray) {
+ storage = newData
+ }
+
+ fun save() {
+ SP.putString("QuickWizard", storage.toString())
+ }
+
+ fun size(): Int = storage.length()
+
+ operator fun get(position: Int): QuickWizardEntry =
+ QuickWizardEntry(storage.get(position) as JSONObject, position)
+
+
+ fun newEmptyItem(): QuickWizardEntry {
+ return QuickWizardEntry()
+ }
+
+ fun addOrUpdate(newItem: QuickWizardEntry) {
+ if (newItem.position == -1)
+ storage.put(newItem.storage)
+ else
+ storage.put(newItem.position, newItem.storage)
+ save()
+ }
+
+ fun remove(position: Int) {
+ storage.remove(position)
+ save()
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/data/QuickWizardEntry.java b/app/src/main/java/info/nightscout/androidaps/data/QuickWizardEntry.java
index 04f297d7a9..062f6ae391 100644
--- a/app/src/main/java/info/nightscout/androidaps/data/QuickWizardEntry.java
+++ b/app/src/main/java/info/nightscout/androidaps/data/QuickWizardEntry.java
@@ -11,13 +11,14 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
-import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.BolusWizard;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.BolusWizard;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 25.12.2017.
@@ -49,7 +50,7 @@ public class QuickWizardEntry {
useTemptarget: 0
}
*/
- public QuickWizardEntry() {
+ QuickWizardEntry() {
String emptyData = "{\"buttonText\":\"\",\"carbs\":0,\"validFrom\":0,\"validTo\":86340}";
try {
storage = new JSONObject(emptyData);
@@ -59,18 +60,17 @@ public class QuickWizardEntry {
position = -1;
}
- public QuickWizardEntry(JSONObject entry, int position) {
+ QuickWizardEntry(JSONObject entry, int position) {
storage = entry;
this.position = position;
}
- public Boolean isActive() {
+ Boolean isActive() {
return Profile.secondsFromMidnight() >= validFrom() && Profile.secondsFromMidnight() <= validTo();
}
- public BolusWizard doCalc(Profile profile, TempTarget tempTarget, BgReading lastBG, boolean _synchronized) {
- BolusWizard wizard = new BolusWizard();
-
+ public BolusWizard doCalc(Profile profile, String profileName, BgReading lastBG, boolean _synchronized) {
+ final TempTarget tempTarget = TreatmentsPlugin.getPlugin().getTempTargetFromHistory();
//BG
double bg = 0;
if (lastBG != null && useBG() == YES) {
@@ -85,11 +85,6 @@ public class QuickWizardEntry {
cob = cobInfo.displayCob;
}
- // Temp target
- if (useTempTarget() == NO) {
- tempTarget = null;
- }
-
// Bolus IOB
boolean bolusIOB = false;
if (useBolusIOB() == YES) {
@@ -129,8 +124,7 @@ public class QuickWizardEntry {
trend = true;
}
- wizard.doCalc(profile, tempTarget, carbs(), cob, bg, 0d, bolusIOB, basalIOB, superBolus, trend);
- return wizard;
+ return new BolusWizard(profile, profileName, tempTarget, carbs(), cob, bg, 0d, 100, true, useCOB() == YES, bolusIOB, basalIOB, superBolus, useTempTarget() == YES, trend, "QuickWizard");
}
public String buttonText() {
diff --git a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
index 3b5963b83b..8b206e2c78 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java
@@ -1,7 +1,5 @@
package info.nightscout.androidaps.db;
-import android.content.res.Resources;
-
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@@ -14,15 +12,13 @@ import java.util.Objects;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSSgv;
-import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.nsclient.data.NSSgv;
+import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_BGREADINGS)
public class BgReading implements DataPointWithLabelInterface {
@@ -220,8 +216,8 @@ public class BgReading implements DataPointWithLabelInterface {
@Override
public int getColor() {
String units = ProfileFunctions.getInstance().getProfileUnits();
- Double lowLine = OverviewPlugin.getPlugin().determineLowLine(units);
- Double highLine = OverviewPlugin.getPlugin().determineHighLine(units);
+ Double lowLine = OverviewPlugin.INSTANCE.determineLowLine(units);
+ Double highLine = OverviewPlugin.INSTANCE.determineHighLine(units);
int color = MainApp.gc(R.color.inrange);
if (isPrediction())
return getPredectionColor();
diff --git a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
index 60c7553cc3..40fadff684 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
@@ -13,7 +13,6 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.Date;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
@@ -26,14 +25,14 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.NSClientInternal.data.NSMbg;
-import info.nightscout.androidaps.plugins.Overview.OverviewFragment;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.T;
-import info.nightscout.utils.Translator;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg;
+import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.T;
+import info.nightscout.androidaps.utils.Translator;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_CAREPORTALEVENTS)
public class CareportalEvent implements DataPointWithLabelInterface, Interval {
@@ -90,16 +89,26 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
return System.currentTimeMillis() - date;
}
- public long getHoursFromStart() {
- return (System.currentTimeMillis() - date) / (60 * 60 * 1000);
+ public double getHoursFromStart() {
+ return (System.currentTimeMillis() - date) / (60 * 60 * 1000.0);
+ }
+
+ public String age(boolean useShortText) {
+ Map diff = computeDiff(date, System.currentTimeMillis());
+
+ String days = " " + MainApp.gs(R.string.days) + " ";
+ String hours = " " + MainApp.gs(R.string.hours) + " ";
+
+ if (useShortText) {
+ days = "d";
+ hours = "h";
+ }
+
+ return diff.get(TimeUnit.DAYS) + days + diff.get(TimeUnit.HOURS) + hours;
}
public String age() {
- Map diff = computeDiff(date, System.currentTimeMillis());
- if (OverviewFragment.shorttextmode)
- return diff.get(TimeUnit.DAYS) + "d" + diff.get(TimeUnit.HOURS) + "h";
- else
- return diff.get(TimeUnit.DAYS) + " " + MainApp.gs(R.string.days) + " " + diff.get(TimeUnit.HOURS) + " " + MainApp.gs(R.string.hours);
+ return age(OverviewFragment.shorttextmode);
}
public boolean isOlderThan(double hours) {
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 56f5d3b432..d8926fc4c1 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
@@ -3,7 +3,7 @@ package info.nightscout.androidaps.db;
import android.content.Context;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
-import android.support.annotation.Nullable;
+import androidx.annotation.Nullable;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.CloseableIterator;
@@ -21,6 +21,8 @@ import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.GregorianCalendar;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
@@ -29,13 +31,14 @@ import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.data.OverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventCareportalEventChange;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
import info.nightscout.androidaps.events.EventNewBG;
-import info.nightscout.androidaps.events.EventProfileSwitchChange;
+import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventRefreshOverview;
import info.nightscout.androidaps.events.EventReloadProfileSwitchData;
import info.nightscout.androidaps.events.EventReloadTempBasalData;
@@ -44,16 +47,19 @@ import info.nightscout.androidaps.events.EventTempBasalChange;
import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRNSHistorySync;
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.RecordTypes;
-import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.utils.JsonHelper;
-import info.nightscout.utils.PercentageSplitter;
-import info.nightscout.utils.ToastUtils;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
+import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRNSHistorySync;
+import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
+import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID;
+import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset;
+import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID;
+import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.utils.JsonHelper;
+import info.nightscout.androidaps.utils.PercentageSplitter;
+import info.nightscout.androidaps.utils.ToastUtils;
/**
* This Helper contains all resource to provide a central DB management functionality. Only methods handling
@@ -76,8 +82,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents";
public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches";
public static final String DATABASE_TDDS = "TDDs";
+ public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets";
+ public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs";
+ public static final String DATABASE_INSIGHT_PUMP_IDS = "InsightPumpIDs";
- private static final int DATABASE_VERSION = 9;
+ private static final int DATABASE_VERSION = 11;
public static Long earliestDataChange = null;
@@ -122,6 +131,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class);
TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class);
TableUtils.createTableIfNotExists(connectionSource, TDD.class);
+ TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
+ TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
+ TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
+ database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
+ "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
+ database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
+ "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
} catch (SQLException e) {
log.error("Can't create database", e);
throw new RuntimeException(e);
@@ -134,11 +150,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
this.oldVersion = oldVersion;
this.newVersion = newVersion;
- if (oldVersion == 7 && newVersion == 8) {
- log.debug("Upgrading database from v7 to v8");
- } else if (oldVersion == 8 && newVersion == 9) {
- log.debug("Upgrading database from v8 to v9");
- } else {
+ if (oldVersion < 7) {
log.info(DatabaseHelper.class.getName(), "onUpgrade");
TableUtils.dropTable(connectionSource, TempTarget.class, true);
TableUtils.dropTable(connectionSource, BgReading.class, true);
@@ -149,6 +161,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
TableUtils.dropTable(connectionSource, CareportalEvent.class, true);
TableUtils.dropTable(connectionSource, ProfileSwitch.class, true);
onCreate(database, connectionSource);
+ } else if (oldVersion < 10) {
+ TableUtils.createTableIfNotExists(connectionSource, InsightHistoryOffset.class);
+ TableUtils.createTableIfNotExists(connectionSource, InsightBolusID.class);
+ TableUtils.createTableIfNotExists(connectionSource, InsightPumpID.class);
+ database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_BOLUS_IDS + "\", " + System.currentTimeMillis() + " " +
+ "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\")");
+ database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " +
+ "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")");
+ } else if (oldVersion < 11) {
+ database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_BOLUS_IDS + "\"");
+ database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\"");
}
} catch (SQLException e) {
log.error("Can't drop databases", e);
@@ -220,7 +243,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
new java.util.TimerTask() {
@Override
public void run() {
- MainApp.bus().post(new EventRefreshOverview("resetDatabases"));
+ RxBus.INSTANCE.send(new EventRefreshOverview("resetDatabases"));
}
},
3000
@@ -327,6 +350,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return getDao(ProfileSwitch.class);
}
+ private Dao getDaoInsightPumpID() throws SQLException {
+ return getDao(InsightPumpID.class);
+ }
+
+ private Dao getDaoInsightBolusID() throws SQLException {
+ return getDao(InsightBolusID.class);
+ }
+
+ private Dao getDaoInsightHistoryOffset() throws SQLException {
+ return getDao(InsightHistoryOffset.class);
+ }
+
public static long roundDateToSec(long date) {
long rounded = date - date % 1000;
if (rounded != date)
@@ -377,7 +412,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventNewBg");
- MainApp.bus().post(new EventNewBG(bgReading));
+ RxBus.INSTANCE.send(new EventNewBG(bgReading));
scheduledBgPost = null;
}
}
@@ -396,24 +431,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
*/
@Nullable
public static BgReading lastBg() {
- List bgList = null;
+ List bgList = IobCobCalculatorPlugin.getPlugin().getBgReadings();
- try {
- Dao daoBgReadings = MainApp.getDbHelper().getDaoBgReadings();
- QueryBuilder queryBuilder = daoBgReadings.queryBuilder();
- queryBuilder.orderBy("date", false);
- queryBuilder.limit(1L);
- queryBuilder.where().ge("value", 39).and().eq("isValid", true);
- PreparedQuery preparedQuery = queryBuilder.prepare();
- bgList = daoBgReadings.query(preparedQuery);
-
- } catch (SQLException e) {
- log.error("Unhandled exception", e);
- }
- if (bgList != null && bgList.size() > 0)
- return bgList.get(0);
- else
+ if (bgList == null)
return null;
+
+ for (int i = 0; i < bgList.size(); i++)
+ if (bgList.get(i).value >= 39)
+ return bgList.get(i);
+ return null;
}
/*
@@ -448,7 +474,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
- return new ArrayList();
+ return new ArrayList<>();
}
public List getBgreadingsDataFromTime(long start, long end, boolean ascending) {
@@ -465,7 +491,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
} catch (SQLException e) {
log.error("Unhandled exception", e);
}
- return new ArrayList();
+ return new ArrayList<>();
}
public List getAllBgreadingsDataFromTime(long mills, boolean ascending) {
@@ -511,6 +537,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return tddList;
}
+ public List getTDDsForLastXDays(int days) {
+ List tddList;
+ GregorianCalendar gc = new GregorianCalendar();
+ gc.add(Calendar.DAY_OF_YEAR, (-1) * days);
+
+ try {
+ QueryBuilder queryBuilder = getDaoTDD().queryBuilder();
+ queryBuilder.orderBy("date", false);
+ Where where = queryBuilder.where();
+ where.ge("date", gc.getTimeInMillis());
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ tddList = getDaoTDD().query(preparedQuery);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ tddList = new ArrayList<>();
+ }
+ return tddList;
+ }
// ------------- DbRequests handling -------------------
@@ -573,7 +617,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
}
}
- // -------------------- TREATMENT HANDLING -------------------
+ // -------------------- TEMPTARGET HANDLING -------------------
public static void updateEarliestDataChange(long newDate) {
if (earliestDataChange == null) {
@@ -604,6 +648,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
+ public List getTemptargetsDataFromTime(long from, long to, boolean ascending) {
+ try {
+ Dao daoTempTargets = getDaoTempTargets();
+ List tempTargets;
+ QueryBuilder queryBuilder = daoTempTargets.queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.between("date", from, to);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ tempTargets = daoTempTargets.query(preparedQuery);
+ return tempTargets;
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return new ArrayList();
+ }
+
public boolean createOrUpdate(TempTarget tempTarget) {
try {
TempTarget old;
@@ -676,7 +737,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempTargetChange");
- MainApp.bus().post(new EventTempTargetChange());
+ RxBus.INSTANCE.send(new EventTempTargetChange());
scheduledTemTargetPost = null;
}
}
@@ -710,7 +771,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
String units = JsonHelper.safeGetString(trJson, "units", Constants.MGDL);
TempTarget tempTarget = new TempTarget()
.date(trJson.getLong("mills"))
- .duration(trJson.getInt("duration"))
+ .duration(JsonHelper.safeGetInt(trJson, "duration"))
.low(Profile.toMgdl(trJson.getDouble("targetBottom"), units))
.high(Profile.toMgdl(trJson.getDouble("targetTop"), units))
.reason(JsonHelper.safeGetString(trJson, "reason", ""))
@@ -829,6 +890,31 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
return false;
}
+
+ // search by date (in case its standard record that has become pump record)
+ QueryBuilder queryBuilder2 = getDaoTemporaryBasal().queryBuilder();
+ Where where2 = queryBuilder2.where();
+ where2.eq("date", tempBasal.date);
+ PreparedQuery preparedQuery2 = queryBuilder2.prepare();
+ List trList2 = getDaoTemporaryBasal().query(preparedQuery2);
+
+ if (trList2.size() > 0) {
+ old = trList2.get(0);
+
+ old.copyFromPump(tempBasal);
+ old.source = Source.PUMP;
+
+ if (L.isEnabled(L.DATABASE))
+ log.debug("TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
+
+ getDaoTemporaryBasal().update(old);
+
+ updateEarliestDataChange(tempBasal.date);
+ scheduleTemporaryBasalChange();
+
+ return false;
+ }
+
getDaoTemporaryBasal().create(tempBasal);
if (L.isEnabled(L.DATABASE))
log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString());
@@ -927,15 +1013,31 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList();
}
+ public List getTemporaryBasalsDataFromTime(long from, long to, boolean ascending) {
+ try {
+ List tempbasals;
+ QueryBuilder queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.between("date", from, to);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ tempbasals = getDaoTemporaryBasal().query(preparedQuery);
+ return tempbasals;
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return new ArrayList();
+ }
+
private static void scheduleTemporaryBasalChange() {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventTempBasalChange");
- MainApp.bus().post(new EventReloadTempBasalData());
- MainApp.bus().post(new EventTempBasalChange());
+ RxBus.INSTANCE.send(new EventReloadTempBasalData());
+ RxBus.INSTANCE.send(new EventTempBasalChange());
if (earliestDataChange != null)
- MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
+ RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledTemBasalsPost = null;
}
@@ -1053,6 +1155,29 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null;
}
+
+ public TemporaryBasal findTempBasalByPumpId(Long pumpId) {
+ try {
+ QueryBuilder queryBuilder = null;
+ queryBuilder = getDaoTemporaryBasal().queryBuilder();
+ queryBuilder.orderBy("date", false);
+ Where where = queryBuilder.where();
+ where.eq("pumpId", pumpId);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ List list = getDaoTemporaryBasal().query(preparedQuery);
+
+ if (list.size() > 0)
+ return list.get(0);
+ else
+ return null;
+
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
+
// ------------ ExtendedBolus handling ---------------
public boolean createOrUpdate(ExtendedBolus extendedBolus) {
@@ -1149,6 +1274,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return false;
}
+ public ExtendedBolus getExtendedBolusByPumpId(long pumpId) {
+ try {
+ return getDaoExtendedBolus().queryBuilder()
+ .where().eq("pumpId", pumpId)
+ .queryForFirst();
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
public void delete(ExtendedBolus extendedBolus) {
try {
getDaoExtendedBolus().delete(extendedBolus);
@@ -1234,9 +1370,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing EventExtendedBolusChange");
- MainApp.bus().post(new EventReloadTreatmentData(new EventExtendedBolusChange()));
+ RxBus.INSTANCE.send(new EventReloadTreatmentData(new EventExtendedBolusChange()));
if (earliestDataChange != null)
- MainApp.bus().post(new EventNewHistoryData(earliestDataChange));
+ RxBus.INSTANCE.send(new EventNewHistoryData(earliestDataChange));
earliestDataChange = null;
scheduledExtendedBolusPost = null;
}
@@ -1320,6 +1456,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<>();
}
+ public List getCareportalEvents(long start, long end, boolean ascending) {
+ try {
+ List careportalEvents;
+ QueryBuilder queryBuilder = getDaoCareportalEvents().queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ Where where = queryBuilder.where();
+ where.between("date", start, end);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ careportalEvents = getDaoCareportalEvents().query(preparedQuery);
+ preprocessOpenAPSOfflineEvents(careportalEvents);
+ return careportalEvents;
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return new ArrayList<>();
+ }
+
public void preprocessOpenAPSOfflineEvents(List list) {
OverlappingIntervals offlineEvents = new OverlappingIntervals();
for (int i = 0; i < list.size(); i++) {
@@ -1423,7 +1576,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
public void run() {
if (L.isEnabled(L.DATABASE))
log.debug("Firing scheduleCareportalEventChange");
- MainApp.bus().post(new EventCareportalEventChange());
+ RxBus.INSTANCE.send(new EventCareportalEventChange());
scheduledCareportalEventPost = null;
}
}
@@ -1473,6 +1626,24 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return new ArrayList<>();
}
+ public List getProfileSwitchEventsFromTime(long from, long to, boolean ascending) {
+ try {
+ Dao daoProfileSwitch = getDaoProfileSwitch();
+ List profileSwitches;
+ QueryBuilder queryBuilder = daoProfileSwitch.queryBuilder();
+ queryBuilder.orderBy("date", ascending);
+ queryBuilder.limit(100L);
+ Where where = queryBuilder.where();
+ where.between("date", from, to);
+ PreparedQuery preparedQuery = queryBuilder.prepare();
+ profileSwitches = daoProfileSwitch.query(preparedQuery);
+ return profileSwitches;
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return new ArrayList<>();
+ }
+
public boolean createOrUpdate(ProfileSwitch profileSwitch) {
try {
ProfileSwitch old;
@@ -1547,9 +1718,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
class PostRunnable implements Runnable {
public void run() {
if (L.isEnabled(L.DATABASE))
- log.debug("Firing EventProfileSwitchChange");
- MainApp.bus().post(new EventReloadProfileSwitchData());
- MainApp.bus().post(new EventProfileSwitchChange());
+ log.debug("Firing EventProfileNeedsUpdate");
+ RxBus.INSTANCE.send(new EventReloadProfileSwitchData());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
scheduledProfileSwitchEventPost = null;
}
}
@@ -1656,5 +1827,67 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
return null;
}
+ // ---------------- Insight history handling ---------------
+
+ public void createOrUpdate(InsightHistoryOffset offset) {
+ try {
+ getDaoInsightHistoryOffset().createOrUpdate(offset);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ }
+
+ public InsightHistoryOffset getInsightHistoryOffset(String pumpSerial) {
+ try {
+ return getDaoInsightHistoryOffset().queryForId(pumpSerial);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
+ public void createOrUpdate(InsightBolusID bolusID) {
+ try {
+ getDaoInsightBolusID().createOrUpdate(bolusID);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ }
+
+ public InsightBolusID getInsightBolusID(String pumpSerial, int bolusID, long timestamp) {
+ try {
+ return getDaoInsightBolusID().queryBuilder()
+ .where().eq("pumpSerial", pumpSerial)
+ .and().eq("bolusID", bolusID)
+ .and().between("timestamp", timestamp - 259200000, timestamp + 259200000)
+ .queryForFirst();
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
+ public void createOrUpdate(InsightPumpID pumpID) {
+ try {
+ getDaoInsightPumpID().createOrUpdate(pumpID);
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ }
+
+ public InsightPumpID getPumpStoppedEvent(String pumpSerial, long before) {
+ try {
+ return getDaoInsightPumpID().queryBuilder()
+ .orderBy("timestamp", false)
+ .where().eq("pumpSerial", pumpSerial)
+ .and().in("eventType", "PumpStopped", "PumpPaused")
+ .and().lt("timestamp", before)
+ .queryForFirst();
+ } catch (SQLException e) {
+ log.error("Unhandled exception", e);
+ }
+ return null;
+ }
+
// ---------------- Food handling ---------------
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DbObjectBase.java b/app/src/main/java/info/nightscout/androidaps/db/DbObjectBase.java
new file mode 100644
index 0000000000..a0c7f4bd7b
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/db/DbObjectBase.java
@@ -0,0 +1,9 @@
+package info.nightscout.androidaps.db;
+
+public interface DbObjectBase {
+
+ long getDate();
+
+ long getPumpId();
+
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
index b4fda73ab6..25d2c308c1 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/ExtendedBolus.java
@@ -9,7 +9,6 @@ import android.graphics.Color;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
-import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,17 +18,19 @@ import java.util.Objects;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.JsonHelper;
-import info.nightscout.utils.Round;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.treatments.Treatment;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.JsonHelper;
+import info.nightscout.androidaps.utils.Round;
/**
* Created by mike on 21.05.2017.
@@ -220,7 +221,7 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
IobTotal result = new IobTotal(time);
InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
- int realDuration = getDurationToTime(time);
+ double realDuration = getDurationToTime(time);
if (realDuration > 0) {
double dia_ago = time - dia * 60 * 60 * 1000;
@@ -248,6 +249,56 @@ public class ExtendedBolus implements Interval, DataPointWithLabelInterface {
return result;
}
+ public IobTotal iobCalc(long time, Profile profile, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
+ IobTotal result = new IobTotal(time);
+ InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
+
+ double realDuration = getDurationToTime(time);
+ double netBasalAmount = 0d;
+
+ double sensitivityRatio = lastAutosensResult.ratio;
+ double normalTarget = 100;
+
+ if (exercise_mode && isTempTarget && profile.getTarget() >= normalTarget + 5) {
+ // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44
+ // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6
+ double c = half_basal_exercise_target - normalTarget;
+ sensitivityRatio = c / (c + profile.getTarget() - normalTarget);
+ }
+
+ if (realDuration > 0) {
+ double netBasalRate;
+ double dia_ago = time - dia * 60 * 60 * 1000;
+ int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
+ double spacing = realDuration / aboutFiveMinIntervals;
+
+ for (long j = 0L; j < aboutFiveMinIntervals; j++) {
+ // find middle of the interval
+ long calcdate = (long) (date + j * spacing * 60 * 1000 + 0.5d * spacing * 60 * 1000);
+
+ double basalRate = profile.getBasal(calcdate);
+ double basalRateCorrection = basalRate * (sensitivityRatio - 1);
+
+
+ netBasalRate = absoluteRate() - basalRateCorrection;
+
+ if (calcdate > dia_ago && calcdate <= time) {
+ double tempBolusSize = netBasalRate * spacing / 60d;
+
+ Treatment tempBolusPart = new Treatment();
+ tempBolusPart.insulin = tempBolusSize;
+ tempBolusPart.date = calcdate;
+
+ Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, dia);
+ result.iob += aIOB.iobContrib;
+ result.activity += aIOB.activityContrib;
+ result.extendedBolusInsulin += tempBolusPart.insulin;
+ }
+ }
+ }
+ return result;
+ }
+
public int getRealDuration() {
return getDurationToTime(System.currentTimeMillis());
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
index f7252e97df..62b963e9ef 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/ProfileSwitch.java
@@ -1,12 +1,13 @@
package info.nightscout.androidaps.db;
import android.graphics.Color;
-import android.support.annotation.Nullable;
+
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
-import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -19,14 +20,16 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.DataPointWithLabelInterface;
-import info.nightscout.androidaps.plugins.Overview.graphExtensions.PointsWithLabelGraphSeries;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
-import info.nightscout.androidaps.plugins.ProfileLocal.LocalProfilePlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.T;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataPointWithLabelInterface;
+import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries;
+import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
+import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.T;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_PROFILESWITCHES)
public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@@ -79,12 +82,12 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return this;
}
- public ProfileSwitch source(int source) {
+ public ProfileSwitch source(int source) {
this.source = source;
return this;
}
- public ProfileSwitch duration(int duration) {
+ public ProfileSwitch duration(int duration) {
this.durationInMinutes = duration;
return this;
}
@@ -104,11 +107,11 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
/**
* Note: the name returned here is used as the PS name when uploading to NS. When such a PS is retrieved
* again from NS, the added parts must be removed again, see
- * {@link info.nightscout.utils.PercentageSplitter#pureName}
+ * {@link info.nightscout.androidaps.utils.PercentageSplitter#pureName}
*/
public String getCustomizedName() {
String name = profileName;
- if(LocalProfilePlugin.LOCAL_PROFILE.equals(name)){
+ if (LocalProfilePlugin.LOCAL_PROFILE.equals(name)) {
name = DecimalFormatter.to2Decimal(getProfileObject().percentageBasalSum()) + "U ";
}
if (isCPP) {
@@ -157,7 +160,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
// -------- Interval interface ---------
- Long cuttedEnd = null;
+ private Long cuttedEnd = null;
public long durationInMsec() {
return durationInMinutes * 60 * 1000L;
@@ -213,16 +216,17 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
@Override
public boolean isValid() {
-
boolean isValid = getProfileObject() != null && getProfileObject().isValid(DateUtil.dateAndTimeString(date));
- if (!isValid)
+ ProfileSwitch active = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(DateUtil.now());
+ long activeProfileSwitchDate = active != null ? active.date : -1L;
+ if (!isValid && date == activeProfileSwitchDate)
createNotificationInvalidProfile(DateUtil.dateAndTimeString(date));
return isValid;
}
- public void createNotificationInvalidProfile(String detail) {
+ private void createNotificationInvalidProfile(String detail) {
Notification notification = new Notification(Notification.ZERO_VALUE_IN_PROFILE, String.format(MainApp.gs(R.string.zerovalueinprofile), detail), Notification.LOW, 5);
- MainApp.bus().post(new EventNewNotification(notification));
+ RxBus.INSTANCE.send(new EventNewNotification(notification));
}
public static boolean isEvent5minBack(List list, long time, boolean zeroDurationOnly) {
@@ -291,6 +295,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface {
return Color.CYAN;
}
+ @NonNull
public String toString() {
return "ProfileSwitch{" +
"date=" + date +
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TDD.java b/app/src/main/java/info/nightscout/androidaps/db/TDD.java
index 9ca849b7b6..93a228316c 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TDD.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TDD.java
@@ -6,9 +6,8 @@ import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Objects;
-
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
/**
* Created by mike on 20.09.2017.
@@ -45,4 +44,16 @@ public class TDD {
this.basal = basal;
this.total = total;
}
+
+
+ @Override
+ public String toString() {
+ return "TDD [" +
+ "date=" + date +
+ "date(str)=" + DateTimeUtil.toStringFromTimeInMillis(date) +
+ ", bolus=" + bolus +
+ ", basal=" + basal +
+ ", total=" + total +
+ ']';
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
index 15692cbdfe..ef60d02911 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TempTarget.java
@@ -6,14 +6,16 @@ import com.j256.ormlite.table.DatabaseTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Date;
import java.util.Objects;
import info.nightscout.androidaps.Constants;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.DecimalFormatter;
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPTARGETS)
public class TempTarget implements Interval {
@@ -192,4 +194,11 @@ public class TempTarget implements Interval {
'}';
}
+ public String friendlyDescription(String units) {
+ return Profile.toTargetRangeString(low, high, Constants.MGDL, units) +
+ units +
+ "@" + MainApp.gs(R.string.mins, durationInMinutes) +
+ (reason != null && !reason.equals("") ? "(" + reason + ")" : "");
+ }
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
index eeaa8c0ee7..f2a10cf4a4 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/TemporaryBasal.java
@@ -8,7 +8,6 @@ import org.slf4j.LoggerFactory;
import java.util.Objects;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.IobTotal;
@@ -16,19 +15,20 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.InsulinInterface;
import info.nightscout.androidaps.interfaces.Interval;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.treatments.Treatment;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 21.05.2017.
*/
@DatabaseTable(tableName = DatabaseHelper.DATABASE_TEMPORARYBASALS)
-public class TemporaryBasal implements Interval {
+public class TemporaryBasal implements Interval, DbObjectBase {
private static Logger log = LoggerFactory.getLogger(L.DATABASE);
@DatabaseField(id = true)
@@ -157,6 +157,14 @@ public class TemporaryBasal implements Interval {
netExtendedRate = t.netExtendedRate;
}
+ public void copyFromPump(TemporaryBasal t) {
+ durationInMinutes = t.durationInMinutes;
+ isAbsolute = t.isAbsolute;
+ percentRate = t.percentRate;
+ absoluteRate = t.absoluteRate;
+ pumpId = t.pumpId;
+ }
+
// -------- Interval interface ---------
Long cuttedEnd = null;
@@ -234,7 +242,7 @@ public class TemporaryBasal implements Interval {
double netBasalAmount = 0d;
if (realDuration > 0) {
- double netBasalRate = 0d;
+ double netBasalRate;
double dia = profile.getDia();
double dia_ago = time - dia * 60 * 60 * 1000;
int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
@@ -244,10 +252,8 @@ public class TemporaryBasal implements Interval {
// find middle of the interval
long calcdate = (long) (date + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
- Double basalRate = profile.getBasal(calcdate);
+ double basalRate = profile.getBasal(calcdate);
- if (basalRate == null)
- continue;
if (isAbsolute) {
netBasalRate = absoluteRate - basalRate;
} else {
@@ -277,6 +283,73 @@ public class TemporaryBasal implements Interval {
return result;
}
+ public IobTotal iobCalc(long time, Profile profile, AutosensResult lastAutosensResult, boolean exercise_mode, int half_basal_exercise_target, boolean isTempTarget) {
+
+ if (isFakeExtended) {
+ log.error("iobCalc should only be called on Extended boluses separately");
+ return new IobTotal(time);
+ }
+
+ IobTotal result = new IobTotal(time);
+ InsulinInterface insulinInterface = ConfigBuilderPlugin.getPlugin().getActiveInsulin();
+
+ double realDuration = getDurationToTime(time);
+ double netBasalAmount = 0d;
+
+ double sensitivityRatio = lastAutosensResult.ratio;
+ double normalTarget = 100;
+
+ if (exercise_mode && isTempTarget && profile.getTarget() >= normalTarget + 5) {
+ // w/ target 100, temp target 110 = .89, 120 = 0.8, 140 = 0.67, 160 = .57, and 200 = .44
+ // e.g.: Sensitivity ratio set to 0.8 based on temp target of 120; Adjusting basal from 1.65 to 1.35; ISF from 58.9 to 73.6
+ double c = half_basal_exercise_target - normalTarget;
+ sensitivityRatio = c / (c + profile.getTarget() - normalTarget);
+ }
+
+ if (realDuration > 0) {
+ double netBasalRate;
+ double dia = profile.getDia();
+ double dia_ago = time - dia * 60 * 60 * 1000;
+ int aboutFiveMinIntervals = (int) Math.ceil(realDuration / 5d);
+ double tempBolusSpacing = realDuration / aboutFiveMinIntervals;
+
+ for (long j = 0L; j < aboutFiveMinIntervals; j++) {
+ // find middle of the interval
+ long calcdate = (long) (date + j * tempBolusSpacing * 60 * 1000 + 0.5d * tempBolusSpacing * 60 * 1000);
+
+ double basalRate = profile.getBasal(calcdate);
+ basalRate *= sensitivityRatio;
+
+ if (isAbsolute) {
+ netBasalRate = absoluteRate - basalRate;
+ } else {
+ double abs = percentRate / 100d * profile.getBasal(calcdate);
+ netBasalRate = abs - basalRate;
+ }
+
+ if (calcdate > dia_ago && calcdate <= time) {
+ double tempBolusSize = netBasalRate * tempBolusSpacing / 60d;
+ netBasalAmount += tempBolusSize;
+
+ Treatment tempBolusPart = new Treatment();
+ tempBolusPart.insulin = tempBolusSize;
+ tempBolusPart.date = calcdate;
+
+ Iob aIOB = insulinInterface.iobCalcForTreatment(tempBolusPart, time, dia);
+ result.basaliob += aIOB.iobContrib;
+ result.activity += aIOB.activityContrib;
+ result.netbasalinsulin += tempBolusPart.insulin;
+ if (tempBolusPart.insulin > 0) {
+ result.hightempinsulin += tempBolusPart.insulin;
+ }
+ }
+ result.netRatio = netBasalRate; // ratio at the end of interval
+ }
+ }
+ result.netInsulin = netBasalAmount;
+ return result;
+ }
+
public int getRealDuration() {
return getDurationToTime(System.currentTimeMillis());
}
@@ -332,8 +405,10 @@ public class TemporaryBasal implements Interval {
if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile();
+ if (profile == null)
+ return "null";
Double currentBasalRate = profile.getBasal();
- double rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
+ double rate = currentBasalRate + netExtendedRate;
return getCalcuatedPercentageIfNeeded() + DecimalFormatter.to2Decimal(rate) + "U/h (" + DecimalFormatter.to2Decimal(netExtendedRate) + "E) @" +
DateUtil.timeString(date) +
" " + getRealDuration() + "/" + durationInMinutes + "'";
@@ -351,12 +426,14 @@ public class TemporaryBasal implements Interval {
public String toStringShort() {
if (isAbsolute || isFakeExtended) {
- double rate = 0d;
+ double rate;
if (isFakeExtended) {
Profile profile = ProfileFunctions.getInstance().getProfile();
- Double currentBasalRate = profile.getBasal();
- rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
- } else if (isAbsolute) {
+ if (profile == null)
+ return "null";
+ double currentBasalRate = profile.getBasal();
+ rate = currentBasalRate + netExtendedRate;
+ } else {
rate = absoluteRate;
}
@@ -376,24 +453,25 @@ public class TemporaryBasal implements Interval {
}
private String getCalcuatedPercentageIfNeeded() {
+ Profile profile = ProfileFunctions.getInstance().getProfile();
+
+ if (profile == null)
+ return "null";
+
if (isAbsolute || isFakeExtended) {
- double rate = 0d;
+ double rate;
if (isFakeExtended) {
- Profile profile = ProfileFunctions.getInstance().getProfile();
- Double currentBasalRate = profile.getBasal();
- rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
- } else if (isAbsolute) {
+ double currentBasalRate = profile.getBasal();
+ rate = currentBasalRate + netExtendedRate;
+ } else {
rate = absoluteRate;
}
if (SP.getBoolean(R.string.key_danar_visualizeextendedaspercentage, false) && SP.getBoolean(R.string.key_danar_useextended, false)) {
- Profile profile = ProfileFunctions.getInstance().getProfile();
- if (profile != null) {
- double basal = profile.getBasal();
- if (basal != 0) {
- return Math.round(rate * 100d / basal) + "% ";
- }
+ double basal = profile.getBasal();
+ if (basal != 0) {
+ return Math.round(rate * 100d / basal) + "% ";
}
}
}
@@ -401,14 +479,18 @@ public class TemporaryBasal implements Interval {
}
public String toStringVeryShort() {
+ Profile profile = ProfileFunctions.getInstance().getProfile();
+
+ if (profile == null)
+ return "null";
+
if (isAbsolute || isFakeExtended) {
- double rate = 0d;
+ double rate;
if (isFakeExtended) {
- Profile profile = ProfileFunctions.getInstance().getProfile();
- Double currentBasalRate = profile.getBasal();
- rate = (currentBasalRate == null) ? 0d : (currentBasalRate + netExtendedRate);
- } else if (isAbsolute) {
+ double currentBasalRate = profile.getBasal();
+ rate = currentBasalRate + netExtendedRate;
+ } else {
rate = absoluteRate;
}
return DecimalFormatter.to2Decimal(rate) + "U/h ";
@@ -417,4 +499,13 @@ public class TemporaryBasal implements Interval {
}
}
+ @Override
+ public long getDate() {
+ return this.date;
+ }
+
+ @Override
+ public long getPumpId() {
+ return this.pumpId;
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/Event.java b/app/src/main/java/info/nightscout/androidaps/events/Event.java
deleted file mode 100644
index 864d55d6f7..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/Event.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
-import org.apache.commons.lang3.builder.ToStringStyle;
-
-/** Base class for all events posted on the event bus. */
-public abstract class Event {
- static {
- ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE);
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.toString(this);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/Event.kt b/app/src/main/java/info/nightscout/androidaps/events/Event.kt
new file mode 100644
index 0000000000..a44f65e836
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/Event.kt
@@ -0,0 +1,18 @@
+package info.nightscout.androidaps.events
+
+import org.apache.commons.lang3.builder.ReflectionToStringBuilder
+import org.apache.commons.lang3.builder.ToStringStyle
+
+/** Base class for all events posted on the event bus. */
+abstract class Event {
+
+ override fun toString(): String {
+ return ReflectionToStringBuilder.toString(this)
+ }
+
+ companion object {
+ init {
+ ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE)
+ }
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java
deleted file mode 100644
index 2dfbf9ae35..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/** Base class for events to update the UI, mostly a specific tab. */
-public class EventAcceptOpenLoopChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt
new file mode 100644
index 0000000000..552564edfc
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventAcceptOpenLoopChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventAcceptOpenLoopChange : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java
deleted file mode 100644
index 9ce91a9a39..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 07.07.2016.
- */
-public class EventAppExit extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt
new file mode 100644
index 0000000000..640b586f5f
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventAppExit.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventAppExit : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java
deleted file mode 100644
index 17262cfb85..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 23.01.2018.
- */
-
-public class EventAppInitialized extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt
new file mode 100644
index 0000000000..293f9698f2
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventAppInitialized.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventAppInitialized : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java
deleted file mode 100644
index cb727758bb..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by adrian on 07/02/17.
- */
-
-public class EventBolusRequested extends Event {
- private double amount;
-
- public EventBolusRequested (double amount){
- this.amount = amount;
- }
-
- public double getAmount() {
- return amount;
- }
-
- public void setAmount(double amount) {
- this.amount = amount;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt
new file mode 100644
index 0000000000..a528ef1656
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventBolusRequested(var amount: Double) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java
deleted file mode 100644
index 9b47ed39cb..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 25.05.2017.
- */
-
-public class EventCareportalEventChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt
new file mode 100644
index 0000000000..e7d52d86c0
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventCareportalEventChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventCareportalEventChange : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java b/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java
deleted file mode 100644
index bcd9061133..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package info.nightscout.androidaps.events;
-
-public class EventChargingState {
-
- public boolean isCharging = false;
-
- public EventChargingState() {}
-
- public EventChargingState(boolean isCharging) {
- this.isCharging = isCharging;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.kt b/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.kt
new file mode 100644
index 0000000000..f9ff60a71d
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventChargingState.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventChargingState(val isCharging: Boolean) : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java
deleted file mode 100644
index ad5f558fe8..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 17.02.2017.
- */
-
-public class EventConfigBuilderChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt
new file mode 100644
index 0000000000..b674374fad
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventConfigBuilderChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventConfigBuilderChange : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt
new file mode 100644
index 0000000000..d75bf612ce
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventCustomActionsChanged : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java
deleted file mode 100644
index e52761dc58..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 13.02.2018.
- */
-
-public class EventCustomCalculationFinished extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt
new file mode 100644
index 0000000000..f6092b395d
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventCustomCalculationFinished.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventCustomCalculationFinished : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java
deleted file mode 100644
index 8881b0ecc1..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 15.05.2017.
- */
-
-public class EventExtendedBolusChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt
new file mode 100644
index 0000000000..4ed0ca5ffe
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventExtendedBolusChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventExtendedBolusChange : EventLoop()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java b/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java
deleted file mode 100644
index 0d07cd6c61..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventFeatureRunning.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by jamorham on 07/02/2018.
- *
- * Event to indicate that an app feature is being used, for example bolus wizard being opened
- *
- * The purpose this has been created for is to enable opportunistic connection to the pump
- * so that it is already connected before the user wishes to enact a pump function
- *
- */
-
-public class EventFeatureRunning extends Event {
-
- private Feature feature = Feature.UNKNOWN;
-
- public EventFeatureRunning() {
- }
-
- public EventFeatureRunning(Feature feature) {
- this.feature = feature;
- }
-
- public Feature getFeature() {
- return feature;
- }
-
- public enum Feature {
- UNKNOWN,
- MAIN,
- WIZARD,
-
- JUST_ADD_MORE_HERE
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java
deleted file mode 100644
index 48e6be3a14..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 20.09.2017.
- */
-
-public class EventFoodDatabaseChanged extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt
new file mode 100644
index 0000000000..83402c3cb6
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventFoodDatabaseChanged.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventFoodDatabaseChanged : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java
deleted file mode 100644
index f2bef1d3d0..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 13.12.2016.
- */
-
-public class EventInitializationChanged extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt
new file mode 100644
index 0000000000..33ab0062c5
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventInitializationChanged.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventInitializationChanged : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt
new file mode 100644
index 0000000000..fee6c9f800
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.events
+
+import android.location.Location
+
+class EventLocationChange(var location: Location) : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java
deleted file mode 100644
index d694d52537..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/** Supeclass for all events concerned with input or output into or from the LoopPlugin. */
-public abstract class EventLoop extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt
new file mode 100644
index 0000000000..dd28e2323b
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventLoop.kt
@@ -0,0 +1,4 @@
+package info.nightscout.androidaps.events
+
+/** Supeclass for all events concerned with input or output into or from the LoopPlugin. */
+abstract class EventLoop : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java
deleted file mode 100644
index 57050bdcc9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package info.nightscout.androidaps.events;
-
-
-import info.nightscout.utils.StringUtils;
-
-public class EventNetworkChange extends Event {
-
- public boolean mobileConnected = false;
- public boolean wifiConnected = false;
-
- public String ssid = "";
- public boolean roaming = false;
-
- public String getSsid() {
- return StringUtils.removeSurroundingQuotes(ssid);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt
new file mode 100644
index 0000000000..62c8bdd13e
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt
@@ -0,0 +1,16 @@
+package info.nightscout.androidaps.events
+
+import info.nightscout.androidaps.utils.StringUtils
+
+class EventNetworkChange : Event() {
+
+ var mobileConnected = false
+ var wifiConnected = false
+
+ var ssid = ""
+ var roaming = false
+
+ fun connectedSsid(): String {
+ return StringUtils.removeSurroundingQuotes(ssid)
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java
deleted file mode 100644
index dc4d434e0a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import android.support.annotation.Nullable;
-
-import info.nightscout.androidaps.db.BgReading;
-
-/**
- * Created by mike on 05.06.2016.
- */
-public class EventNewBG extends EventLoop {
- @Nullable
- public final BgReading bgReading;
-
- public EventNewBG(BgReading bgReading) {
- this.bgReading = bgReading;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt
new file mode 100644
index 0000000000..08c05407c9
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.events
+
+import info.nightscout.androidaps.db.BgReading
+
+class EventNewBG(val bgReading: BgReading?) : EventLoop()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java
deleted file mode 100644
index f26a310b6b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 04.06.2016.
- */
-public class EventNewBasalProfile extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt
new file mode 100644
index 0000000000..2ffa5a9724
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNewBasalProfile.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventNewBasalProfile : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java
deleted file mode 100644
index 90b6f5681b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import android.os.Bundle;
-
-/**
- * Event which is published with data fetched from NightScout specific for the
- * Food-class.
- *
- * Payload is the from NS retrieved JSON-String which should be handled by all
- * subscriber.
- */
-
-public class EventNsFood extends Event {
-
- public static final int ADD = 0;
- public static final int UPDATE = 1;
- public static final int REMOVE = 2;
-
- private final int mode;
-
- private final Bundle payload;
-
- public EventNsFood(int mode, Bundle payload) {
- this.mode = mode;
- this.payload = payload;
- }
-
- public int getMode() {
- return mode;
- }
-
- public Bundle getPayload() {
- return payload;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt
new file mode 100644
index 0000000000..2f34e76c85
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsFood.kt
@@ -0,0 +1,19 @@
+package info.nightscout.androidaps.events
+
+import android.os.Bundle
+
+/**
+ * Event which is published with data fetched from NightScout specific for the
+ * Food-class.
+ *
+ * Payload is the from NS retrieved JSON-String which should be handled by all
+ * subscriber.
+ */
+
+class EventNsFood(val mode: Int, val payload: Bundle) : Event() {
+ companion object {
+ val ADD = 0
+ val UPDATE = 1
+ val REMOVE = 2
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java
deleted file mode 100644
index 2c5ba6c9c0..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import org.json.JSONObject;
-
-
-/**
- * Event which is published with data fetched from NightScout specific for the
- * Treatment-class.
- *
- * Payload is the from NS retrieved JSON-String which should be handled by all
- * subscriber.
- */
-
-public class EventNsTreatment extends Event {
-
- public static final int ADD = 0;
- public static final int UPDATE = 1;
- public static final int REMOVE = 2;
-
- private final int mode;
-
- private final JSONObject payload;
-
- public EventNsTreatment(int mode, JSONObject payload) {
- this.mode = mode;
- this.payload = payload;
- }
-
- public int getMode() {
- return mode;
- }
-
- public JSONObject getPayload() {
- return payload;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt
new file mode 100644
index 0000000000..149894c221
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventNsTreatment.kt
@@ -0,0 +1,21 @@
+package info.nightscout.androidaps.events
+
+import org.json.JSONObject
+
+
+/**
+ * Event which is published with data fetched from NightScout specific for the
+ * Treatment-class.
+ *
+ *
+ * Payload is the from NS retrieved JSON-String which should be handled by all
+ * subscriber.
+ */
+
+class EventNsTreatment(val mode: Int, val payload: JSONObject) : Event() {
+ companion object {
+ val ADD = 0
+ val UPDATE = 1
+ val REMOVE = 2
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java
deleted file mode 100644
index f23d4e802a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import info.nightscout.androidaps.MainApp;
-
-/**
- * Created by mike on 19.06.2016.
- */
-public class EventPreferenceChange extends Event {
- public String changedKey;
- public EventPreferenceChange(String key) {
- changedKey = key;
- }
-
- public EventPreferenceChange(int resourceID) {
- changedKey = MainApp.gs(resourceID);
- }
-
- public boolean isChanged(int id) {
- return changedKey.equals(MainApp.gs(id));
- }
-
- public boolean isChanged(String id) {
- return changedKey.equals(id);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt
new file mode 100644
index 0000000000..d224d75df1
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt
@@ -0,0 +1,19 @@
+package info.nightscout.androidaps.events
+
+import info.nightscout.androidaps.MainApp
+
+class EventPreferenceChange : Event {
+ private var changedKey: String? = null
+
+ constructor(key: String) {
+ changedKey = key
+ }
+
+ constructor(resourceID: Int) {
+ changedKey = MainApp.gs(resourceID)
+ }
+
+ fun isChanged(id: Int): Boolean {
+ return changedKey == MainApp.gs(id)
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt
new file mode 100644
index 0000000000..2baf1db945
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventProfileNeedsUpdate : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java
deleted file mode 100644
index 0b2d933c12..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.java
+++ /dev/null
@@ -1,4 +0,0 @@
-package info.nightscout.androidaps.events;
-
-public class EventProfileStoreChanged extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt
new file mode 100644
index 0000000000..0e839ca2d3
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventProfileStoreChanged.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventProfileStoreChanged : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java
deleted file mode 100644
index 7bab9d4518..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventProfileSwitchChange.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 02.06.2017.
- */
-
-public class EventProfileSwitchChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java
deleted file mode 100644
index 6729a4e703..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-
-/**
- * Created by mike on 19.02.2017.
- */
-
-public class EventPumpStatusChanged extends Event {
- public static final int CONNECTING = 0;
- public static final int CONNECTED = 1;
- public static final int HANDSHAKING = 2;
- public static final int PERFORMING = 3;
- public static final int DISCONNECTING = 4;
- public static final int DISCONNECTED = 5;
-
- public int sStatus = DISCONNECTED;
- public int sSecondsElapsed = 0;
- public String sPerfomingAction = "";
-
- public static String error = "";
-
- public EventPumpStatusChanged(int status) {
- sStatus = status;
- sSecondsElapsed = 0;
- error = "";
- }
-
- public EventPumpStatusChanged(int status, int secondsElapsed) {
- sStatus = status;
- sSecondsElapsed = secondsElapsed;
- error = "";
- }
-
- public EventPumpStatusChanged(int status, String error) {
- sStatus = status;
- sSecondsElapsed = 0;
- this.error = error;
- }
-
- public EventPumpStatusChanged(String action) {
- sStatus = PERFORMING;
- sSecondsElapsed = 0;
- sPerfomingAction = action;
- }
-
- public String textStatus() {
- if (sStatus == CONNECTING)
- return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed);
- else if (sStatus == HANDSHAKING)
- return MainApp.gs(R.string.handshaking);
- else if (sStatus == CONNECTED)
- return MainApp.gs(R.string.connected);
- else if (sStatus == PERFORMING)
- return sPerfomingAction;
- else if (sStatus == DISCONNECTING)
- return MainApp.gs(R.string.disconnecting);
- else if (sStatus == DISCONNECTED)
- return "";
- return "";
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt
new file mode 100644
index 0000000000..3d25bc1ca5
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt
@@ -0,0 +1,62 @@
+package info.nightscout.androidaps.events
+
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+
+class EventPumpStatusChanged : EventStatus {
+
+ enum class Status {
+ CONNECTING,
+ CONNECTED,
+ HANDSHAKING,
+ PERFORMING,
+ DISCONNECTING,
+ DISCONNECTED
+ }
+
+ var sStatus: Status = Status.DISCONNECTED
+ var sSecondsElapsed = 0
+ var sPerfomingAction = ""
+ var error = ""
+
+ constructor(status: Status) {
+ sStatus = status
+ sSecondsElapsed = 0
+ error = ""
+ }
+
+ constructor(status: Status, secondsElapsed: Int) {
+ sStatus = status
+ sSecondsElapsed = secondsElapsed
+ error = ""
+ }
+
+ constructor(status: Status, error: String) {
+ sStatus = status
+ sSecondsElapsed = 0
+ this.error = error
+ }
+
+ constructor(action: String) {
+ sStatus = Status.PERFORMING
+ sSecondsElapsed = 0
+ sPerfomingAction = action
+ }
+
+ // status for startup wizard
+ override fun getStatus(): String {
+ if (sStatus == Status.CONNECTING)
+ return String.format(MainApp.gs(R.string.danar_history_connectingfor), sSecondsElapsed)
+ else if (sStatus == Status.HANDSHAKING)
+ return MainApp.gs(R.string.handshaking)
+ else if (sStatus == Status.CONNECTED)
+ return MainApp.gs(R.string.connected)
+ else if (sStatus == Status.PERFORMING)
+ return sPerfomingAction
+ else if (sStatus == Status.DISCONNECTING)
+ return MainApp.gs(R.string.disconnecting)
+ else if (sStatus == Status.DISCONNECTED)
+ return ""
+ return ""
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt b/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt
new file mode 100644
index 0000000000..aa0db3467a
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventRebuildTabs @JvmOverloads constructor(var recreate: Boolean = false) : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java
deleted file mode 100644
index 390ad8ea4f..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshGui.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 13.06.2016.
- */
-public class EventRefreshGui extends Event {
- public boolean recreate = false;
- public EventRefreshGui(boolean recreate) {
- this.recreate = recreate;
- }
- public EventRefreshGui(){
- this(false);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java
deleted file mode 100644
index 2ba78fa9ec..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 16.06.2017.
- */
-
-public class EventRefreshOverview extends Event {
- public String from;
-
- public EventRefreshOverview(String from) {
- this.from = from;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt
new file mode 100644
index 0000000000..533a25dd40
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventRefreshOverview.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventRefreshOverview(var from: String) : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java
deleted file mode 100644
index 212e8856d9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 12.06.2017.
- */
-
-public class EventReloadProfileSwitchData extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt
new file mode 100644
index 0000000000..6f6d848b5e
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadProfileSwitchData.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventReloadProfileSwitchData : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java
deleted file mode 100644
index 80125cbb4a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 29.05.2017.
- */
-
-public class EventReloadTempBasalData extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt
new file mode 100644
index 0000000000..fa8f720896
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTempBasalData.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventReloadTempBasalData : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java
deleted file mode 100644
index 0ba9b95ad7..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 29.05.2017.
- */
-
-public class EventReloadTreatmentData extends Event {
- public Object next;
-
- public EventReloadTreatmentData(Object next) {
- this.next = next;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt
new file mode 100644
index 0000000000..1f8b2938b9
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventReloadTreatmentData.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventReloadTreatmentData(var next: Event) : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt b/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt
new file mode 100644
index 0000000000..193c3b1fdb
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventStatus.kt
@@ -0,0 +1,6 @@
+package info.nightscout.androidaps.events
+
+// pass string to startup wizard
+abstract class EventStatus :Event() {
+ abstract fun getStatus() : String
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java
deleted file mode 100644
index 73660bb00e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 05.06.2016.
- */
-public class EventTempBasalChange extends EventLoop {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt
new file mode 100644
index 0000000000..3f3ecf732e
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventTempBasalChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventTempBasalChange : EventLoop()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java
deleted file mode 100644
index 4e3bf5c5f8..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/**
- * Created by mike on 13.01.2017.
- */
-
-public class EventTempTargetChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt
new file mode 100644
index 0000000000..c108d6589c
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventTempTargetChange.kt
@@ -0,0 +1,3 @@
+package info.nightscout.androidaps.events
+
+class EventTempTargetChange : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java
deleted file mode 100644
index 989b24b7f9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package info.nightscout.androidaps.events;
-
-import android.support.annotation.Nullable;
-
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
-
-/**
- * Created by mike on 04.06.2016.
- */
-public class EventTreatmentChange extends EventLoop {
- @Nullable
- public final Treatment treatment;
-
- public EventTreatmentChange(Treatment treatment) {
- this.treatment = treatment;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt
new file mode 100644
index 0000000000..9cbc9d1563
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.events
+
+import info.nightscout.androidaps.plugins.treatments.Treatment
+
+class EventTreatmentChange(val treatment: Treatment?) : EventLoop()
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java
deleted file mode 100644
index 3471d2e851..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package info.nightscout.androidaps.events;
-
-/** Base class for events to update the UI, mostly a specific tab. */
-public abstract class EventUpdateGui extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt
new file mode 100644
index 0000000000..cc21e784b9
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/events/EventUpdateGui.kt
@@ -0,0 +1,4 @@
+package info.nightscout.androidaps.events
+
+/** Base class for events to update the UI, mostly a specific tab. */
+abstract class EventUpdateGui : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
index 2f37c47391..7d32e37ff0 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/APSInterface.java
@@ -1,13 +1,14 @@
package info.nightscout.androidaps.interfaces;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
/**
* Created by mike on 10.06.2016.
*/
public interface APSInterface {
- public APSResult getLastAPSResult();
- public long getLastAPSRun();
+ APSResult getLastAPSResult();
- public void invoke(String initiator, boolean tempBasalFallback);
+ long getLastAPSRun();
+
+ void invoke(String initiator, boolean tempBasalFallback);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
index 5ac8cc83f7..14b2d549af 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ConstraintsInterface.java
@@ -35,6 +35,10 @@ public interface ConstraintsInterface {
return value;
}
+ default Constraint isSuperBolusEnabled(Constraint value) {
+ return value;
+ }
+
default Constraint applyBasalConstraints(Constraint absoluteRate, Profile profile) {
return absoluteRate;
}
@@ -57,6 +61,6 @@ public interface ConstraintsInterface {
default Constraint applyMaxIOBConstraints(Constraint maxIob) {
return maxIob;
- };
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
index 34b14d9b5d..2ad36fb747 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/InsulinInterface.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.interfaces;
import info.nightscout.androidaps.data.Iob;
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
+import info.nightscout.androidaps.plugins.treatments.Treatment;
/**
* Created by mike on 17.04.2017.
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
index a1a35b7413..f7c8e9ada4 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
@@ -1,16 +1,23 @@
package info.nightscout.androidaps.interfaces;
import android.os.SystemClock;
-import android.support.v4.app.FragmentActivity;
+
+import androidx.appcompat.app.AlertDialog;
+import androidx.fragment.app.FragmentActivity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.events.EventConfigBuilderChange;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui;
import info.nightscout.androidaps.queue.CommandQueue;
+import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 09.06.2016.
@@ -38,17 +45,46 @@ public abstract class PluginBase {
// Default always calls invoke
// Plugins that have special constraints if they get switched to may override this method
- public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity activity) {
- pluginSwitcher.invoke();
+ public void switchAllowed(boolean newState, FragmentActivity activity, PluginType type) {
+ performPluginSwitch(newState, type);
}
-// public PluginType getType() {
-// return mainType;
-// }
+ protected void confirmPumpPluginActivation(boolean newState, FragmentActivity activity, PluginType type) {
+ if (type == PluginType.PUMP) {
+ boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
+ if (allowHardwarePump || activity == null) {
+ performPluginSwitch(newState, type);
+ } else {
+ AlertDialog.Builder builder = new AlertDialog.Builder(activity);
+ builder.setMessage(R.string.allow_hardware_pump_text)
+ .setPositiveButton(R.string.yes, (dialog, id) -> {
+ performPluginSwitch(newState, type);
+ SP.putBoolean("allow_hardware_pump", true);
+ if (L.isEnabled(L.PUMP))
+ log.debug("First time HW pump allowed!");
+ })
+ .setNegativeButton(R.string.cancel, (dialog, id) -> {
+ RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui());
+ if (L.isEnabled(L.PUMP))
+ log.debug("User does not allow switching to HW pump!");
+ });
+ builder.create().show();
+ }
+ } else {
+ performPluginSwitch(newState, type);
+ }
+ }
-// public String getFragmentClass() {
-// return fragmentClass;
-// }
+ private void performPluginSwitch(boolean enabled, PluginType type) {
+ setPluginEnabled(type, enabled);
+ setFragmentVisible(type, enabled);
+ ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType());
+ ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled");
+ RxBus.INSTANCE.send(new EventRebuildTabs());
+ RxBus.INSTANCE.send(new EventConfigBuilderChange());
+ RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui());
+ ConfigBuilderPlugin.getPlugin().logPluginStatus();
+ }
public String getName() {
if (pluginDescription.pluginName == -1)
@@ -80,10 +116,6 @@ public abstract class PluginBase {
return pluginDescription.preferencesId;
}
- public int getAdvancedPreferencesId() {
- return pluginDescription.advancedPreferencesId;
- }
-
public boolean isEnabled(PluginType type) {
if (pluginDescription.alwaysEnabled && type == pluginDescription.mainType)
return true;
@@ -93,6 +125,8 @@ public abstract class PluginBase {
return state == State.ENABLED && specialEnableCondition();
if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.PUMP && isEnabled(PluginType.PUMP))
return true;
+ if (type == PluginType.CONSTRAINTS && pluginDescription.mainType == PluginType.APS && isEnabled(PluginType.APS))
+ return true;
if (type == PluginType.PROFILE && pluginDescription.mainType == PluginType.PUMP)
return isProfileInterfaceEnabled;
return false;
@@ -141,7 +175,7 @@ public abstract class PluginBase {
}
public boolean isFragmentVisible() {
- if (pluginDescription.alwayVisible)
+ if (pluginDescription.alwaysVisible)
return true;
if (pluginDescription.neverVisible)
return false;
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java
index 1634fc672d..5882c5870c 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginDescription.java
@@ -3,7 +3,7 @@ package info.nightscout.androidaps.interfaces;
public class PluginDescription {
PluginType mainType = PluginType.GENERAL;
String fragmentClass = null;
- public boolean alwayVisible = false;
+ public boolean alwaysVisible = false;
public boolean neverVisible = false;
public boolean alwaysEnabled = false;
boolean showInList = true;
@@ -11,7 +11,6 @@ public class PluginDescription {
int shortName = -1;
int description = -1;
int preferencesId = -1;
- int advancedPreferencesId = -1;
public boolean enableByDefault = false;
public boolean visibleByDefault = false;
@@ -30,8 +29,8 @@ public class PluginDescription {
return this;
}
- public PluginDescription alwayVisible(boolean alwayVisible) {
- this.alwayVisible = alwayVisible;
+ public PluginDescription alwaysVisible(boolean alwayVisible) {
+ this.alwaysVisible = alwayVisible;
return this;
}
@@ -60,11 +59,6 @@ public class PluginDescription {
return this;
}
- public PluginDescription advancedPreferencesId(int advancedPreferencesId) {
- this.advancedPreferencesId = advancedPreferencesId;
- return this;
- }
-
public PluginDescription enableByDefault(boolean enableByDefault) {
this.enableByDefault = enableByDefault;
return this;
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
index e3b368fe86..482278e437 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/ProfileInterface.java
@@ -1,6 +1,6 @@
package info.nightscout.androidaps.interfaces;
-import android.support.annotation.Nullable;
+import androidx.annotation.Nullable;
import info.nightscout.androidaps.data.ProfileStore;
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
index 34221b203f..e4a02883e8 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpDescription.java
@@ -1,8 +1,8 @@
package info.nightscout.androidaps.interfaces;
-import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpCapability;
-import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpTempBasalType;
-import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
+import info.nightscout.androidaps.plugins.pump.common.defs.PumpCapability;
+import info.nightscout.androidaps.plugins.pump.common.defs.PumpTempBasalType;
+import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/**
* Created by mike on 08.12.2016.
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 614c6033d3..025f10076d 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PumpInterface.java
@@ -2,9 +2,15 @@ package info.nightscout.androidaps.interfaces;
import org.json.JSONObject;
+import java.util.List;
+
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
+import info.nightscout.androidaps.plugins.common.ManufacturerType;
+import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
+import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
+import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
/**
* Created by mike on 04.06.2016.
@@ -12,40 +18,64 @@ import info.nightscout.androidaps.data.PumpEnactResult;
public interface PumpInterface {
boolean isInitialized(); // true if pump status has been read and is ready to accept commands
+
boolean isSuspended(); // true if suspended (not delivering insulin)
+
boolean isBusy(); // if true pump is not ready to accept commands right now
+
boolean isConnected(); // true if BT connection is established
+
boolean isConnecting(); // true if BT connection is in progress
+
boolean isHandshakeInProgress(); // true if BT is connected but initial handshake is still in progress
+
void finishHandshaking(); // set initial handshake completed
void connect(String reason);
+
void disconnect(String reason);
+
void stopConnecting();
void getPumpStatus();
// Upload to pump new basal profile
PumpEnactResult setNewBasalProfile(Profile profile);
+
boolean isThisProfileSet(Profile profile);
long lastDataTime();
double getBaseBasalRate(); // base basal rate, not temp basal
+ double getReservoirLevel();
+
+ int getBatteryLevel(); // in percent as integer
+
PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo);
+
void stopBolusDelivering();
+
PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew);
+
PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew);
+
PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes);
+
//some pumps might set a very short temp close to 100% as cancelling a temp can be noisy
//when the cancel request is requested by the user (forced), the pump should always do a real cancel
PumpEnactResult cancelTempBasal(boolean enforceNew);
+
PumpEnactResult cancelExtendedBolus();
// Status to be passed to NS
JSONObject getJSONStatus(Profile profile, String profileName);
- String deviceID();
+
+ ManufacturerType manufacturer();
+
+ PumpType model();
+
+ String serialNumber();
// Pump capabilities
PumpDescription getPumpDescription();
@@ -57,4 +87,16 @@ public interface PumpInterface {
PumpEnactResult loadTDDs();
+ boolean canHandleDST();
+
+ List getCustomActions();
+
+ void executeCustomAction(CustomActionType customActionType);
+
+ /**
+ * This method will be called when time or Timezone changes, and pump driver can then do a specific action (for
+ * example update clock on pump).
+ */
+ void timeDateOrTimeZoneChanged();
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java
index f4514ad572..9d75382542 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/SensitivityInterface.java
@@ -1,7 +1,7 @@
package info.nightscout.androidaps.interfaces;
-import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
/**
* Created by mike on 24.06.2017.
diff --git a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
index dc437e04ab..43661b117a 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/TreatmentsInterface.java
@@ -5,12 +5,13 @@ import java.util.List;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
+import info.nightscout.androidaps.data.NonOverlappingIntervals;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
+import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.data.ProfileIntervals;
@@ -25,12 +26,13 @@ public interface TreatmentsInterface {
IobTotal getLastCalculationTreatments();
IobTotal getCalculationToTimeTreatments(long time);
IobTotal getLastCalculationTempBasals();
- IobTotal getCalculationToTimeTempBasals(long time, Profile profile);
+ IobTotal getCalculationToTimeTempBasals(long time);
MealData getMealData();
List getTreatmentsFromHistory();
List getTreatments5MinBackFromHistory(long time);
+ List getTreatmentsFromHistoryAfterTimestamp(long timestamp);
long getLastBolusTime();
// real basals (not faked by extended bolus)
@@ -42,7 +44,7 @@ public interface TreatmentsInterface {
// basal that can be faked by extended boluses
boolean isTempBasalInProgress();
TemporaryBasal getTempBasalFromHistory(long time);
- Intervals getTemporaryBasalsFromHistory();
+ NonOverlappingIntervals getTemporaryBasalsFromHistory();
boolean isInHistoryExtendedBoluslInProgress();
ExtendedBolus getExtendedBolusFromHistory(long time);
@@ -63,4 +65,4 @@ public interface TreatmentsInterface {
long oldestDataAvailable();
-}
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.java b/app/src/main/java/info/nightscout/androidaps/logging/L.java
index 0fde02f4ed..25b6750844 100644
--- a/app/src/main/java/info/nightscout/androidaps/logging/L.java
+++ b/app/src/main/java/info/nightscout/androidaps/logging/L.java
@@ -3,7 +3,7 @@ package info.nightscout.androidaps.logging;
import java.util.ArrayList;
import java.util.List;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.utils.SP;
public class L {
@@ -77,7 +77,9 @@ public class L {
public static final String CORE = "CORE";
public static final String AUTOSENS = "AUTOSENS";
+ public static final String AUTOMATION = "AUTOMATION";
public static final String EVENTS = "EVENTS";
+ public static final String GLUCOSE = "GLUCOSE";
public static final String BGSOURCE = "BGSOURCE";
public static final String OVERVIEW = "OVERVIEW";
public static final String NOTIFICATION = "NOTIFICATION";
@@ -86,6 +88,7 @@ public class L {
public static final String DATAFOOD = "DATAFOOD";
public static final String DATATREATMENTS = "DATATREATMENTS";
public static final String NSCLIENT = "NSCLIENT";
+ public static final String TIDEPOOL = "TIDEPOOL";
public static final String CONSTRAINTS = "CONSTRAINTS";
public static final String PUMP = "PUMP";
public static final String PUMPQUEUE = "PUMPQUEUE";
@@ -95,12 +98,16 @@ public class L {
public static final String PROFILE = "PROFILE";
public static final String CONFIGBUILDER = "CONFIGBUILDER";
public static final String UI = "UI";
+ public static final String LOCATION = "LOCATION";
+ public static final String SMS = "SMS";
private static void initialize() {
logElements = new ArrayList<>();
logElements.add(new LogElement(APS, true));
+ logElements.add(new LogElement(AUTOMATION, true));
logElements.add(new LogElement(AUTOSENS, false));
logElements.add(new LogElement(BGSOURCE, true));
+ logElements.add(new LogElement(GLUCOSE, false));
logElements.add(new LogElement(CONFIGBUILDER, false));
logElements.add(new LogElement(CONSTRAINTS, true));
logElements.add(new LogElement(CORE, true));
@@ -109,14 +116,17 @@ public class L {
logElements.add(new LogElement(DATASERVICE, true));
logElements.add(new LogElement(DATATREATMENTS, true));
logElements.add(new LogElement(EVENTS, false, true));
+ logElements.add(new LogElement(LOCATION, true));
logElements.add(new LogElement(NOTIFICATION, true));
logElements.add(new LogElement(NSCLIENT, true));
+ logElements.add(new LogElement(TIDEPOOL, true));
logElements.add(new LogElement(OVERVIEW, true));
logElements.add(new LogElement(PROFILE, true));
logElements.add(new LogElement(PUMP, true));
logElements.add(new LogElement(PUMPBTCOMM, false));
logElements.add(new LogElement(PUMPCOMM, true));
logElements.add(new LogElement(PUMPQUEUE, true));
+ logElements.add(new LogElement(SMS, true));
logElements.add(new LogElement(UI, true));
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
deleted file mode 100644
index a71b447d82..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsFragment.java
+++ /dev/null
@@ -1,252 +0,0 @@
-package info.nightscout.androidaps.plugins.Actions;
-
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.support.v4.app.FragmentManager;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.activities.HistoryBrowseActivity;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.activities.TDDStatsActivity;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventInitializationChanged;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.Actions.dialogs.FillDialog;
-import info.nightscout.androidaps.plugins.Actions.dialogs.NewExtendedBolusDialog;
-import info.nightscout.androidaps.plugins.Actions.dialogs.NewTempBasalDialog;
-import info.nightscout.androidaps.plugins.Careportal.CareportalFragment;
-import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
-import info.nightscout.androidaps.plugins.Careportal.OptionsToShow;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.SingleClickButton;
-
-/**
- * A simple {@link Fragment} subclass.
- */
-public class ActionsFragment extends SubscriberFragment implements View.OnClickListener {
-
- static ActionsPlugin actionsPlugin = new ActionsPlugin();
-
- static public ActionsPlugin getPlugin() {
- return actionsPlugin;
- }
-
- SingleClickButton profileSwitch;
- SingleClickButton tempTarget;
- SingleClickButton extendedBolus;
- SingleClickButton extendedBolusCancel;
- SingleClickButton tempBasal;
- SingleClickButton tempBasalCancel;
- SingleClickButton fill;
- SingleClickButton tddStats;
- SingleClickButton history;
-
- public ActionsFragment() {
- super();
- }
-
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.actions_fragment, container, false);
-
- profileSwitch = (SingleClickButton) view.findViewById(R.id.actions_profileswitch);
- tempTarget = (SingleClickButton) view.findViewById(R.id.actions_temptarget);
- extendedBolus = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus);
- extendedBolusCancel = (SingleClickButton) view.findViewById(R.id.actions_extendedbolus_cancel);
- tempBasal = (SingleClickButton) view.findViewById(R.id.actions_settempbasal);
- tempBasalCancel = (SingleClickButton) view.findViewById(R.id.actions_canceltempbasal);
- fill = (SingleClickButton) view.findViewById(R.id.actions_fill);
- tddStats = view.findViewById(R.id.actions_tddstats);
- history = view.findViewById(R.id.actions_historybrowser);
-
- profileSwitch.setOnClickListener(this);
- tempTarget.setOnClickListener(this);
- extendedBolus.setOnClickListener(this);
- extendedBolusCancel.setOnClickListener(this);
- tempBasal.setOnClickListener(this);
- tempBasalCancel.setOnClickListener(this);
- fill.setOnClickListener(this);
- history.setOnClickListener(this);
- tddStats.setOnClickListener(this);
-
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
- profileSwitch.setVisibility(View.VISIBLE);
- } else {
- profileSwitch.setVisibility(View.GONE);
- }
-
- if (ProfileFunctions.getInstance().getProfile() == null) {
- tempTarget.setVisibility(View.GONE);
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.GONE);
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.GONE);
- fill.setVisibility(View.GONE);
- return;
- }
-
- final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease()
- && pump.getPumpDescription().isSetBasalProfileCapable;
-
- if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended())
- profileSwitch.setVisibility(View.GONE);
- else
- profileSwitch.setVisibility(View.VISIBLE);
-
- if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.GONE);
- } else {
- ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
- if (activeExtendedBolus != null) {
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.VISIBLE);
- extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
- } else {
- extendedBolus.setVisibility(View.VISIBLE);
- extendedBolusCancel.setVisibility(View.GONE);
- }
- }
-
-
- if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.GONE);
- } else {
- final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (activeTemp != null) {
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.VISIBLE);
- tempBasalCancel.setText(MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort());
- } else {
- tempBasal.setVisibility(View.VISIBLE);
- tempBasalCancel.setVisibility(View.GONE);
- }
- }
-
- if (!pump.getPumpDescription().isRefillingCapable || !pump.isInitialized() || pump.isSuspended())
- fill.setVisibility(View.GONE);
- else
- fill.setVisibility(View.VISIBLE);
-
- if (!Config.APS)
- tempTarget.setVisibility(View.GONE);
- else
- tempTarget.setVisibility(View.VISIBLE);
-
- if (!ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().supportsTDDs) tddStats.setVisibility(View.GONE);
- else tddStats.setVisibility(View.VISIBLE);
- }
- });
- }
-
-
- @Override
- public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
- switch (view.getId()) {
- case R.id.actions_profileswitch:
- NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
- final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH;
- profileswitch.executeProfileSwitch = true;
- newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
- newDialog.show(manager, "NewNSTreatmentDialog");
- break;
- case R.id.actions_temptarget:
- NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
- final OptionsToShow temptarget = CareportalFragment.TEMPTARGET;
- temptarget.executeTempTarget = true;
- newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
- newTTDialog.show(manager, "NewNSTreatmentDialog");
- break;
- case R.id.actions_extendedbolus:
- NewExtendedBolusDialog newExtendedDialog = new NewExtendedBolusDialog();
- newExtendedDialog.show(manager, "NewExtendedDialog");
- break;
- case R.id.actions_extendedbolus_cancel:
- if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(null);
- FabricPrivacy.getInstance().logCustom(new CustomEvent("CancelExtended"));
- }
- break;
- case R.id.actions_canceltempbasal:
- if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null);
- FabricPrivacy.getInstance().logCustom(new CustomEvent("CancelTemp"));
- }
- break;
- case R.id.actions_settempbasal:
- NewTempBasalDialog newTempDialog = new NewTempBasalDialog();
- newTempDialog.show(manager, "NewTempDialog");
- break;
- case R.id.actions_fill:
- FillDialog fillDialog = new FillDialog();
- fillDialog.show(manager, "FillDialog");
- break;
- case R.id.actions_historybrowser:
- startActivity(new Intent(getContext(), HistoryBrowseActivity.class));
- break;
- case R.id.actions_tddstats:
- startActivity(new Intent(getContext(), TDDStatsActivity.class));
- break;
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
deleted file mode 100644
index ff6275c9c9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Actions/ActionsPlugin.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package info.nightscout.androidaps.plugins.Actions;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-
-/**
- * Created by mike on 05.11.2016.
- */
-
-public class ActionsPlugin extends PluginBase {
-
- public ActionsPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(ActionsFragment.class.getName())
- .pluginName(R.string.actions)
- .shortName(R.string.actions_shortname)
- .description(R.string.description_actions)
- );
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Common/SubscriberFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/Common/SubscriberFragment.java
deleted file mode 100644
index fabd83f0ea..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Common/SubscriberFragment.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package info.nightscout.androidaps.plugins.Common;
-
-import android.support.v4.app.Fragment;
-
-import butterknife.Unbinder;
-import info.nightscout.androidaps.MainApp;
-
-abstract public class SubscriberFragment extends Fragment {
- protected Unbinder unbinder;
-
- @Override
- public void onPause() {
- super.onPause();
- MainApp.bus().unregister(this);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- MainApp.bus().register(this);
- updateGUI();
- }
-
- @Override public synchronized void onDestroyView() {
- super.onDestroyView();
- if (unbinder != null)
- unbinder.unbind();
- }
-
-
- protected abstract void updateGUI();
-}
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
deleted file mode 100644
index 3df78c9a28..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ConfigBuilderFragment.java
+++ /dev/null
@@ -1,286 +0,0 @@
-package info.nightscout.androidaps.plugins.ConfigBuilder;
-
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.support.annotation.NonNull;
-import android.support.annotation.StringRes;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.ImageButton;
-import android.widget.LinearLayout;
-import android.widget.RadioButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import butterknife.Unbinder;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.activities.PreferencesActivity;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventConfigBuilderChange;
-import info.nightscout.androidaps.events.EventRefreshGui;
-import info.nightscout.androidaps.interfaces.APSInterface;
-import info.nightscout.androidaps.interfaces.BgSourceInterface;
-import info.nightscout.androidaps.interfaces.ConstraintsInterface;
-import info.nightscout.androidaps.interfaces.InsulinInterface;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.ProfileInterface;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.interfaces.SensitivityInterface;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.Insulin.InsulinOrefRapidActingPlugin;
-import info.nightscout.androidaps.plugins.ProfileNS.NSProfilePlugin;
-import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.Sensitivity.SensitivityOref0Plugin;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.PasswordProtection;
-
-
-public class ConfigBuilderFragment extends SubscriberFragment {
-
- private List pluginViewHolders = new ArrayList<>();
-
- @BindView(R.id.categories)
- LinearLayout categories;
-
- @BindView(R.id.main_layout)
- ScrollView mainLayout;
- @BindView(R.id.unlock)
- Button unlock;
-
- @Override
- public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.configbuilder_fragment, container, false);
- unbinder = ButterKnife.bind(this, view);
-
- if (PasswordProtection.isLocked("settings_password"))
- mainLayout.setVisibility(View.GONE);
- else unlock.setVisibility(View.GONE);
-
- createViews();
-
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @OnClick(R.id.unlock)
- void onClickUnlock() {
- PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", () -> {
- mainLayout.setVisibility(View.VISIBLE);
- unlock.setVisibility(View.GONE);
- }, null);
- }
-
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- for (PluginViewHolder pluginViewHolder : pluginViewHolders) pluginViewHolder.unbind();
- pluginViewHolders.clear();
- }
-
- @Override
- protected void updateGUI() {
- for (PluginViewHolder pluginViewHolder : pluginViewHolders) pluginViewHolder.update();
- }
-
- private void createViews() {
- createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface.class, PluginType.PROFILE));
- createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface.class, PluginType.INSULIN));
- createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface.class, PluginType.BGSOURCE));
- createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, MainApp.getSpecificPluginsVisibleInList(PluginType.PUMP));
- createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, MainApp.getSpecificPluginsVisibleInListByInterface(SensitivityInterface.class, PluginType.SENSITIVITY));
- createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, MainApp.getSpecificPluginsVisibleInList(PluginType.APS));
- createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, MainApp.getSpecificPluginsVisibleInList(PluginType.LOOP));
- createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, MainApp.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface.class, PluginType.CONSTRAINTS));
- createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, MainApp.getSpecificPluginsVisibleInList(PluginType.TREATMENT));
- createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, MainApp.getSpecificPluginsVisibleInList(PluginType.GENERAL));
- }
-
- private void createViewsForPlugins(@StringRes int title, @StringRes int description, PluginType pluginType, List plugins) {
- if (plugins.size() == 0) return;
- LinearLayout parent = (LinearLayout) getLayoutInflater().inflate(R.layout.configbuilder_single_category, null);
- ((TextView) parent.findViewById(R.id.category_title)).setText(MainApp.gs(title));
- ((TextView) parent.findViewById(R.id.category_description)).setText(MainApp.gs(description));
- LinearLayout pluginContainer = parent.findViewById(R.id.category_plugins);
- for (PluginBase plugin: plugins) {
- PluginViewHolder pluginViewHolder = new PluginViewHolder(pluginType, plugin);
- pluginContainer.addView(pluginViewHolder.getBaseView());
- pluginViewHolders.add(pluginViewHolder);
- }
- categories.addView(parent);
- }
-
- private boolean areMultipleSelectionsAllowed(PluginType type) {
- return type == PluginType.GENERAL || type == PluginType.CONSTRAINTS ||type == PluginType.LOOP;
- }
-
- public static void processOnEnabledCategoryChanged(PluginBase changedPlugin, PluginType type) {
- ArrayList pluginsInCategory = null;
- switch (type) {
- // Multiple selection allowed
- case GENERAL:
- case CONSTRAINTS:
- case LOOP:
- break;
- // Single selection allowed
- case INSULIN:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(InsulinInterface.class);
- break;
- case SENSITIVITY:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(SensitivityInterface.class);
- break;
- case APS:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(APSInterface.class);
- break;
- case PROFILE:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(ProfileInterface.class);
- break;
- case BGSOURCE:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(BgSourceInterface.class);
- break;
- case TREATMENT:
- case PUMP:
- pluginsInCategory = MainApp.getSpecificPluginsListByInterface(PumpInterface.class);
- break;
- }
- if (pluginsInCategory != null) {
- boolean newSelection = changedPlugin.isEnabled(type);
- if (newSelection) { // new plugin selected -> disable others
- for (PluginBase p : pluginsInCategory) {
- if (p.getName().equals(changedPlugin.getName())) {
- // this is new selected
- } else {
- p.setPluginEnabled(type, false);
- p.setFragmentVisible(type, false);
- }
- }
- } else { // enable first plugin in list
- if (type == PluginType.PUMP)
- VirtualPumpPlugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.INSULIN)
- InsulinOrefRapidActingPlugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.SENSITIVITY)
- SensitivityOref0Plugin.getPlugin().setPluginEnabled(type, true);
- else if (type == PluginType.PROFILE)
- NSProfilePlugin.getPlugin().setPluginEnabled(type, true);
- else
- pluginsInCategory.get(0).setPluginEnabled(type, true);
- }
- }
- }
-
- public class PluginViewHolder {
-
- private Unbinder unbinder;
- private PluginType pluginType;
- private PluginBase plugin;
-
- LinearLayout baseView;
- @BindView(R.id.plugin_enabled_exclusive)
- RadioButton enabledExclusive;
- @BindView(R.id.plugin_enabled_inclusive)
- CheckBox enabledInclusive;
- @BindView(R.id.plugin_name)
- TextView pluginName;
- @BindView(R.id.plugin_description)
- TextView pluginDescription;
- @BindView(R.id.plugin_preferences)
- ImageButton pluginPreferences;
- @BindView(R.id.plugin_visibility)
- CheckBox pluginVisibility;
-
- public PluginViewHolder(PluginType pluginType, PluginBase plugin) {
- this.pluginType = pluginType;
- this.plugin = plugin;
- baseView = (LinearLayout) getLayoutInflater().inflate(R.layout.configbuilder_single_plugin, null);
- unbinder = ButterKnife.bind(this, baseView);
- update();
- }
-
- public LinearLayout getBaseView() {
- return baseView;
- }
-
- public void update() {
- enabledExclusive.setVisibility(areMultipleSelectionsAllowed(pluginType) ? View.GONE : View.VISIBLE);
- enabledInclusive.setVisibility(areMultipleSelectionsAllowed(pluginType) ? View.VISIBLE : View.GONE);
- enabledExclusive.setChecked(plugin.isEnabled(pluginType));
- enabledInclusive.setChecked(plugin.isEnabled(pluginType));
- enabledInclusive.setEnabled(!plugin.pluginDescription.alwaysEnabled);
- enabledExclusive.setEnabled(!plugin.pluginDescription.alwaysEnabled);
- pluginName.setText(plugin.getName());
- if (plugin.getDescription() == null) pluginDescription.setVisibility(View.GONE);
- else {
- pluginDescription.setVisibility(View.VISIBLE);
- pluginDescription.setText(plugin.getDescription());
- }
- pluginPreferences.setVisibility(plugin.getPreferencesId() == -1 || !plugin.isEnabled(pluginType) ? View.INVISIBLE : View.VISIBLE);
- pluginVisibility.setVisibility(plugin.hasFragment() ? View.VISIBLE : View.INVISIBLE);
- pluginVisibility.setEnabled(!(plugin.pluginDescription.neverVisible || plugin.pluginDescription.alwayVisible) && plugin.isEnabled(pluginType));
- pluginVisibility.setChecked(plugin.isFragmentVisible());
- }
-
- @OnClick(R.id.plugin_visibility)
- void onVisibilityChanged() {
- plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked());
- ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxVisible");
- MainApp.bus().post(new EventRefreshGui());
- ConfigBuilderPlugin.getPlugin().logPluginStatus();
- }
-
- @OnClick({R.id.plugin_enabled_exclusive, R.id.plugin_enabled_inclusive})
- void onEnabledChanged() {
- plugin.switchAllowed(new PluginSwitcher(), getActivity());
- }
-
- @OnClick(R.id.plugin_preferences)
- void onPluginPreferencesClicked() {
- PasswordProtection.QueryPassword(getContext(), R.string.settings_password, "settings_password", () -> {
- Intent i = new Intent(getContext(), PreferencesActivity.class);
- i.putExtra("id", plugin.getPreferencesId());
- startActivity(i);
- }, null);
- }
-
- public void unbind() {
- unbinder.unbind();
- }
-
- public class PluginSwitcher {
- public void invoke() {
- boolean enabled = enabledExclusive.getVisibility() == View.VISIBLE ? enabledExclusive.isChecked() : enabledInclusive.isChecked();
- plugin.setPluginEnabled(pluginType, enabled);
- plugin.setFragmentVisible(pluginType, enabled);
- processOnEnabledCategoryChanged(plugin, pluginType);
- updateGUI();
- ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled");
- MainApp.bus().post(new EventRefreshGui());
- MainApp.bus().post(new EventConfigBuilderChange());
- ConfigBuilderPlugin.getPlugin().logPluginStatus();
- FabricPrivacy.getInstance().logCustom(new CustomEvent("ConfigurationChange"));
- }
-
- public void cancel(){
- updateGUI();
- }
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java
deleted file mode 100644
index 9b4e1d0a28..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/DetailedBolusInfoStorage.java
+++ /dev/null
@@ -1,44 +0,0 @@
-package info.nightscout.androidaps.plugins.ConfigBuilder;
-
-import android.support.annotation.Nullable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.logging.L;
-
-/**
- * Created by mike on 08.08.2017.
- */
-
-public class DetailedBolusInfoStorage {
- private static Logger log = LoggerFactory.getLogger(L.PUMP);
- private static List store = new ArrayList<>();
-
- public static synchronized void add(DetailedBolusInfo detailedBolusInfo) {
- log.debug("Stored bolus info: " + detailedBolusInfo);
- store.add(detailedBolusInfo);
- }
-
- @Nullable
- public static synchronized DetailedBolusInfo findDetailedBolusInfo(long bolustime) {
- DetailedBolusInfo found = null;
- for (int i = 0; i < store.size(); i++) {
- long infoTime = store.get(i).date;
- if (L.isEnabled(L.PUMP))
- log.debug("Existing bolus info: " + store.get(i));
- if (bolustime > infoTime - 60 * 1000 && bolustime < infoTime + 60 * 1000) {
- found = store.get(i);
- if (L.isEnabled(L.PUMP))
- log.debug("Using & removing bolus info: " + store.get(i));
- store.remove(i);
- break;
- }
- }
- return found;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ProfileFunctions.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ProfileFunctions.java
deleted file mode 100644
index 312c0cd9ae..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConfigBuilder/ProfileFunctions.java
+++ /dev/null
@@ -1,142 +0,0 @@
-package info.nightscout.androidaps.plugins.ConfigBuilder;
-
-import android.content.Intent;
-import android.support.annotation.Nullable;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.BuildConfig;
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileStore;
-import info.nightscout.androidaps.db.ProfileSwitch;
-import info.nightscout.androidaps.events.EventNewBasalProfile;
-import info.nightscout.androidaps.events.EventProfileSwitchChange;
-import info.nightscout.androidaps.interfaces.ProfileInterface;
-import info.nightscout.androidaps.interfaces.TreatmentsInterface;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Overview.Dialogs.ErrorHelperActivity;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.utils.FabricPrivacy;
-
-public class ProfileFunctions {
- private static Logger log = LoggerFactory.getLogger(L.PROFILE);
-
- private static ProfileFunctions profileFunctions = null;
-
- public static ProfileFunctions getInstance() {
- if (profileFunctions == null)
- profileFunctions = new ProfileFunctions();
- return profileFunctions;
- }
-
- static {
- ProfileFunctions.getInstance(); // register to bus at start
- }
-
- ProfileFunctions() {
- MainApp.bus().register(this);
- }
-
- @Subscribe
- public void onProfileSwitch(EventProfileSwitchChange ignored) {
- if (L.isEnabled(L.PROFILE))
- log.debug("onProfileSwitch");
- ConfigBuilderPlugin.getPlugin().getCommandQueue().setProfile(getProfile(), new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
- i.putExtra("soundid", R.raw.boluserror);
- i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.failedupdatebasalprofile));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
- }
- MainApp.bus().post(new EventNewBasalProfile());
- }
- });
- }
-
- public String getProfileName() {
- return getProfileName(System.currentTimeMillis());
- }
-
- public String getProfileName(boolean customized) {
- return getProfileName(System.currentTimeMillis(), customized);
- }
-
- public String getProfileName(long time) {
- return getProfileName(time, true);
- }
-
- public String getProfileName(long time, boolean customized) {
- TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
- ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
-
- ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
- if (profileSwitch != null) {
- if (profileSwitch.profileJson != null) {
- return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
- } else {
- ProfileStore profileStore = activeProfile.getProfile();
- if (profileStore != null) {
- Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
- if (profile != null)
- return profileSwitch.profileName;
- }
- }
- }
- return MainApp.gs(R.string.noprofileselected);
- }
-
- public boolean isProfileValid(String from) {
- return getProfile() != null && getProfile().isValid(from);
- }
-
- @Nullable
- public Profile getProfile() {
- return getProfile(System.currentTimeMillis());
- }
-
- public String getProfileUnits() {
- Profile profile = getProfile();
- return profile != null ? profile.getUnits() : Constants.MGDL;
- }
-
- @Nullable
- public Profile getProfile(long time) {
- TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
- ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
-
- //log.debug("Profile for: " + new Date(time).toLocaleString() + " : " + getProfileName(time));
- ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
- if (profileSwitch != null) {
- if (profileSwitch.profileJson != null) {
- return profileSwitch.getProfileObject();
- } else if (activeProfile.getProfile() != null) {
- Profile profile = activeProfile.getProfile().getSpecificProfile(profileSwitch.profileName);
- if (profile != null)
- return profile;
- }
- }
- if (activeTreatments.getProfileSwitchesFromHistory().size() > 0) {
- FabricPrivacy.getInstance().logCustom(new CustomEvent("CatchedError")
- .putCustomAttribute("buildversion", BuildConfig.BUILDVERSION)
- .putCustomAttribute("version", BuildConfig.VERSION)
- .putCustomAttribute("time", time)
- .putCustomAttribute("getProfileSwitchesFromHistory", activeTreatments.getProfileSwitchesFromHistory().toString())
- );
- }
- log.error("getProfile at the end: returning null");
- return null;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java
deleted file mode 100644
index 3dcec0920f..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesFragment.java
+++ /dev/null
@@ -1,211 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import android.os.Looper;
-import android.support.annotation.NonNull;
-import android.support.v7.widget.CardView;
-import android.support.v7.widget.LinearLayoutManager;
-import android.support.v7.widget.LinearSmoothScroller;
-import android.support.v7.widget.RecyclerView;
-import android.text.Html;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import java.util.Date;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
-import info.nightscout.utils.FabricPrivacy;
-
-public class ObjectivesFragment extends SubscriberFragment {
- RecyclerView recyclerView;
- CheckBox enableFake;
- TextView reset;
- ObjectivesAdapter objectivesAdapter = new ObjectivesAdapter();
- Handler handler = new Handler(Looper.getMainLooper());
-
- private Runnable objectiveUpdater = new Runnable() {
- @Override
- public void run() {
- handler.postDelayed(this, 60 * 1000);
- updateGUI();
- }
- };
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.objectives_fragment, container, false);
-
- recyclerView = view.findViewById(R.id.objectives_recyclerview);
- recyclerView.setLayoutManager(new LinearLayoutManager(view.getContext()));
- recyclerView.setAdapter(objectivesAdapter);
- enableFake = view.findViewById(R.id.objectives_fake);
- reset = view.findViewById(R.id.objectives_reset);
- enableFake.setOnClickListener(v -> updateGUI());
- reset.setOnClickListener(v -> {
- ObjectivesPlugin.getPlugin().reset();
- ObjectivesPlugin.getPlugin().saveProgress();
- recyclerView.getAdapter().notifyDataSetChanged();
- scrollToCurrentObjective();
- });
- scrollToCurrentObjective();
- startUpdateTimer();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Override
- public synchronized void onDestroyView() {
- super.onDestroyView();
- handler.removeCallbacks(objectiveUpdater);
- }
-
- private void startUpdateTimer() {
- handler.removeCallbacks(objectiveUpdater);
- for (Objective objective : ObjectivesPlugin.getPlugin().getObjectives()) {
- if (objective.isStarted() && !objective.isAccomplished()) {
- long timeTillNextMinute = (System.currentTimeMillis() - objective.getStartedOn().getTime()) % (60 * 1000);
- handler.postDelayed(objectiveUpdater, timeTillNextMinute);
- break;
- }
- }
- }
-
- private void scrollToCurrentObjective() {
- for (int i = 0; i < ObjectivesPlugin.getPlugin().getObjectives().size(); i++) {
- Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(i);
- if (!objective.isStarted() || !objective.isAccomplished()) {
- RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(getContext()) {
- @Override
- protected int getVerticalSnapPreference() {
- return LinearSmoothScroller.SNAP_TO_START;
- }
-
- @Override
- protected int calculateTimeForScrolling(int dx) {
- return super.calculateTimeForScrolling(dx) * 4;
- }
- };
- smoothScroller.setTargetPosition(i);
- recyclerView.getLayoutManager().startSmoothScroll(smoothScroller);
- break;
- }
- }
- }
-
- private class ObjectivesAdapter extends RecyclerView.Adapter {
-
- @NonNull
- @Override
- public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
- return new ViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.objectives_item, parent, false));
- }
-
- @Override
- public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
- Objective objective = ObjectivesPlugin.getPlugin().getObjectives().get(position);
- holder.title.setText(MainApp.gs(R.string.nth_objective, position + 1));
- if (objective.getObjective() != 0) {
- holder.objective.setVisibility(View.VISIBLE);
- holder.objective.setText(MainApp.gs(objective.getObjective()));
- } else holder.objective.setVisibility(View.GONE);
- if (objective.getGate() != 0) {
- holder.gate.setVisibility(View.VISIBLE);
- holder.gate.setText(MainApp.gs(objective.getGate()));
- } else holder.gate.setVisibility(View.GONE);
- if (!objective.isStarted()) {
- holder.gate.setTextColor(0xFFFFFFFF);
- holder.verify.setVisibility(View.GONE);
- holder.progress.setVisibility(View.GONE);
- if (position == 0 || ObjectivesPlugin.getPlugin().getObjectives().get(position - 1).isAccomplished())
- holder.start.setVisibility(View.VISIBLE);
- else holder.start.setVisibility(View.GONE);
- } else if (objective.isAccomplished()) {
- holder.gate.setTextColor(0xFF4CAF50);
- holder.verify.setVisibility(View.GONE);
- holder.progress.setVisibility(View.GONE);
- holder.start.setVisibility(View.GONE);
- } else if (objective.isStarted()) {
- holder.gate.setTextColor(0xFFFFFFFF);
- holder.verify.setVisibility(View.VISIBLE);
- holder.verify.setEnabled(objective.isCompleted() || enableFake.isChecked());
- holder.start.setVisibility(View.GONE);
- holder.progress.setVisibility(View.VISIBLE);
- holder.progress.removeAllViews();
- for (Objective.Task task : objective.getTasks()) {
- if (task.shouldBeIgnored()) continue;
- TextView textView = new TextView(holder.progress.getContext());
- textView.setTextColor(0xFFFFFFFF);
- String basicHTML = "%2$s: %3$s";
- String formattedHTML = String.format(basicHTML, task.isCompleted() ? "#4CAF50" : "#FF9800", MainApp.gs(task.getTask()), task.getProgress());
- textView.setText(Html.fromHtml(formattedHTML));
- holder.progress.addView(textView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
- }
- }
- holder.verify.setOnClickListener((view) -> {
- objective.setAccomplishedOn(new Date());
- notifyDataSetChanged();
- scrollToCurrentObjective();
- startUpdateTimer();
- });
- holder.start.setOnClickListener((view) -> {
- objective.setStartedOn(new Date());
- notifyDataSetChanged();
- scrollToCurrentObjective();
- startUpdateTimer();
- });
- }
-
- @Override
- public int getItemCount() {
- return ObjectivesPlugin.getPlugin().getObjectives().size();
- }
-
- public class ViewHolder extends RecyclerView.ViewHolder {
-
- public CardView cardView;
- public TextView title;
- public TextView objective;
- public TextView gate;
- public LinearLayout progress;
- public Button verify;
- public Button start;
-
- public ViewHolder(View itemView) {
- super(itemView);
- cardView = (CardView) itemView;
- title = itemView.findViewById(R.id.objective_title);
- objective = itemView.findViewById(R.id.objective_objective);
- gate = itemView.findViewById(R.id.objective_gate);
- progress = itemView.findViewById(R.id.objective_progress);
- verify = itemView.findViewById(R.id.objective_verify);
- start = itemView.findViewById(R.id.objective_start);
- }
- }
- }
-
- @Override
- public void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- objectivesAdapter.notifyDataSetChanged();
- });
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java
deleted file mode 100644
index cc50189346..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/ObjectivesPlugin.java
+++ /dev/null
@@ -1,164 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.interfaces.ConstraintsInterface;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.events.EventObjectivesSaved;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective1;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective2;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective3;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective4;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective5;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective6;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective7;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives.Objective8;
-import info.nightscout.utils.SP;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class ObjectivesPlugin extends PluginBase implements ConstraintsInterface {
- private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
-
- private static ObjectivesPlugin objectivesPlugin;
-
- public List objectives = new ArrayList<>();
- public boolean bgIsAvailableInNS = false;
- public boolean pumpStatusIsAvailableInNS = false;
- public Integer manualEnacts = 0;
-
- public static ObjectivesPlugin getPlugin() {
- if (objectivesPlugin == null) {
- objectivesPlugin = new ObjectivesPlugin();
- }
- return objectivesPlugin;
- }
-
- private ObjectivesPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.CONSTRAINTS)
- .fragmentClass(ObjectivesFragment.class.getName())
- .alwaysEnabled(!Config.NSCLIENT)
- .showInList(!Config.NSCLIENT)
- .pluginName(R.string.objectives)
- .shortName(R.string.objectives_shortname)
- .description(R.string.description_objectives)
- );
- setupObjectives();
- loadProgress();
- }
-
- @Override
- public boolean specialEnableCondition() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- return pump == null || pump.getPumpDescription().isTempBasalCapable;
- }
-
- private void setupObjectives() {
- objectives.add(new Objective1());
- objectives.add(new Objective2());
- objectives.add(new Objective3());
- objectives.add(new Objective4());
- objectives.add(new Objective5());
- objectives.add(new Objective6());
- objectives.add(new Objective7());
- objectives.add(new Objective8());
- }
-
- public void reset() {
- for (Objective objective : objectives) {
- objective.setStartedOn(null);
- objective.setAccomplishedOn(null);
- }
- bgIsAvailableInNS = false;
- pumpStatusIsAvailableInNS = false;
- manualEnacts = 0;
- saveProgress();
- }
-
- public void saveProgress() {
- SP.putBoolean("Objectives" + "bgIsAvailableInNS", bgIsAvailableInNS);
- SP.putBoolean("Objectives" + "pumpStatusIsAvailableInNS", pumpStatusIsAvailableInNS);
- SP.putString("Objectives" + "manualEnacts", Integer.toString(manualEnacts));
- if (L.isEnabled(L.CONSTRAINTS))
- log.debug("Objectives stored");
- MainApp.bus().post(new EventObjectivesSaved());
- }
-
- private void loadProgress() {
- bgIsAvailableInNS = SP.getBoolean("Objectives" + "bgIsAvailableInNS", false);
- pumpStatusIsAvailableInNS = SP.getBoolean("Objectives" + "pumpStatusIsAvailableInNS", false);
- try {
- manualEnacts = SP.getInt("Objectives" + "manualEnacts", 0);
- } catch (Exception e) {
- log.error("Unhandled exception", e);
- }
- if (L.isEnabled(L.CONSTRAINTS))
- log.debug("Objectives loaded");
- }
-
- public List getObjectives() {
- return objectives;
- }
-
- /**
- * Constraints interface
- **/
- @Override
- public Constraint isLoopInvocationAllowed(Constraint value) {
- if (!objectives.get(0).isStarted())
- value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), 1), this);
- return value;
- }
-
- @Override
- public Constraint isClosedLoopAllowed(Constraint value) {
- if (!objectives.get(3).isStarted())
- value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), 4), this);
- return value;
- }
-
- @Override
- public Constraint isAutosensModeEnabled(Constraint value) {
- if (!objectives.get(5).isStarted())
- value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), 6), this);
- return value;
- }
-
- @Override
- public Constraint isAMAModeEnabled(Constraint value) {
- if (!objectives.get(6).isStarted())
- value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), 7), this);
- return value;
- }
-
- @Override
- public Constraint isSMBModeEnabled(Constraint value) {
- if (!objectives.get(7).isStarted())
- value.set(false, String.format(MainApp.gs(R.string.objectivenotstarted), 8), this);
- return value;
- }
-
- @Override
- public Constraint applyMaxIOBConstraints(Constraint maxIob) {
- if (objectives.get(3).isStarted() && !objectives.get(3).isAccomplished())
- maxIob.set(0d, String.format(MainApp.gs(R.string.objectivenotfinished), 4), this);
- return maxIob;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/events/EventObjectivesSaved.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/events/EventObjectivesSaved.java
deleted file mode 100644
index 1822368cf9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/events/EventObjectivesSaved.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.events;
-
-import info.nightscout.androidaps.events.Event;
-
-public class EventObjectivesSaved extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective.java
deleted file mode 100644
index 5127f64b34..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective.java
+++ /dev/null
@@ -1,141 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
-
-import android.support.annotation.StringRes;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.T;
-
-public abstract class Objective {
-
- private int number;
- @StringRes
- private int objective;
- @StringRes
- private int gate;
- private Date startedOn;
- private Date accomplishedOn;
- private List tasks = new ArrayList<>();
-
- public Objective(int number, @StringRes int objective, @StringRes int gate) {
- this.number = number;
- this.objective = objective;
- this.gate = gate;
- startedOn = new Date(SP.getLong("Objectives" + number + "started", 0L));
- if (startedOn.getTime() == 0L) startedOn = null;
- accomplishedOn = new Date(SP.getLong("Objectives" + number + "accomplished", 0L));
- if (accomplishedOn.getTime() == 0L) accomplishedOn = null;
- setupTasks(tasks);
- for (Task task : tasks) task.objective = this;
- }
-
- public boolean isCompleted() {
- for (Task task : tasks) {
- if (!task.shouldBeIgnored() && !task.isCompleted())
- return false;
- }
- return true;
- }
-
- public boolean isAccomplished() {
- return accomplishedOn != null;
- }
-
- public boolean isStarted() {
- return startedOn != null;
- }
-
- public Date getStartedOn() {
- return startedOn;
- }
-
- public int getObjective() {
- return objective;
- }
-
- public int getGate() {
- return gate;
- }
-
- public void setStartedOn(Date startedOn) {
- this.startedOn = startedOn;
- SP.putLong("Objectives" + number + "started", startedOn == null ? 0 : startedOn.getTime());
- }
-
- public void setAccomplishedOn(Date accomplishedOn) {
- this.accomplishedOn = accomplishedOn;
- SP.putLong("Objectives" + number + "accomplished", accomplishedOn == null ? 0 : accomplishedOn.getTime());
- }
-
- protected void setupTasks(List tasks) {
-
- }
-
- public List getTasks() {
- return tasks;
- }
-
- public abstract class Task {
- @StringRes
- private int task;
- private Objective objective;
-
- public Task(@StringRes int task) {
- this.task = task;
- }
-
- public int getTask() {
- return task;
- }
-
- protected Objective getObjective() {
- return objective;
- }
-
- public abstract boolean isCompleted();
-
- public String getProgress() {
- return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet);
- }
-
- public boolean shouldBeIgnored() {
- return false;
- }
- }
-
- public class MinimumDurationTask extends Task {
-
- private long minimumDuration;
-
- public MinimumDurationTask(long minimumDuration) {
- super(R.string.time_elapsed);
- this.minimumDuration = minimumDuration;
- }
-
- @Override
- public boolean isCompleted() {
- return getObjective().isStarted() && System.currentTimeMillis() - getObjective().getStartedOn().getTime() >= minimumDuration;
- }
-
- @Override
- public String getProgress() {
- return getDurationText(System.currentTimeMillis() - getObjective().getStartedOn().getTime())
- + " / " + getDurationText(minimumDuration);
- }
-
- private String getDurationText(long duration) {
- int days = (int) Math.floor((double) duration / T.days(1).msecs());
- int hours = (int) Math.floor((double) duration / T.hours(1).msecs());
- int minutes = (int) Math.floor((double) duration / T.mins(1).msecs());
- if (days > 0) return MainApp.gq(R.plurals.objective_days, days, days);
- else if (hours > 0) return MainApp.gq(R.plurals.objective_hours, hours, hours);
- else return MainApp.gq(R.plurals.objective_minutes, minutes, minutes);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective2.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective2.java
deleted file mode 100644
index ac5485f953..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective2.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
-
-import java.util.List;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
-import info.nightscout.utils.T;
-
-public class Objective2 extends Objective {
-
- public final int MANUAL_ENACTS_NEEDED = 20;
-
- public Objective2() {
- super(1, R.string.objectives_1_objective, R.string.objectives_1_gate);
- }
-
- @Override
- protected void setupTasks(List tasks) {
- tasks.add(new MinimumDurationTask(T.days(7).msecs()));
- tasks.add(new Task(R.string.objectives_manualenacts) {
- @Override
- public boolean isCompleted() {
- return ObjectivesPlugin.getPlugin().manualEnacts >= MANUAL_ENACTS_NEEDED;
- }
-
- @Override
- public String getProgress() {
- if (ObjectivesPlugin.getPlugin().manualEnacts >= MANUAL_ENACTS_NEEDED)
- return MainApp.gs(R.string.completed_well_done);
- else
- return ObjectivesPlugin.getPlugin().manualEnacts + " / " + MANUAL_ENACTS_NEEDED;
- }
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective3.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective3.java
deleted file mode 100644
index 8a84e3c83c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective3.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
-
-import info.nightscout.androidaps.R;
-
-public class Objective3 extends Objective {
-
- public Objective3() {
- super(2, R.string.objectives_2_objective, R.string.objectives_2_gate);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective6.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective6.java
deleted file mode 100644
index 7867b28e70..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective6.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
-
-import java.util.List;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.utils.T;
-
-public class Objective6 extends Objective {
-
- public Objective6() {
- super(5, R.string.objectives_5_objective, R.string.objectives_5_gate);
- }
-
- @Override
- protected void setupTasks(List tasks) {
- tasks.add(new MinimumDurationTask(T.days(7).msecs()));
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective7.java b/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective7.java
deleted file mode 100644
index 670cffe746..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ConstraintsObjectives/objectives/Objective7.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package info.nightscout.androidaps.plugins.ConstraintsObjectives.objectives;
-
-import java.util.List;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.utils.T;
-
-public class Objective7 extends Objective {
-
- public Objective7() {
- super(6, R.string.objectives_6_objective, 0);
- }
-
- @Override
- protected void setupTasks(List tasks) {
- tasks.add(new MinimumDurationTask(T.days(28).msecs()));
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java
deleted file mode 100644
index 2cb9b7ca4c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventAutosensCalculationFinished.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.IobCobCalculator.events;
-
-import info.nightscout.androidaps.events.Event;
-import info.nightscout.androidaps.events.EventLoop;
-
-/**
- * Created by mike on 30.04.2017.
- */
-
-public class EventAutosensCalculationFinished extends EventLoop {
- public Event cause;
-
- public EventAutosensCalculationFinished(Event cause) {
- this.cause = cause;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventIobCalculationProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventIobCalculationProgress.java
deleted file mode 100644
index 08f2747e60..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventIobCalculationProgress.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package info.nightscout.androidaps.plugins.IobCobCalculator.events;
-
-import info.nightscout.androidaps.events.Event;
-
-public class EventIobCalculationProgress extends Event {
- public String progress;
-
- public EventIobCalculationProgress(String progress) {
- this.progress = progress;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java
deleted file mode 100644
index 8814741099..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/IobCobCalculator/events/EventNewHistoryData.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package info.nightscout.androidaps.plugins.IobCobCalculator.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 26.04.2017.
- */
-
-public class EventNewHistoryData extends Event {
- public long time = 0;
-
- public EventNewHistoryData(long time) {
- this.time = time;
- }
-}
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
deleted file mode 100644
index 0c0e31fb03..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopFragment.java
+++ /dev/null
@@ -1,146 +0,0 @@
-package info.nightscout.androidaps.plugins.Loop;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.text.Html;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
-import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
-import info.nightscout.utils.FabricPrivacy;
-
-public class LoopFragment extends SubscriberFragment {
- @BindView(R.id.loop_run)
- Button runNowButton;
- @BindView(R.id.loop_lastrun)
- TextView lastRunView;
- @BindView(R.id.loop_lastenact)
- TextView lastEnactView;
- @BindView(R.id.loop_source)
- TextView sourceView;
- @BindView(R.id.loop_request)
- TextView requestView;
- @BindView(R.id.loop_constraintsprocessed)
- TextView constraintsProcessedView;
- @BindView(R.id.loop_constraints)
- TextView constraintsView;
- @BindView(R.id.loop_tbrsetbypump)
- TextView tbrSetByPumpView;
- @BindView(R.id.loop_smbsetbypump)
- TextView smbSetByPumpView;
-
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.loop_fragment, container, false);
- unbinder = ButterKnife.bind(this, view);
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
- return null;
- }
-
- @OnClick(R.id.loop_run)
- void onRunClick() {
- lastRunView.setText(MainApp.gs(R.string.executing));
- new Thread(() -> LoopPlugin.getPlugin().invoke("Loop button", true)).start();
- FabricPrivacy.getInstance().logCustom(new CustomEvent("Loop_Run"));
- }
-
- @Subscribe
- public void onStatusEvent(final EventLoopUpdateGui ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventLoopSetLastRunGui ev) {
- clearGUI();
- final Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> { synchronized (LoopFragment.this) { if (lastRunView != null) lastRunView.setText(ev.text); } });
- }
-
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- synchronized (LoopFragment.this) {
- if (!isBound()) return;
- LoopPlugin.LastRun lastRun = LoopPlugin.lastRun;
- if (lastRun != null) {
- requestView.setText(lastRun.request != null ? lastRun.request.toSpanned() : "");
- constraintsProcessedView.setText(lastRun.constraintsProcessed != null ? lastRun.constraintsProcessed.toSpanned() : "");
- sourceView.setText(lastRun.source != null ? lastRun.source : "");
- lastRunView.setText(lastRun.lastAPSRun != null && lastRun.lastAPSRun.getTime() != 0 ? lastRun.lastAPSRun.toLocaleString() : "");
- lastEnactView.setText(lastRun.lastEnact != null && lastRun.lastEnact.getTime() != 0 ? lastRun.lastEnact.toLocaleString() : "");
- tbrSetByPumpView.setText(lastRun.tbrSetByPump != null ? Html.fromHtml(lastRun.tbrSetByPump.toHtml()) : "");
- smbSetByPumpView.setText(lastRun.smbSetByPump != null ? Html.fromHtml(lastRun.smbSetByPump.toHtml()) : "");
-
- String constraints = "";
- if (lastRun.constraintsProcessed != null) {
- Constraint allConstraints = new Constraint<>(0d);
- if (lastRun.constraintsProcessed.rateConstraint != null)
- allConstraints.copyReasons(lastRun.constraintsProcessed.rateConstraint);
- if (lastRun.constraintsProcessed.smbConstraint != null)
- allConstraints.copyReasons(lastRun.constraintsProcessed.smbConstraint);
- constraints = allConstraints.getMostLimitedReasons();
- }
- constraintsView.setText(constraints);
- }
- }
- });
- }
-
- void clearGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- synchronized (LoopFragment.this) {
- if (isBound()) {
- requestView.setText("");
- constraintsProcessedView.setText("");
- sourceView.setText("");
- lastRunView.setText("");
- lastEnactView.setText("");
- tbrSetByPumpView.setText("");
- smbSetByPumpView.setText("");
- }
- }
- });
- }
-
- boolean isBound() {
- return requestView != null
- && constraintsProcessedView != null
- && sourceView != null
- && lastRunView != null
- && lastEnactView != null
- && tbrSetByPumpView != null
- && smbSetByPumpView != null
- && constraintsView != null
- && runNowButton != null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopSetLastRunGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopSetLastRunGui.java
deleted file mode 100644
index 1ef5dc4c94..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopSetLastRunGui.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.plugins.Loop.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventLoopSetLastRunGui extends EventUpdateGui {
- public String text = null;
-
- public EventLoopSetLastRunGui(String text) {
- this.text = text;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopUpdateGui.java
deleted file mode 100644
index d4417dbb12..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventLoopUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.Loop.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventLoopUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventNewOpenLoopNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventNewOpenLoopNotification.java
deleted file mode 100644
index 001d11661e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/events/EventNewOpenLoopNotification.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.Loop.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 07.08.2016.
- */
-public class EventNewOpenLoopNotification extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Maintenance/activities/LogSettingActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/Maintenance/activities/LogSettingActivity.java
deleted file mode 100644
index 7d21d561b9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Maintenance/activities/LogSettingActivity.java
+++ /dev/null
@@ -1,80 +0,0 @@
-package info.nightscout.androidaps.plugins.Maintenance.activities;
-
-import android.os.Bundle;
-import android.support.v7.app.AppCompatActivity;
-import android.view.View;
-import android.widget.CheckBox;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import java.util.List;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import butterknife.Unbinder;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-
-public class LogSettingActivity extends AppCompatActivity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_logsetting);
- ButterKnife.bind(this);
-
- createViewsForSettings(L.getLogElements());
- }
-
- private void createViewsForSettings(List elements) {
- if (elements.size() == 0) return;
- LinearLayout container = (LinearLayout) findViewById(R.id.logsettings_placeholder);
- container.removeAllViews();
- for (L.LogElement element : elements) {
- PluginViewHolder pluginViewHolder = new PluginViewHolder(element);
- container.addView(pluginViewHolder.getBaseView());
- }
- }
-
- @OnClick(R.id.logsettings_reset)
- public void onResetClick() {
- L.resetToDefaults();
- createViewsForSettings(L.getLogElements());
- }
-
- public class PluginViewHolder {
-
- private Unbinder unbinder;
- private L.LogElement element;
-
- LinearLayout baseView;
- @BindView(R.id.logsettings_description)
- TextView description;
- @BindView(R.id.logsettings_visibility)
- CheckBox enabled;
-
- public PluginViewHolder(L.LogElement element) {
- this.element = element;
- baseView = (LinearLayout) getLayoutInflater().inflate(R.layout.logsettings_item, null);
- unbinder = ButterKnife.bind(this, baseView);
-
- description.setText(element.name);
- enabled.setChecked(element.enabled);
- }
-
- public View getBaseView() {
- return baseView;
- }
-
- @OnClick(R.id.logsettings_visibility)
- void onEnagledChanged() {
- element.setEnabled(enabled.isChecked());
- }
-
- public void unbind() {
- unbinder.unbind();
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java
deleted file mode 100644
index 9eff2ca84c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/NSClientFragment.java
+++ /dev/null
@@ -1,169 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal;
-
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.graphics.Paint;
-import android.os.Bundle;
-import android.text.Html;
-import android.text.Spanned;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CheckBox;
-import android.widget.CompoundButton;
-import android.widget.ScrollView;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientNewLog;
-import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
-import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientUpdateGUI;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.SP;
-
-public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
- private TextView logTextView;
- private TextView queueTextView;
- private TextView urlTextView;
- private TextView statusTextView;
- private TextView clearlog;
- private TextView restart;
- private TextView delivernow;
- private TextView clearqueue;
- private TextView showqueue;
- private ScrollView logScrollview;
- private CheckBox autoscrollCheckbox;
- private CheckBox pausedCheckbox;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false);
-
- logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview);
- autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll);
- autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll);
- autoscrollCheckbox.setOnCheckedChangeListener(this);
- pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused);
- pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused);
- pausedCheckbox.setOnCheckedChangeListener(this);
- logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log);
- queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue);
- urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url);
- statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status);
-
- clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog);
- clearlog.setOnClickListener(this);
- clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- restart = (TextView) view.findViewById(R.id.nsclientinternal_restart);
- restart.setOnClickListener(this);
- restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow);
- delivernow.setOnClickListener(this);
- delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue);
- clearqueue.setOnClickListener(this);
- clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue);
- showqueue.setOnClickListener(this);
- showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
-
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.nsclientinternal_restart:
- MainApp.bus().post(new EventNSClientRestart());
- FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientRestart"));
- break;
- case R.id.nsclientinternal_delivernow:
- NSClientPlugin.getPlugin().resend("GUI");
- FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientDeliverNow"));
- break;
- case R.id.nsclientinternal_clearlog:
- NSClientPlugin.getPlugin().clearLog();
- break;
- case R.id.nsclientinternal_clearqueue:
- final Context context = getContext();
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
-
- builder.setTitle(MainApp.gs(R.string.confirmation));
- builder.setMessage("Clear queue? All data in queue will be lost!");
- builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- UploadQueue.clearQueue();
- updateGUI();
- FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientClearQueue"));
- }
- });
- builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
- builder.show();
- break;
- case R.id.nsclientinternal_showqueue:
- MainApp.bus().post(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList()));
- FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientShowQueue"));
- break;
- }
- }
-
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- switch (buttonView.getId()) {
- case R.id.nsclientinternal_paused:
- NSClientPlugin.getPlugin().pause(isChecked);
- updateGUI();
- FabricPrivacy.getInstance().logCustom(new CustomEvent("NSClientPause"));
- break;
- case R.id.nsclientinternal_autoscroll:
- SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked);
- NSClientPlugin.getPlugin().autoscroll = isChecked;
- updateGUI();
- break;
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventNSClientUpdateGUI ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- NSClientPlugin.getPlugin().updateLog();
- pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false));
- logTextView.setText(NSClientPlugin.getPlugin().textLog);
- if (NSClientPlugin.getPlugin().autoscroll) {
- logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
- }
- urlTextView.setText(NSClientPlugin.getPlugin().url());
- Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + "");
- queueTextView.setText(queuetext);
- statusTextView.setText(NSClientPlugin.getPlugin().status);
- });
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java
deleted file mode 100644
index 82b11a812d..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientNewLog.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.events;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 15.02.2017.
- */
-
-public class EventNSClientNewLog extends Event {
- public Date date = new Date();
- public String action;
- public String logText;
- public EventNSClientNewLog(String action, String logText) {
- this.action = action;
- this.logText = logText;
- }
-
- SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
-
- public StringBuilder toPreparedHtml() {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(timeFormat.format(date));
- stringBuilder.append(" ");
- stringBuilder.append(action);
- stringBuilder.append(" ");
- stringBuilder.append(logText);
- stringBuilder.append("
");
- return stringBuilder;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java
deleted file mode 100644
index b968878da8..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientRestart.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 15.02.2017.
- */
-
-public class EventNSClientRestart extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java
deleted file mode 100644
index 977c0e31fc..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientStatus.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 02.01.2016.
- */
-public class EventNSClientStatus extends Event {
- public String status = "";
-
- public EventNSClientStatus(String status) {
- this.status = status;
- }
-
- public EventNSClientStatus() {
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java
deleted file mode 100644
index dd78d2cd28..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/events/EventNSClientUpdateGUI.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 17.02.2017.
- */
-
-public class EventNSClientUpdateGUI extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java
deleted file mode 100644
index dd5d3330ab..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/AutoStartReceiver.java
+++ /dev/null
@@ -1,17 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-
-import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
-
-public class AutoStartReceiver extends BroadcastReceiver {
- public AutoStartReceiver() {
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- context.startService(new Intent(context, NSClientService.class));
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java
deleted file mode 100644
index a38ca842f9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/NSClientInternal/receivers/RestartReceiver.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package info.nightscout.androidaps.plugins.NSClientInternal.receivers;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.support.v4.content.WakefulBroadcastReceiver;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.plugins.NSClientInternal.events.EventNSClientRestart;
-import info.nightscout.androidaps.plugins.NSClientInternal.services.NSClientService;
-
-public class RestartReceiver extends WakefulBroadcastReceiver {
- public RestartReceiver() {
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
- startWakefulService(context, new Intent(context, NSClientService.class)
- .setAction(intent.getAction())
- .putExtras(intent));
-
- MainApp.bus().post(new EventNSClientRestart());
- completeWakefulIntent(intent);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java
deleted file mode 100644
index 1874816ddc..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAFragment.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.JSONFormatter;
-
-public class OpenAPSAMAFragment extends SubscriberFragment implements View.OnClickListener {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- Button run;
- TextView lastRunView;
- TextView glucoseStatusView;
- TextView currentTempView;
- TextView iobDataView;
- TextView profileView;
- TextView mealDataView;
- TextView autosensDataView;
- TextView resultView;
- TextView scriptdebugView;
- TextView requestView;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.openapsama_fragment, container, false);
-
- run = (Button) view.findViewById(R.id.openapsma_run);
- run.setOnClickListener(this);
- lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun);
- glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus);
- currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp);
- iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata);
- profileView = (TextView) view.findViewById(R.id.openapsma_profile);
- mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata);
- autosensDataView = (TextView) view.findViewById(R.id.openapsma_autosensdata);
- scriptdebugView = (TextView) view.findViewById(R.id.openapsma_scriptdebugdata);
- resultView = (TextView) view.findViewById(R.id.openapsma_result);
- requestView = (TextView) view.findViewById(R.id.openapsma_request);
-
- updateGUI();
- return view;
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.openapsma_run:
- OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false);
- FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_AMA_Run"));
- break;
- }
-
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateResultGui ev) {
- updateResultGUI(ev.text);
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- DetermineBasalResultAMA lastAPSResult = OpenAPSAMAPlugin.getPlugin().lastAPSResult;
- if (lastAPSResult != null) {
- resultView.setText(JSONFormatter.format(lastAPSResult.json));
- requestView.setText(lastAPSResult.toSpanned());
- }
- DetermineBasalAdapterAMAJS determineBasalAdapterAMAJS = OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS;
- if (determineBasalAdapterAMAJS != null) {
- glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getGlucoseStatusParam()));
- currentTempView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getCurrentTempParam()));
- try {
- JSONArray iobArray = new JSONArray(determineBasalAdapterAMAJS.getIobDataParam());
- iobDataView.setText(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0)));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- iobDataView.setText("JSONException");
- }
- profileView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getProfileParam()));
- mealDataView.setText(JSONFormatter.format(determineBasalAdapterAMAJS.getMealDataParam()));
- scriptdebugView.setText(determineBasalAdapterAMAJS.getScriptDebug());
- }
- if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0) {
- lastRunView.setText(DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun));
- }
- if (OpenAPSAMAPlugin.getPlugin().lastAutosensResult != null) {
- autosensDataView.setText(JSONFormatter.format(OpenAPSAMAPlugin.getPlugin().lastAutosensResult.json()));
- }
- });
- }
-
- void updateResultGUI(final String text) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- resultView.setText(text);
- glucoseStatusView.setText("");
- currentTempView.setText("");
- iobDataView.setText("");
- profileView.setText("");
- mealDataView.setText("");
- autosensDataView.setText("");
- scriptdebugView.setText("");
- requestView.setText("");
- lastRunView.setText("");
- });
- }
-}
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
deleted file mode 100644
index 12d7988a16..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAFragment.java
+++ /dev/null
@@ -1,118 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.JSONFormatter;
-
-public class OpenAPSMAFragment extends SubscriberFragment implements View.OnClickListener {
- Button run;
- TextView lastRunView;
- TextView glucoseStatusView;
- TextView currentTempView;
- TextView iobDataView;
- TextView profileView;
- TextView mealDataView;
- TextView resultView;
- TextView requestView;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.openapsma_fragment, container, false);
-
- run = (Button) view.findViewById(R.id.openapsma_run);
- run.setOnClickListener(this);
- lastRunView = (TextView) view.findViewById(R.id.openapsma_lastrun);
- glucoseStatusView = (TextView) view.findViewById(R.id.openapsma_glucosestatus);
- currentTempView = (TextView) view.findViewById(R.id.openapsma_currenttemp);
- iobDataView = (TextView) view.findViewById(R.id.openapsma_iobdata);
- profileView = (TextView) view.findViewById(R.id.openapsma_profile);
- mealDataView = (TextView) view.findViewById(R.id.openapsma_mealdata);
- resultView = (TextView) view.findViewById(R.id.openapsma_result);
- requestView = (TextView) view.findViewById(R.id.openapsma_request);
-
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.openapsma_run:
- OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button", false);
- FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_MA_Run"));
- break;
- }
-
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateResultGui ev) {
- updateResultGUI(ev.text);
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- DetermineBasalResultMA lastAPSResult = OpenAPSMAPlugin.getPlugin().lastAPSResult;
- if (lastAPSResult != null) {
- resultView.setText(JSONFormatter.format(lastAPSResult.json));
- requestView.setText(lastAPSResult.toSpanned());
- }
- DetermineBasalAdapterMAJS determineBasalAdapterMAJS = OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS;
- if (determineBasalAdapterMAJS != null) {
- glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getGlucoseStatusParam()));
- currentTempView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getCurrentTempParam()));
- iobDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getIobDataParam()));
- profileView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getProfileParam()));
- mealDataView.setText(JSONFormatter.format(determineBasalAdapterMAJS.getMealDataParam()));
- }
- if (OpenAPSMAPlugin.getPlugin().lastAPSRun != 0) {
- lastRunView.setText(DateUtil.dateAndTimeFullString(OpenAPSMAPlugin.getPlugin().lastAPSRun));
- }
- });
- }
-
- private void updateResultGUI(final String text) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- resultView.setText(text);
- glucoseStatusView.setText("");
- currentTempView.setText("");
- iobDataView.setText("");
- profileView.setText("");
- mealDataView.setText("");
- requestView.setText("");
- lastRunView.setText("");
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateGui.java
deleted file mode 100644
index 40f3c31973..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventOpenAPSUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java
deleted file mode 100644
index 177133f155..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/events/EventOpenAPSUpdateResultGui.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventOpenAPSUpdateResultGui extends EventUpdateGui {
- public String text;
-
- public EventOpenAPSUpdateResultGui(String text) {
- this.text = text;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java
deleted file mode 100644
index d27f8b31d0..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBFragment.java
+++ /dev/null
@@ -1,160 +0,0 @@
-package info.nightscout.androidaps.plugins.OpenAPSSMB;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.JSONFormatter;
-
-public class OpenAPSSMBFragment extends SubscriberFragment {
- private static Logger log = LoggerFactory.getLogger(L.APS);
-
- @BindView(R.id.openapsma_run)
- Button run;
- @BindView(R.id.openapsma_lastrun)
- TextView lastRunView;
- @BindView(R.id.openapsma_constraints)
- TextView constraintsView;
- @BindView(R.id.openapsma_glucosestatus)
- TextView glucoseStatusView;
- @BindView(R.id.openapsma_currenttemp)
- TextView currentTempView;
- @BindView(R.id.openapsma_iobdata)
- TextView iobDataView;
- @BindView(R.id.openapsma_profile)
- TextView profileView;
- @BindView(R.id.openapsma_mealdata)
- TextView mealDataView;
- @BindView(R.id.openapsma_autosensdata)
- TextView autosensDataView;
- @BindView(R.id.openapsma_result)
- TextView resultView;
- @BindView(R.id.openapsma_scriptdebugdata)
- TextView scriptdebugView;
- @BindView(R.id.openapsma_request)
- TextView requestView;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.openapsama_fragment, container, false);
-
- unbinder = ButterKnife.bind(this, view);
- return view;
- }
-
- @OnClick(R.id.openapsma_run)
- public void onRunClick() {
- OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false);
- FabricPrivacy.getInstance().logCustom(new CustomEvent("OpenAPS_SMB_Run"));
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateResultGui ev) {
- updateResultGUI(ev.text);
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- synchronized (OpenAPSSMBFragment.this) {
- if (!isBound()) return;
- OpenAPSSMBPlugin plugin = OpenAPSSMBPlugin.getPlugin();
- DetermineBasalResultSMB lastAPSResult = plugin.lastAPSResult;
- if (lastAPSResult != null) {
- resultView.setText(JSONFormatter.format(lastAPSResult.json));
- requestView.setText(lastAPSResult.toSpanned());
- }
- DetermineBasalAdapterSMBJS determineBasalAdapterSMBJS = plugin.lastDetermineBasalAdapterSMBJS;
- if (determineBasalAdapterSMBJS != null) {
- glucoseStatusView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getGlucoseStatusParam()).toString().trim());
- currentTempView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getCurrentTempParam()).toString().trim());
- try {
- JSONArray iobArray = new JSONArray(determineBasalAdapterSMBJS.getIobDataParam());
- iobDataView.setText((String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n" + JSONFormatter.format(iobArray.getString(0))).trim());
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- iobDataView.setText("JSONException see log for details");
- }
- profileView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getProfileParam()).toString().trim());
- mealDataView.setText(JSONFormatter.format(determineBasalAdapterSMBJS.getMealDataParam()).toString().trim());
- scriptdebugView.setText(determineBasalAdapterSMBJS.getScriptDebug().trim());
- if (lastAPSResult != null && lastAPSResult.inputConstraints != null)
- constraintsView.setText(lastAPSResult.inputConstraints.getReasons().trim());
- }
- if (plugin.lastAPSRun != 0) {
- lastRunView.setText(DateUtil.dateAndTimeFullString(plugin.lastAPSRun));
- }
- if (plugin.lastAutosensResult != null) {
- autosensDataView.setText(JSONFormatter.format(plugin.lastAutosensResult.json()).toString().trim());
- }
- }
- });
- }
-
- void updateResultGUI(final String text) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- synchronized (OpenAPSSMBFragment.this) {
- if (isBound()) {
- resultView.setText(text);
- glucoseStatusView.setText("");
- currentTempView.setText("");
- iobDataView.setText("");
- profileView.setText("");
- mealDataView.setText("");
- autosensDataView.setText("");
- scriptdebugView.setText("");
- requestView.setText("");
- lastRunView.setText("");
- }
- }
- });
- }
-
- private boolean isBound() {
- return run != null
- && lastRunView != null
- && constraintsView != null
- && glucoseStatusView != null
- && currentTempView != null
- && iobDataView != null
- && profileView != null
- && mealDataView != null
- && autosensDataView != null
- && resultView != null
- && scriptdebugView != null
- && requestView != null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressHelperActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressHelperActivity.java
deleted file mode 100644
index 6fddc218ac..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/BolusProgressHelperActivity.java
+++ /dev/null
@@ -1,24 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.Dialogs;
-
-import android.os.Bundle;
-import android.support.v7.app.AppCompatActivity;
-
-/**
- * Created by adrian on 09/02/17.
- */
-
-public class BolusProgressHelperActivity extends AppCompatActivity {
- public BolusProgressHelperActivity() {
- super();
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.getIntent().getDoubleExtra("insulin", 0d);
- BolusProgressDialog bolusProgressDialog = new BolusProgressDialog();
- bolusProgressDialog.setHelperActivity(this);
- bolusProgressDialog.setInsulin(this.getIntent().getDoubleExtra("insulin", 0d));
- bolusProgressDialog.show(this.getSupportFragmentManager(), "BolusProgress");
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java
deleted file mode 100644
index 50de25b656..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/EditQuickWizardDialog.java
+++ /dev/null
@@ -1,190 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.Dialogs;
-
-
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.ArrayAdapter;
-import android.widget.EditText;
-import android.widget.Spinner;
-
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.QuickWizard;
-import info.nightscout.androidaps.data.QuickWizardEntry;
-import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.Overview.events.EventQuickWizardChange;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.SafeParse;
-
-public class EditQuickWizardDialog extends DialogFragment implements View.OnClickListener {
- private static Logger log = LoggerFactory.getLogger(EditQuickWizardDialog.class);
-
- QuickWizardEntry entry = new QuickWizard().newEmptyItem();
- QuickWizard quickWizard = MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard;
-
- EditText buttonEdit;
- EditText carbsEdit;
- Spinner fromSpinner;
- Spinner toSpinner;
- Spinner useBGSpinner;
- Spinner useCOBSpinner;
- Spinner useBolusIOBSpinner;
- Spinner useBasalIOBSpinner;
- Spinner useTrendSpinner;
- Spinner useSuperBolusSpinner;
- Spinner useTempTargetSpinner;
-
- public EditQuickWizardDialog() {
- }
-
- public void setData(QuickWizardEntry data) {
- entry = data;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
- getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
-
- View view = inflater.inflate(R.layout.overview_editquickwizard_dialog, container, false);
- buttonEdit = (EditText) view.findViewById(R.id.overview_editquickwizard_button_edit);
- carbsEdit = (EditText) view.findViewById(R.id.overview_editquickwizard_carbs_edit);
- fromSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_from_spinner);
- toSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_to_spinner);
- useBGSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usebg_spinner);
- useCOBSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usecob_spinner);
- useBolusIOBSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usebolusiob_spinner);
- useBasalIOBSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usebasaliob_spinner);
- useTrendSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usetrend_spinner);
- useSuperBolusSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usesuperbolus_spinner);
- useTempTargetSpinner = (Spinner) view.findViewById(R.id.overview_editquickwizard_usetemptarget_spinner);
-
- view.findViewById(R.id.ok).setOnClickListener(this);
- view.findViewById(R.id.cancel).setOnClickListener(this);
-
- int posFrom = 0;
- int posTo = 95;
- ArrayList timeList = new ArrayList<>();
- int pos = 0;
- for (int t = 0; t < 24 * 60 * 60; t += 15 * 60) {
- timeList.add(DateUtil.timeString(DateUtil.toDate(t)));
- if (entry.validFrom() == t) posFrom = pos;
- if (entry.validTo() == t) posTo = pos;
- pos++;
- }
- timeList.add(DateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60)));
-
- ArrayAdapter adapter = new ArrayAdapter(getContext(),
- R.layout.spinner_centered, timeList);
- fromSpinner.setAdapter(adapter);
- toSpinner.setAdapter(adapter);
-
- buttonEdit.setText(entry.buttonText());
- carbsEdit.setText(entry.carbs().toString());
- fromSpinner.setSelection(posFrom);
- toSpinner.setSelection(posTo);
-
- setSelection(useBGSpinner, entry.useBG());
- setSelection(useCOBSpinner, entry.useCOB());
- setSelection(useBolusIOBSpinner, entry.useBolusIOB());
- setSelection(useBasalIOBSpinner, entry.useBasalIOB());
- setSelection(useTrendSpinner, entry.useTrend());
- setSelection(useSuperBolusSpinner, entry.useSuperBolus());
- setSelection(useTempTargetSpinner, entry.useTempTarget());
-
- return view;
- }
-
- @Override
- public void onResume() {
- super.onResume();
- if (getDialog() != null)
- getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.ok:
- if (fromSpinner.getSelectedItem() == null) return;
- if (toSpinner.getSelectedItem() == null) return;
- try {
- entry.storage.put("buttonText", buttonEdit.getText().toString());
- entry.storage.put("carbs", SafeParse.stringToInt(carbsEdit.getText().toString()));
- int validFromInt = DateUtil.toSeconds(fromSpinner.getSelectedItem().toString());
- entry.storage.put("validFrom", validFromInt);
- int validToInt = DateUtil.toSeconds(toSpinner.getSelectedItem().toString());
- entry.storage.put("validTo", validToInt);
- entry.storage.put("useBG", getSelection(useBGSpinner));
- entry.storage.put("useCOB", getSelection(useCOBSpinner));
- entry.storage.put("useBolusIOB", getSelection(useBolusIOBSpinner));
- entry.storage.put("useBasalIOB", getSelection(useBasalIOBSpinner));
- entry.storage.put("useTrend", getSelection(useTrendSpinner));
- entry.storage.put("useSuperBolus", getSelection(useSuperBolusSpinner));
- entry.storage.put("useTempTarget", getSelection(useTempTargetSpinner));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- quickWizard.addOrUpdate(entry);
- dismiss();
- MainApp.bus().post(new EventQuickWizardChange());
- break;
- case R.id.cancel:
- dismiss();
- break;
- }
- }
-
- int getSelection(Spinner spinner) {
- String value = spinner.getSelectedItem().toString();
- if (value.equals(MainApp.gs(R.string.yes)))
- return QuickWizardEntry.YES;
- if (value.equals(MainApp.gs(R.string.no)))
- return QuickWizardEntry.NO;
- if (value.equals(MainApp.gs(R.string.positiveonly)))
- return QuickWizardEntry.POSITIVE_ONLY;
- if (value.equals(MainApp.gs(R.string.negativeonly)))
- return QuickWizardEntry.NEGATIVE_ONLY;
- return QuickWizardEntry.NO;
- }
-
- void setSelection(Spinner spinner, int value) {
- String selection;
- switch (value) {
- case QuickWizardEntry.YES:
- selection = MainApp.gs(R.string.yes);
- break;
- case QuickWizardEntry.NO:
- selection = MainApp.gs(R.string.no);
- break;
- case QuickWizardEntry.POSITIVE_ONLY:
- selection = MainApp.gs(R.string.positiveonly);
- break;
- case QuickWizardEntry.NEGATIVE_ONLY:
- selection = MainApp.gs(R.string.negativeonly);
- break;
- default:
- selection = MainApp.gs(R.string.no);
- break;
- }
-
- for (int i = 0; i < spinner.getCount(); i++) {
- if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(selection)) {
- spinner.setSelection(i);
- break;
- }
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java
deleted file mode 100644
index dc4fa21aca..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorDialog.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.Dialogs;
-
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.services.AlarmSoundService;
-
-public class ErrorDialog extends DialogFragment implements View.OnClickListener {
- private static Logger log = LoggerFactory.getLogger(ErrorDialog.class);
- Button muteButton;
- Button okButton;
- TextView statusView;
- ErrorHelperActivity helperActivity;
-
- static String status;
- static String title;
- static int soundId;
-
- public ErrorDialog() {
- super();
- }
-
- public void setStatus(String status) {
- this.status = status;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public void setSound(int soundId) {
- this.soundId = soundId;
- }
-
- public void setHelperActivity(ErrorHelperActivity activity) {
- this.helperActivity = activity;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- getDialog().setTitle(title);
- View view = inflater.inflate(R.layout.overview_error_dialog, container, false);
- muteButton = (Button) view.findViewById(R.id.overview_error_mute);
- okButton = (Button) view.findViewById(R.id.overview_error_ok);
- statusView = (TextView) view.findViewById(R.id.overview_error_status);
- muteButton.setOnClickListener(this);
- okButton.setOnClickListener(this);
- setCancelable(false);
-
- startAlarm();
- return view;
- }
-
- @Override
- public void onResume() {
- super.onResume();
- if (getDialog() != null)
- getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- statusView.setText(status);
- }
-
- @Override
- public void dismiss() {
- super.dismissAllowingStateLoss();
- if (helperActivity != null) {
- helperActivity.finish();
- }
- stopAlarm();
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.overview_error_mute:
- log.debug("Error dialog mute button pressed");
- stopAlarm();
- break;
- case R.id.overview_error_ok:
- log.debug("Error dialog ok button pressed");
- dismiss();
- break;
- }
- }
-
- private void startAlarm() {
- Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
- alarm.putExtra("soundid", soundId);
- MainApp.instance().startService(alarm);
- }
-
- private void stopAlarm() {
- Intent alarm = new Intent(MainApp.instance().getApplicationContext(), AlarmSoundService.class);
- MainApp.instance().stopService(alarm);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java
deleted file mode 100644
index c556a6c844..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/ErrorHelperActivity.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.Dialogs;
-
-import android.os.Bundle;
-import android.support.v7.app.AppCompatActivity;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.utils.SP;
-
-public class ErrorHelperActivity extends AppCompatActivity {
- public ErrorHelperActivity() {
- super();
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- ErrorDialog errorDialog = new ErrorDialog();
- errorDialog.setHelperActivity(this);
- errorDialog.setStatus(getIntent().getStringExtra("status"));
- errorDialog.setSound(getIntent().getIntExtra("soundid", 0));
- errorDialog.setTitle(getIntent().getStringExtra("title"));
- errorDialog.show(this.getSupportFragmentManager(), "Error");
-
- if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) {
- NSUpload.uploadError(getIntent().getStringExtra("status"));
- }
- }
-}
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
deleted file mode 100644
index 1b6a4f2ff8..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/Dialogs/WizardDialog.java
+++ /dev/null
@@ -1,613 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.Dialogs;
-
-import android.app.Activity;
-import android.content.Context;
-import android.content.DialogInterface;
-import android.content.Intent;
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.support.v7.app.AlertDialog;
-import android.text.Editable;
-import android.text.Html;
-import android.text.TextWatcher;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.CheckBox;
-import android.widget.CompoundButton;
-import android.widget.EditText;
-import android.widget.LinearLayout;
-import android.widget.Spinner;
-import android.widget.TextView;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.Date;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileStore;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.CareportalEvent;
-import info.nightscout.androidaps.db.DatabaseHelper;
-import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.events.EventFeatureRunning;
-import info.nightscout.androidaps.events.EventNewBG;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.CobInfo;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.utils.BolusWizard;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.NumberPicker;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
-import info.nightscout.utils.ToastUtils;
-
-public class WizardDialog extends DialogFragment implements OnClickListener, CompoundButton.OnCheckedChangeListener, Spinner.OnItemSelectedListener {
- private static Logger log = LoggerFactory.getLogger(WizardDialog.class);
-
- Button okButton;
- TextView bg;
- TextView bgInsulin;
- TextView bgUnits;
- CheckBox bgCheckbox;
- CheckBox ttCheckbox;
- TextView carbs;
- TextView carbsInsulin;
- TextView bolusIobInsulin;
- TextView basalIobInsulin;
- CheckBox bolusIobCheckbox;
- CheckBox basalIobCheckbox;
- TextView correctionInsulin;
- TextView total;
- Spinner profileSpinner;
- CheckBox superbolusCheckbox;
- TextView superbolus;
- TextView superbolusInsulin;
- CheckBox bgtrendCheckbox;
- TextView bgTrend;
- TextView bgTrendInsulin;
- LinearLayout cobLayout;
- CheckBox cobCheckbox;
- TextView cob;
- TextView cobInsulin;
-
- NumberPicker editBg;
- NumberPicker editCarbs;
- NumberPicker editCorr;
- NumberPicker editCarbTime;
-
- LinearLayout notesLayout;
- EditText notesEdit;
-
- Integer calculatedCarbs = 0;
- Double calculatedTotalInsulin = 0d;
- JSONObject boluscalcJSON;
-
- Context context;
-
- //one shot guards
- private boolean accepted;
- private boolean okClicked;
-
- public WizardDialog() {
- super();
- }
-
- @Override
- public void onAttach(Context context) {
- super.onAttach(context);
- this.context = context;
- }
-
- @Override
- public void onDetach() {
- super.onDetach();
- this.context = null;
- }
-
- @Override
- public void onResume() {
- super.onResume();
- MainApp.bus().register(this);
- MainApp.bus().post(new EventFeatureRunning(EventFeatureRunning.Feature.WIZARD));
- }
-
- @Override
- public void onPause() {
- super.onPause();
- MainApp.bus().unregister(this);
- }
-
- @Override
- public void onSaveInstanceState(Bundle savedInstanceState) {
- savedInstanceState.putBoolean("bgCheckbox", bgCheckbox.isChecked());
- savedInstanceState.putBoolean("ttCheckbox", ttCheckbox.isChecked());
- savedInstanceState.putBoolean("bolusIobCheckbox", bolusIobCheckbox.isChecked());
- savedInstanceState.putBoolean("basalIobCheckbox", basalIobCheckbox.isChecked());
- savedInstanceState.putBoolean("bgtrendCheckbox", bgtrendCheckbox.isChecked());
- savedInstanceState.putBoolean("cobCheckbox", cobCheckbox.isChecked());
- savedInstanceState.putDouble("editBg", editBg.getValue());
- savedInstanceState.putDouble("editCarbs", editCarbs.getValue());
- savedInstanceState.putDouble("editCorr", editCorr.getValue());
- savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue());
- super.onSaveInstanceState(savedInstanceState);
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventNewBG e) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- calculateInsulin();
- }
- });
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished e) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- calculateInsulin();
- }
- });
- }
-
- final private TextWatcher textWatcher = 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) {
- calculateInsulin();
- }
- };
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.overview_wizard_dialog, container, false);
-
- getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
- getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
-
- okButton = (Button) view.findViewById(R.id.ok);
- okButton.setOnClickListener(this);
- view.findViewById(R.id.cancel).setOnClickListener(this);
-
- bg = (TextView) view.findViewById(R.id.treatments_wizard_bg);
- bgInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bginsulin);
- bgUnits = (TextView) view.findViewById(R.id.treatments_wizard_bgunits);
- carbs = (TextView) view.findViewById(R.id.treatments_wizard_carbs);
- carbsInsulin = (TextView) view.findViewById(R.id.treatments_wizard_carbsinsulin);
- bolusIobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bolusiobinsulin);
- basalIobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_basaliobinsulin);
- correctionInsulin = (TextView) view.findViewById(R.id.treatments_wizard_correctioninsulin);
- total = (TextView) view.findViewById(R.id.treatments_wizard_total);
- superbolus = (TextView) view.findViewById(R.id.treatments_wizard_sb);
- superbolusInsulin = (TextView) view.findViewById(R.id.treatments_wizard_sbinsulin);
-
- notesLayout = view.findViewById(R.id.treatments_wizard_notes_layout);
- notesLayout.setVisibility(SP.getBoolean(R.string.key_show_notes_entry_dialogs, false) ? View.VISIBLE : View.GONE);
- notesEdit = (EditText) view.findViewById(R.id.treatment_wizard_notes);
-
- bgTrend = (TextView) view.findViewById(R.id.treatments_wizard_bgtrend);
- bgTrendInsulin = (TextView) view.findViewById(R.id.treatments_wizard_bgtrendinsulin);
- cobLayout = (LinearLayout) view.findViewById(R.id.treatments_wizard_cob_layout);
- cob = (TextView) view.findViewById(R.id.treatments_wizard_cob);
- cobInsulin = (TextView) view.findViewById(R.id.treatments_wizard_cobinsulin);
-
- bgCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bgcheckbox);
- ttCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_ttcheckbox);
- bgtrendCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bgtrendcheckbox);
- cobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_cobcheckbox);
- bolusIobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_bolusiobcheckbox);
- basalIobCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_basaliobcheckbox);
- superbolusCheckbox = (CheckBox) view.findViewById(R.id.treatments_wizard_sbcheckbox);
- loadCheckedStates();
-
- bgCheckbox.setOnCheckedChangeListener(this);
- ttCheckbox.setOnCheckedChangeListener(this);
- bgtrendCheckbox.setOnCheckedChangeListener(this);
- cobCheckbox.setOnCheckedChangeListener(this);
- basalIobCheckbox.setOnCheckedChangeListener(this);
- bolusIobCheckbox.setOnCheckedChangeListener(this);
- superbolusCheckbox.setOnCheckedChangeListener(this);
-
- profileSpinner = (Spinner) view.findViewById(R.id.treatments_wizard_profile);
- profileSpinner.setOnItemSelectedListener(this);
-
- editCarbTime = (NumberPicker) view.findViewById(R.id.treatments_wizard_carbtimeinput);
- editCorr = (NumberPicker) view.findViewById(R.id.treatments_wizard_correctioninput);
- editCarbs = (NumberPicker) view.findViewById(R.id.treatments_wizard_carbsinput);
- editBg = (NumberPicker) view.findViewById(R.id.treatments_wizard_bginput);
-
- superbolusCheckbox.setVisibility(SP.getBoolean(R.string.key_usesuperbolus, false) ? View.VISIBLE : View.GONE);
-
- Integer maxCarbs = MainApp.getConstraintChecker().getMaxCarbsAllowed().value();
- Double maxCorrection = MainApp.getConstraintChecker().getMaxBolusAllowed().value();
-
- editBg.setParams(0d, 0d, 500d, 0.1d, new DecimalFormat("0.0"), false, textWatcher);
- editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, textWatcher);
- double bolusstep = ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().bolusStep;
- editCorr.setParams(0d, -maxCorrection, maxCorrection, bolusstep, DecimalFormatter.pumpSupportedBolusFormat(), false, textWatcher);
- editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false);
- initDialog();
-
- setCancelable(true);
- getDialog().setCanceledOnTouchOutside(false);
- //recovering state if there is something
- if (savedInstanceState != null) {
- editCarbs.setValue(savedInstanceState.getDouble("editCarbs"));
- editBg.setValue(savedInstanceState.getDouble("editBg"));
- editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime"));
- editCorr.setValue(savedInstanceState.getDouble("editCorr"));
- }
- return view;
- }
-
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- saveCheckedStates();
- ttCheckbox.setEnabled(bgCheckbox.isChecked() && TreatmentsPlugin.getPlugin().getTempTargetFromHistory() != null);
- calculateInsulin();
- }
-
- private void saveCheckedStates() {
- SP.putBoolean(MainApp.gs(R.string.key_wizard_include_cob), cobCheckbox.isChecked());
- SP.putBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), bgtrendCheckbox.isChecked());
- }
-
- private void loadCheckedStates() {
- bgtrendCheckbox.setChecked(SP.getBoolean(MainApp.gs(R.string.key_wizard_include_trend_bg), false));
- cobCheckbox.setChecked(SP.getBoolean(MainApp.gs(R.string.key_wizard_include_cob), false));
- }
-
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- calculateInsulin();
- okButton.setVisibility(View.VISIBLE);
- }
-
- @Override
- public void onNothingSelected(AdapterView> parent) {
- ToastUtils.showToastInUiThread(context, MainApp.gs(R.string.noprofileselected));
- okButton.setVisibility(View.GONE);
- }
-
- @Override
- public synchronized void onClick(View view) {
- switch (view.getId()) {
- case R.id.ok:
- if (okClicked) {
- log.debug("guarding: ok already clicked");
- dismiss();
- return;
- }
- okClicked = true;
- final Profile profile = ProfileFunctions.getInstance().getProfile();
- final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
-
- if (pump != null && profile != null && (calculatedTotalInsulin > 0d || calculatedCarbs > 0d)) {
- String confirmMessage = MainApp.gs(R.string.entertreatmentquestion);
-
- Double insulinAfterConstraints = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(calculatedTotalInsulin)).value();
- Integer carbsAfterConstraints = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(calculatedCarbs)).value();
-
- if (insulinAfterConstraints > 0)
- confirmMessage += "
" + MainApp.gs(R.string.bolus) + ": " + "" + DecimalFormatter.toPumpSupportedBolus(insulinAfterConstraints) + "U" + "";
- if (carbsAfterConstraints > 0)
- confirmMessage += "
" + MainApp.gs(R.string.carbs) + ": " + "" + carbsAfterConstraints + "g" + "";
-
- if (Math.abs(insulinAfterConstraints - calculatedTotalInsulin) > pump.getPumpDescription().pumpType.determineCorrectBolusSize(insulinAfterConstraints) || !carbsAfterConstraints.equals(calculatedCarbs)) {
- confirmMessage += "
" + MainApp.gs(R.string.bolusconstraintapplied) + "";
- }
-
- final Double finalInsulinAfterConstraints = insulinAfterConstraints;
- final Integer finalCarbsAfterConstraints = carbsAfterConstraints;
- final Double bg = SafeParse.stringToDouble(editBg.getText());
- final int carbTime = SafeParse.stringToInt(editCarbTime.getText());
- final boolean useSuperBolus = superbolusCheckbox.isChecked();
- final String finalNotes = notesEdit.getText().toString();
-
- final AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setTitle(MainApp.gs(R.string.confirmation));
- builder.setMessage(Html.fromHtml(confirmMessage));
- builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- synchronized (builder) {
- if (accepted) {
- log.debug("guarding: already accepted");
- return;
- }
- accepted = true;
- if (finalInsulinAfterConstraints > 0 || finalCarbsAfterConstraints > 0) {
- if (useSuperBolus) {
- final LoopPlugin loopPlugin = LoopPlugin.getPlugin();
- if (loopPlugin.isEnabled(PluginType.LOOP)) {
- loopPlugin.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000);
- MainApp.bus().post(new EventRefreshOverview("WizardDialog"));
- }
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, 120, true, profile, new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
- i.putExtra("soundid", R.raw.boluserror);
- i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
- }
- }
- });
- }
- DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
- detailedBolusInfo.eventType = CareportalEvent.BOLUSWIZARD;
- detailedBolusInfo.insulin = finalInsulinAfterConstraints;
- detailedBolusInfo.carbs = finalCarbsAfterConstraints;
- detailedBolusInfo.context = context;
- detailedBolusInfo.glucose = bg;
- detailedBolusInfo.glucoseType = "Manual";
- detailedBolusInfo.carbTime = carbTime;
- detailedBolusInfo.boluscalc = boluscalcJSON;
- detailedBolusInfo.source = Source.USER;
- detailedBolusInfo.notes = finalNotes;
- if (detailedBolusInfo.insulin > 0 || ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().storesCarbInfo) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
- i.putExtra("soundid", R.raw.boluserror);
- i.putExtra("status", result.comment);
- i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror));
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- MainApp.instance().startActivity(i);
- }
- }
- });
- } else {
- TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
- }
- FabricPrivacy.getInstance().logCustom(new CustomEvent("Wizard"));
- }
- }
- }
- });
- builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
- builder.show();
- dismiss();
- }
- break;
- case R.id.cancel:
- dismiss();
- break;
- }
- }
-
- private void initDialog() {
- Profile profile = ProfileFunctions.getInstance().getProfile();
- ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null ? ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() : null;
-
- if (profile == null || profileStore == null) {
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.noprofile));
- dismiss();
- return;
- }
-
- ArrayList profileList;
- profileList = profileStore.getProfileList();
- profileList.add(0, MainApp.gs(R.string.active));
- ArrayAdapter adapter = new ArrayAdapter<>(getContext(),
- R.layout.spinner_centered, profileList);
-
- profileSpinner.setAdapter(adapter);
-
- String units = profile.getUnits();
- bgUnits.setText(units);
- if (units.equals(Constants.MGDL)) editBg.setStep(1d);
- else editBg.setStep(0.1d);
-
- // Set BG if not old
- BgReading lastBg = DatabaseHelper.actualBg();
-
- if (lastBg != null) {
- editBg.setValue(lastBg.valueToUnits(units));
- } else {
- editBg.setValue(0d);
- }
- ttCheckbox.setEnabled(TreatmentsPlugin.getPlugin().getTempTargetFromHistory() != null);
-
- // IOB calculation
- TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
- IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
- TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
- IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
-
- bolusIobInsulin.setText(DecimalFormatter.to2Decimal(-bolusIob.iob) + "U");
- basalIobInsulin.setText(DecimalFormatter.to2Decimal(-basalIob.basaliob) + "U");
-
- calculateInsulin();
- }
-
- private void calculateInsulin() {
- ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile();
- if (profileSpinner == null || profileSpinner.getSelectedItem() == null || profileStore == null)
- return; // not initialized yet
- String selectedAlternativeProfile = profileSpinner.getSelectedItem().toString();
- Profile specificProfile;
- if (selectedAlternativeProfile.equals(MainApp.gs(R.string.active))) {
- specificProfile = ProfileFunctions.getInstance().getProfile();
- selectedAlternativeProfile = ProfileFunctions.getInstance().getProfileName();
- } else
- specificProfile = profileStore.getSpecificProfile(selectedAlternativeProfile);
-
- // Entered values
- Double c_bg = SafeParse.stringToDouble(editBg.getText());
- Integer c_carbs = SafeParse.stringToInt(editCarbs.getText());
- Double c_correction = SafeParse.stringToDouble(editCorr.getText());
- Double corrAfterConstraint = c_correction;
- if (c_correction > 0)
- c_correction = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(c_correction)).value();
- if (Math.abs(c_correction - corrAfterConstraint) > 0.01d) { // c_correction != corrAfterConstraint doesn't work
- editCorr.setValue(0d);
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.bolusconstraintapplied));
- return;
- }
- Integer carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(new Constraint<>(c_carbs)).value();
- if (Math.abs(c_carbs - carbsAfterConstraint) > 0.01d) {
- editCarbs.setValue(0d);
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.carbsconstraintapplied));
- return;
- }
-
- c_bg = bgCheckbox.isChecked() ? c_bg : 0d;
- TempTarget tempTarget = ttCheckbox.isChecked() ? TreatmentsPlugin.getPlugin().getTempTargetFromHistory() : null;
-
- // COB
- Double c_cob = 0d;
- if (cobCheckbox.isChecked()) {
- CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Wizard COB");
- if (cobInfo != null && cobInfo.displayCob != null)
- c_cob = cobInfo.displayCob;
- }
-
- BolusWizard wizard = new BolusWizard();
- wizard.doCalc(specificProfile, tempTarget, carbsAfterConstraint, c_cob, c_bg, corrAfterConstraint, bolusIobCheckbox.isChecked(), basalIobCheckbox.isChecked(), superbolusCheckbox.isChecked(), bgtrendCheckbox.isChecked());
-
- bg.setText(c_bg + " ISF: " + DecimalFormatter.to1Decimal(wizard.sens));
- bgInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromBG) + "U");
-
- carbs.setText(DecimalFormatter.to0Decimal(c_carbs) + "g IC: " + DecimalFormatter.to1Decimal(wizard.ic));
- carbsInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromCarbs) + "U");
-
- bolusIobInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulingFromBolusIOB) + "U");
- basalIobInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulingFromBasalsIOB) + "U");
-
- correctionInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromCorrection) + "U");
- calculatedTotalInsulin = wizard.calculatedTotalInsulin;
-
- calculatedCarbs = carbsAfterConstraint;
-
- // Superbolus
- if (superbolusCheckbox.isChecked()) {
- superbolus.setText("2h");
- } else {
- superbolus.setText("");
- }
- superbolusInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromSuperBolus) + "U");
-
- // Trend
- if (bgtrendCheckbox.isChecked()) {
- if (wizard.glucoseStatus != null) {
- bgTrend.setText((wizard.glucoseStatus.avgdelta > 0 ? "+" : "") + Profile.toUnitsString(wizard.glucoseStatus.avgdelta * 3, wizard.glucoseStatus.avgdelta * 3 / 18, specificProfile.getUnits()) + " " + specificProfile.getUnits());
- } else {
- bgTrend.setText("");
- }
- } else {
- bgTrend.setText("");
- }
- bgTrendInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromTrend) + "U");
-
- // COB
- if (cobCheckbox.isChecked()) {
- cob.setText(DecimalFormatter.to2Decimal(c_cob) + "g IC: " + DecimalFormatter.to1Decimal(wizard.ic));
- cobInsulin.setText(DecimalFormatter.to2Decimal(wizard.insulinFromCOB) + "U");
- } else {
- cob.setText("");
- cobInsulin.setText("");
- }
-
- if (calculatedTotalInsulin > 0d || calculatedCarbs > 0d) {
- String insulinText = calculatedTotalInsulin > 0d ? (DecimalFormatter.toPumpSupportedBolus(calculatedTotalInsulin) + "U") : "";
- String carbsText = calculatedCarbs > 0d ? (DecimalFormatter.to0Decimal(calculatedCarbs) + "g") : "";
- total.setText(MainApp.gs(R.string.result) + ": " + insulinText + " " + carbsText);
- okButton.setVisibility(View.VISIBLE);
- } else {
- // TODO this should also be run when loading the dialog as the OK button is initially visible
- // but does nothing if neither carbs nor insulin is > 0
- total.setText(MainApp.gs(R.string.missing) + " " + DecimalFormatter.to0Decimal(wizard.carbsEquivalent) + "g");
- okButton.setVisibility(View.INVISIBLE);
- }
-
- boluscalcJSON = new JSONObject();
- try {
- boluscalcJSON.put("profile", selectedAlternativeProfile);
- boluscalcJSON.put("notes", notesEdit.getText());
- boluscalcJSON.put("eventTime", DateUtil.toISOString(new Date()));
- boluscalcJSON.put("targetBGLow", wizard.targetBGLow);
- boluscalcJSON.put("targetBGHigh", wizard.targetBGHigh);
- boluscalcJSON.put("isf", wizard.sens);
- boluscalcJSON.put("ic", wizard.ic);
- boluscalcJSON.put("iob", -(wizard.insulingFromBolusIOB + wizard.insulingFromBasalsIOB));
- boluscalcJSON.put("bolusiob", wizard.insulingFromBolusIOB);
- boluscalcJSON.put("basaliob", wizard.insulingFromBasalsIOB);
- boluscalcJSON.put("bolusiobused", bolusIobCheckbox.isChecked());
- boluscalcJSON.put("basaliobused", basalIobCheckbox.isChecked());
- boluscalcJSON.put("bg", c_bg);
- boluscalcJSON.put("insulinbg", wizard.insulinFromBG);
- boluscalcJSON.put("insulinbgused", bgCheckbox.isChecked());
- boluscalcJSON.put("bgdiff", wizard.bgDiff);
- boluscalcJSON.put("insulincarbs", wizard.insulinFromCarbs);
- boluscalcJSON.put("carbs", c_carbs);
- boluscalcJSON.put("cob", c_cob);
- boluscalcJSON.put("cobused", cobCheckbox.isChecked());
- boluscalcJSON.put("insulincob", wizard.insulinFromCOB);
- boluscalcJSON.put("othercorrection", corrAfterConstraint);
- boluscalcJSON.put("insulinsuperbolus", wizard.insulinFromSuperBolus);
- boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
- boluscalcJSON.put("insulin", calculatedTotalInsulin);
- boluscalcJSON.put("superbolusused", superbolusCheckbox.isChecked());
- boluscalcJSON.put("insulinsuperbolus", wizard.insulinFromSuperBolus);
- boluscalcJSON.put("trendused", bgtrendCheckbox.isChecked());
- boluscalcJSON.put("insulintrend", wizard.insulinFromTrend);
- boluscalcJSON.put("trend", bgTrend.getText());
- boluscalcJSON.put("ttused", ttCheckbox.isChecked());
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java
deleted file mode 100644
index b184201908..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/OverviewPlugin.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview;
-
-import com.squareup.otto.Subscribe;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.QuickWizard;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.notifications.NotificationStore;
-import info.nightscout.utils.SP;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class OverviewPlugin extends PluginBase {
- private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
-
- private static OverviewPlugin overviewPlugin = new OverviewPlugin();
-
- public static OverviewPlugin getPlugin() {
- if (overviewPlugin == null)
- overviewPlugin = new OverviewPlugin();
- return overviewPlugin;
- }
-
- public static double bgTargetLow = 80d;
- public static double bgTargetHigh = 180d;
-
- public QuickWizard quickWizard = new QuickWizard();
-
- public NotificationStore notificationStore = new NotificationStore();
-
- public OverviewPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(OverviewFragment.class.getName())
- .alwayVisible(true)
- .alwaysEnabled(true)
- .pluginName(R.string.overview)
- .shortName(R.string.overview_shortname)
- .preferencesId(R.xml.pref_overview)
- .description(R.string.description_overview)
- );
- String storedData = SP.getString("QuickWizard", "[]");
- try {
- quickWizard.setData(new JSONArray(storedData));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- }
-
- @Override
- protected void onStart() {
- MainApp.bus().register(this);
- super.onStart();
- }
-
- @Override
- protected void onStop() {
- MainApp.bus().unregister(this);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewNotification n) {
- if (notificationStore.add(n.notification))
- MainApp.bus().post(new EventRefreshOverview("EventNewNotification"));
- }
-
- @Subscribe
- public void onStatusEvent(final EventDismissNotification n) {
- if (notificationStore.remove(n.id))
- MainApp.bus().post(new EventRefreshOverview("EventDismissNotification"));
- }
-
- public double determineHighLine(String units) {
- double highLineSetting = SP.getDouble("high_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetHigh, units));
- if (highLineSetting < 1)
- highLineSetting = Profile.fromMgdlToUnits(180d, units);
- return highLineSetting;
- }
-
- public double determineLowLine() {
- Profile profile = ProfileFunctions.getInstance().getProfile();
- if (profile == null) {
- return bgTargetLow;
- }
- return determineLowLine(profile.getUnits());
- }
-
- public double determineLowLine(String units) {
- double lowLineSetting = SP.getDouble("low_mark", Profile.fromMgdlToUnits(OverviewPlugin.bgTargetLow, units));
- if (lowLineSetting < 1)
- lowLineSetting = Profile.fromMgdlToUnits(76d, units);
- return lowLineSetting;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/activities/QuickWizardListActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/activities/QuickWizardListActivity.java
deleted file mode 100644
index 237575c328..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/activities/QuickWizardListActivity.java
+++ /dev/null
@@ -1,172 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.activities;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.support.v4.app.FragmentManager;
-import android.support.v7.app.AppCompatActivity;
-import android.support.v7.widget.CardView;
-import android.support.v7.widget.LinearLayoutManager;
-import android.support.v7.widget.RecyclerView;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.QuickWizard;
-import info.nightscout.androidaps.plugins.Overview.Dialogs.EditQuickWizardDialog;
-import info.nightscout.androidaps.plugins.Overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.Overview.events.EventQuickWizardChange;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-
-public class QuickWizardListActivity extends AppCompatActivity implements View.OnClickListener {
-
- RecyclerView recyclerView;
- LinearLayoutManager llm;
-
- Button adButton;
-
- public static class RecyclerViewAdapter extends RecyclerView.Adapter {
-
- QuickWizard qvData;
- FragmentManager fragmentManager;
-
- RecyclerViewAdapter(QuickWizard data, FragmentManager fragmentManager) {
- this.qvData = data;
- this.fragmentManager = fragmentManager;
- }
-
- @Override
- public QuickWizardEntryViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
- View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.overview_quickwizardlist_item, viewGroup, false);
- QuickWizardEntryViewHolder quickWizardEntryViewHolder = new QuickWizardEntryViewHolder(v, fragmentManager, qvData);
- return quickWizardEntryViewHolder;
- }
-
- @Override
- public void onBindViewHolder(QuickWizardEntryViewHolder holder, int position) {
- holder.from.setText(DateUtil.timeString(qvData.get(position).validFromDate()));
- holder.to.setText(DateUtil.timeString(qvData.get(position).validToDate()));
- holder.buttonText.setText(qvData.get(position).buttonText());
- holder.carbs.setText(DecimalFormatter.to0Decimal(qvData.get(position).carbs()) + " g");
- }
-
- @Override
- public int getItemCount() {
- return qvData.size();
- }
-
- @Override
- public void onAttachedToRecyclerView(RecyclerView recyclerView) {
- super.onAttachedToRecyclerView(recyclerView);
- }
-
- public static class QuickWizardEntryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
- CardView cv;
- TextView buttonText;
- TextView carbs;
- TextView from;
- TextView to;
- Button editButton;
- Button removeButton;
- FragmentManager fragmentManager;
- QuickWizard qvData;
-
- QuickWizardEntryViewHolder(View itemView, FragmentManager fragmentManager, QuickWizard qvData) {
- super(itemView);
- cv = (CardView) itemView.findViewById(R.id.overview_quickwizard_cardview);
- buttonText = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_buttonText);
- carbs = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_carbs);
- from = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_from);
- to = (TextView) itemView.findViewById(R.id.overview_quickwizard_item_to);
- editButton = (Button) itemView.findViewById(R.id.overview_quickwizard_item_edit_button);
- removeButton = (Button) itemView.findViewById(R.id.overview_quickwizard_item_remove_button);
- editButton.setOnClickListener(this);
- removeButton.setOnClickListener(this);
- this.fragmentManager = fragmentManager;
- this.qvData = qvData;
- }
-
- @Override
- public void onClick(View v) {
- int position = getAdapterPosition();
- switch (v.getId()) {
- case R.id.overview_quickwizard_item_edit_button:
- FragmentManager manager = fragmentManager;
- EditQuickWizardDialog editQuickWizardDialog = new EditQuickWizardDialog();
- editQuickWizardDialog.setData(qvData.get(position));
- editQuickWizardDialog.show(manager, "EditQuickWizardDialog");
- break;
- case R.id.overview_quickwizard_item_remove_button:
- qvData.remove(position);
- MainApp.bus().post(new EventQuickWizardChange());
- break;
- }
- }
- }
- }
-
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.overview_quickwizardlist_activity);
-
- recyclerView = (RecyclerView) findViewById(R.id.overview_quickwizardactivity_recyclerview);
- recyclerView.setHasFixedSize(true);
- llm = new LinearLayoutManager(this);
- recyclerView.setLayoutManager(llm);
-
- RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard, getSupportFragmentManager());
- recyclerView.setAdapter(adapter);
-
- adButton = (Button) findViewById(R.id.overview_quickwizardactivity_add_button);
- adButton.setOnClickListener(this);
- }
-
- @Override
- protected void onResume() {
- super.onResume();
- MainApp.bus().register(this);
- }
-
- @Override
- protected void onPause() {
- super.onPause();
- MainApp.bus().unregister(this);
- }
-
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.overview_quickwizardactivity_add_button:
- FragmentManager manager = getSupportFragmentManager();
- EditQuickWizardDialog editQuickWizardDialog = new EditQuickWizardDialog();
- editQuickWizardDialog.show(manager, "EditQuickWizardDialog");
- break;
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventQuickWizardChange ev) {
- updateGUI();
- }
-
- public void updateGUI() {
- Activity activity = this;
- if (activity != null && recyclerView != null) {
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp.getSpecificPlugin(OverviewPlugin.class).quickWizard, getSupportFragmentManager());
- recyclerView.swapAdapter(adapter, false);
- }
- });
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissBolusprogressIfRunning.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissBolusprogressIfRunning.java
deleted file mode 100644
index af336cd74c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissBolusprogressIfRunning.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.events;
-
-import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by adrian on 20/02/17.
- */
-
-public class EventDismissBolusprogressIfRunning extends Event {
- public final PumpEnactResult result;
-
- public EventDismissBolusprogressIfRunning(PumpEnactResult result) {
- this.result = result;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissNotification.java
deleted file mode 100644
index 1fa71febbe..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventDismissNotification.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 03.12.2016.
- */
-
-public class EventDismissNotification extends Event {
- public int id;
-
- public EventDismissNotification(int did) {
- id = did;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventNewNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventNewNotification.java
deleted file mode 100644
index 2a669d26d2..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventNewNotification.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.events;
-
-import info.nightscout.androidaps.events.Event;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
-
-/**
- * Created by mike on 03.12.2016.
- */
-
-public class EventNewNotification extends Event {
- public Notification notification;
-
- public EventNewNotification(Notification n) {
- notification = n;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java
deleted file mode 100644
index 18e8ff91bc..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventOverviewBolusProgress.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.events;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
-import info.nightscout.androidaps.events.Event;
-
-public class EventOverviewBolusProgress extends Event {
- public String status = "";
- public Treatment t = null;
- public int percent = 0;
- public int bolusId;
- private static EventOverviewBolusProgress eventOverviewBolusProgress = null;
-
- public EventOverviewBolusProgress() {
- }
-
- public boolean isSMB(){
- return (t != null) && t.isSMB;
- }
-
- public static EventOverviewBolusProgress getInstance() {
- if(eventOverviewBolusProgress == null) {
- eventOverviewBolusProgress = new EventOverviewBolusProgress();
- }
- return eventOverviewBolusProgress;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventQuickWizardChange.java b/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventQuickWizardChange.java
deleted file mode 100644
index b72c2548e2..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Overview/events/EventQuickWizardChange.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.Overview.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 20.10.2016.
- */
-
-public class EventQuickWizardChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/DummyService.java b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/DummyService.java
deleted file mode 100644
index 56b3a2cd09..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/DummyService.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package info.nightscout.androidaps.plugins.Persistentnotification;
-
-import android.app.Notification;
-import android.app.Service;
-import android.content.Intent;
-import android.os.IBinder;
-import android.support.annotation.Nullable;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.events.EventAppExit;
-import info.nightscout.androidaps.logging.L;
-
-/**
- * Keeps AndroidAPS in foreground state, so it won't be terminated by Android nor get restricted by the background execution limits
- */
-public class DummyService extends Service {
- private static Logger log = LoggerFactory.getLogger(L.CORE);
-
- @Nullable
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
- Notification notification = PersistentNotificationPlugin.getPlugin().updateNotification();
- if (notification != null)
- startForeground(PersistentNotificationPlugin.ONGOING_NOTIFICATION_ID, notification);
- return START_STICKY;
- }
-
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.CORE))
- log.debug("EventAppExit received");
-
- stopSelf();
- }
-
- @Override
- public void onCreate() {
- MainApp.bus().register(this);
- }
-
- @Override
- public void onDestroy() {
- if (L.isEnabled(L.CORE))
- log.debug("onDestroy");
- MainApp.bus().unregister(this);
- stopForeground(true);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java
deleted file mode 100644
index 6b93b7a715..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Persistentnotification/PersistentNotificationPlugin.java
+++ /dev/null
@@ -1,319 +0,0 @@
-package info.nightscout.androidaps.plugins.Persistentnotification;
-
-import android.annotation.SuppressLint;
-import android.app.Notification;
-import android.app.NotificationChannel;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.content.Context;
-import android.content.Intent;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.os.Build;
-import android.support.v4.app.NotificationCompat;
-import android.support.v4.app.TaskStackBuilder;
-
-// Android Auto
-import android.support.v4.app.NotificationCompat;
-import android.support.v4.app.NotificationManagerCompat;
-import android.support.v4.app.RemoteInput;
-
-
-
-
-import com.squareup.otto.Subscribe;
-
-import info.nightscout.androidaps.Config;
-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.GlucoseStatus;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.DatabaseHelper;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventInitializationChanged;
-import info.nightscout.androidaps.events.EventNewBG;
-import info.nightscout.androidaps.events.EventNewBasalProfile;
-import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.events.EventTreatmentChange;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DecimalFormatter;
-
-/**
- * Created by adrian on 23/12/16.
- */
-
-public class PersistentNotificationPlugin extends PluginBase {
-
- private static PersistentNotificationPlugin plugin;
-
- public static PersistentNotificationPlugin getPlugin() {
- if (plugin == null) plugin = new PersistentNotificationPlugin(MainApp.instance());
- return plugin;
- }
-
- public static final String CHANNEL_ID = "AndroidAPS-Ongoing";
-
- public static final int ONGOING_NOTIFICATION_ID = 4711;
- private final Context ctx;
-
- /// For Android Auto
- /// Intents are not declared in manifest and not consumed, this is intentionally because actually we can't do anything with
- private static final String PACKAGE = "info.nightscout";
- private static final String READ_ACTION =
- "info.nightscout.androidaps.ACTION_MESSAGE_READ";
- private static final String REPLY_ACTION =
- "info.nightscout.androidaps.ACTION_MESSAGE_REPLY";
- private static final String CONVERSATION_ID = "conversation_id";
- private static final String EXTRA_VOICE_REPLY = "extra_voice_reply";
- /// End Android Auto
-
-
- public PersistentNotificationPlugin(Context ctx) {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .neverVisible(true)
- .pluginName(R.string.ongoingnotificaction)
- .enableByDefault(true)
- .alwaysEnabled(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
- .description(R.string.description_persistent_notification)
- );
- this.ctx = ctx;
- }
-
- @Override
- protected void onStart() {
- MainApp.bus().register(this);
- createNotificationChannel();
- triggerNotificationUpdate();
- super.onStart();
- }
-
- private void createNotificationChannel() {
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
-
- NotificationManager mNotificationManager =
- (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
- @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
- CHANNEL_ID,
- NotificationManager.IMPORTANCE_HIGH);
- mNotificationManager.createNotificationChannel(channel);
- }
- }
-
- @Override
- protected void onStop() {
- MainApp.bus().unregister(this);
- MainApp.instance().stopService(new Intent(MainApp.instance(), DummyService.class));
- }
-
- private void triggerNotificationUpdate() {
- MainApp.instance().startService(new Intent(MainApp.instance(), DummyService.class));
- }
-
- Notification updateNotification() {
- if (!isEnabled(PluginType.GENERAL)) {
- return null;
- }
-
- String line1;
- String line1_aa;
-
- if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() == null || !ProfileFunctions.getInstance().isProfileValid("Notificiation"))
- return null;
- String units = ProfileFunctions.getInstance().getProfileUnits();
-
-
- BgReading lastBG = DatabaseHelper.lastBg();
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
-
- if (lastBG != null) {
- line1 = line1_aa = lastBG.valueToUnitsToString(units);
- if (glucoseStatus != null) {
- line1 += " Δ" + deltastring(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)
- + " avgΔ" + deltastring(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units);
- line1_aa += " " + lastBG.directionToSymbol();
- } else {
- line1 += " " +
- MainApp.gs(R.string.old_data) +
- " ";
- line1_aa += line1 + ".";
- }
- } else {
- line1 = line1_aa = MainApp.gs(R.string.missed_bg_readings);
- }
-
- TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (activeTemp != null) {
- line1 += " " + activeTemp.toStringShort();
- line1_aa += " " + activeTemp.toStringShort() + ".";
- }
-
- //IOB
- TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
- TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
- IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
- IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
-
-
- String line2 = MainApp.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U " + MainApp.gs(R.string.cob)+": " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "PersistentNotificationPlugin").generateCOBString();
- String line2_aa = MainApp.gs(R.string.treatments_iob_label_string) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U. " + MainApp.gs(R.string.cob)+": " + IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "PersistentNotificationPlugin").generateCOBString() + ".";
-
-
- String line3 = DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate()) + " U/h";
- String line3_aa = DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate()) + " U/h.";
-
-
- line3 += " - " + ProfileFunctions.getInstance().getProfileName();
- line3_aa += " - " + ProfileFunctions.getInstance().getProfileName() + ".";
-
- /// For Android Auto
- Intent msgReadIntent = new Intent()
- .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- .setAction(READ_ACTION)
- .putExtra(CONVERSATION_ID, ONGOING_NOTIFICATION_ID)
- .setPackage(PACKAGE);
-
- PendingIntent msgReadPendingIntent =
- PendingIntent.getBroadcast(ctx,
- ONGOING_NOTIFICATION_ID,
- msgReadIntent,
- PendingIntent.FLAG_UPDATE_CURRENT);
-
- Intent msgReplyIntent = new Intent()
- .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
- .setAction(REPLY_ACTION)
- .putExtra(CONVERSATION_ID, ONGOING_NOTIFICATION_ID)
- .setPackage(PACKAGE);
-
- PendingIntent msgReplyPendingIntent = PendingIntent.getBroadcast(
- ctx,
- ONGOING_NOTIFICATION_ID,
- msgReplyIntent,
- PendingIntent.FLAG_UPDATE_CURRENT);
-
- // Build a RemoteInput for receiving voice input from devices
- RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).build();
-
- // Create the UnreadConversation
- NotificationCompat.CarExtender.UnreadConversation.Builder unreadConversationBuilder =
- new NotificationCompat.CarExtender.UnreadConversation.Builder(line1_aa + "\n" + line2_aa)
- .setLatestTimestamp(System.currentTimeMillis())
- .setReadPendingIntent(msgReadPendingIntent)
- .setReplyAction(msgReplyPendingIntent, remoteInput);
-
- /// Add dot to produce a "more natural sounding result"
- unreadConversationBuilder.addMessage(line3_aa);
- /// End Android Auto
-
-
- NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx, CHANNEL_ID);
- builder.setOngoing(true);
- builder.setOnlyAlertOnce(true);
- builder.setCategory(NotificationCompat.CATEGORY_STATUS);
- if (Config.NSCLIENT){
- builder.setSmallIcon(R.drawable.nsclient_smallicon);
- Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.yellowowl);
- builder.setLargeIcon(largeIcon);
- } else {
- builder.setSmallIcon(R.drawable.ic_notification);
- Bitmap largeIcon = BitmapFactory.decodeResource(ctx.getResources(), R.mipmap.blueowl);
- builder.setLargeIcon(largeIcon);
- }
- builder.setContentTitle(line1);
- builder.setContentText(line2);
- builder.setSubText(line3);
- /// Android Auto
- builder.extend(new NotificationCompat.CarExtender()
- .setUnreadConversation(unreadConversationBuilder.build()));
- /// End Android Auto
-
-
- Intent resultIntent = new Intent(ctx, MainActivity.class);
-
- TaskStackBuilder stackBuilder = TaskStackBuilder.create(ctx);
- stackBuilder.addParentStack(MainActivity.class);
- stackBuilder.addNextIntent(resultIntent);
- PendingIntent resultPendingIntent =
- stackBuilder.getPendingIntent(
- 0,
- PendingIntent.FLAG_UPDATE_CURRENT
- );
- builder.setContentIntent(resultPendingIntent);
- NotificationManager mNotificationManager =
- (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
-
- android.app.Notification notification = builder.build();
- mNotificationManager.notify(ONGOING_NOTIFICATION_ID, notification);
- return notification;
- }
-
- private String deltastring(double deltaMGDL, double deltaMMOL, String units) {
- String deltastring = "";
- if (deltaMGDL >= 0) {
- deltastring += "+";
- } else {
- deltastring += "-";
-
- }
- if (units.equals(Constants.MGDL)) {
- deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMGDL));
- } else {
- deltastring += DecimalFormatter.to1Decimal(Math.abs(deltaMMOL));
- }
- return deltastring;
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBG ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBasalProfile ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged ev) {
- triggerNotificationUpdate();
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- triggerNotificationUpdate();
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java
deleted file mode 100644
index 4edaef1761..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/NSProfileFragment.java
+++ /dev/null
@@ -1,165 +0,0 @@
-package info.nightscout.androidaps.plugins.ProfileNS;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.ArrayAdapter;
-import android.widget.Button;
-import android.widget.Spinner;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import java.util.ArrayList;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import butterknife.OnItemSelected;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileStore;
-import info.nightscout.androidaps.plugins.Careportal.Dialogs.NewNSTreatmentDialog;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.ProfileNS.events.EventNSProfileUpdateGUI;
-import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.OKDialog;
-
-import static butterknife.OnItemSelected.Callback.NOTHING_SELECTED;
-
-
-public class NSProfileFragment extends SubscriberFragment {
- @BindView(R.id.nsprofile_spinner)
- Spinner profileSpinner;
- @BindView(R.id.profileview_noprofile)
- TextView noProfile;
- @BindView(R.id.profileview_invalidprofile)
- TextView invalidProfile;
- @BindView(R.id.profileview_units)
- TextView units;
- @BindView(R.id.profileview_dia)
- TextView dia;
- @BindView(R.id.profileview_activeprofile)
- TextView activeProfile;
- @BindView(R.id.profileview_ic)
- TextView ic;
- @BindView(R.id.profileview_isf)
- TextView isf;
- @BindView(R.id.profileview_basal)
- TextView basal;
- @BindView(R.id.profileview_basaltotal)
- TextView basaltotal;
- @BindView(R.id.profileview_target)
- TextView target;
- @BindView(R.id.basal_graph)
- ProfileGraph basalGraph;
- @BindView(R.id.nsprofile_profileswitch)
- Button activateButton;
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.nsprofile_fragment, container, false);
-
- unbinder = ButterKnife.bind(this, view);
- updateGUI();
- return view;
- }
-
- @Subscribe
- public void onStatusEvent(final EventNSProfileUpdateGUI ev) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- synchronized (NSProfileFragment.this) {
- updateGUI();
- }
- });
- }
-
- @Override
- protected void updateGUI() {
- if (noProfile == null || profileSpinner == null)
- return;
-
- ProfileStore profileStore = NSProfilePlugin.getPlugin().getProfile();
- if (profileStore != null) {
- ArrayList profileList = profileStore.getProfileList();
- ArrayAdapter adapter = new ArrayAdapter<>(getContext(),
- R.layout.spinner_centered, profileList);
- profileSpinner.setAdapter(adapter);
- // set selected to actual profile
- for (int p = 0; p < profileList.size(); p++) {
- if (profileList.get(p).equals(ProfileFunctions.getInstance().getProfileName()))
- profileSpinner.setSelection(p);
- }
- noProfile.setVisibility(View.GONE);
- } else {
- noProfile.setVisibility(View.VISIBLE);
- }
- }
-
- @OnItemSelected(R.id.nsprofile_spinner)
- public void onItemSelected(Spinner spinner, int position) {
- String name = spinner.getItemAtPosition(position).toString();
-
- ProfileStore store = NSProfilePlugin.getPlugin().getProfile();
- if (store != null) {
- Profile profile = store.getSpecificProfile(name);
- if (profile != null) {
- units.setText(profile.getUnits());
- dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
- activeProfile.setText(name);
- ic.setText(profile.getIcList());
- isf.setText(profile.getIsfList());
- basal.setText(profile.getBasalList());
- basaltotal.setText(String.format(MainApp.gs(R.string.profile_total), DecimalFormatter.to2Decimal(profile.baseBasalSum())));
- target.setText(profile.getTargetList());
- basalGraph.show(profile);
- }
- if (profile.isValid("NSProfileFragment")) {
- invalidProfile.setVisibility(View.GONE);
- activateButton.setVisibility(View.VISIBLE);
- } else {
- invalidProfile.setVisibility(View.VISIBLE);
- activateButton.setVisibility(View.GONE);
- }
- } else {
- activateButton.setVisibility(View.GONE);
- }
- }
-
- @OnItemSelected(value = R.id.nsprofile_spinner, callback = NOTHING_SELECTED)
- public void onNothingSelected() {
- invalidProfile.setVisibility(View.VISIBLE);
- noProfile.setVisibility(View.VISIBLE);
- units.setText("");
- dia.setText("");
- activeProfile.setText("");
- ic.setText("");
- isf.setText("");
- basal.setText("");
- basaltotal.setText("");
- target.setText("");
- activateButton.setVisibility(View.GONE);
- }
-
- @OnClick(R.id.nsprofile_profileswitch)
- public void onClickProfileSwitch() {
- String name = profileSpinner.getSelectedItem() != null ? profileSpinner.getSelectedItem().toString() : "";
- ProfileStore store = NSProfilePlugin.getPlugin().getProfile();
- if (store != null) {
- Profile profile = store.getSpecificProfile(name);
- if (profile != null) {
- OKDialog.showConfirmation(getActivity(), MainApp.gs(R.string.activate_profile) + ": " + name + " ?", () ->
- NewNSTreatmentDialog.doProfileSwitch(store, name, 0, 100, 0)
- );
- }
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/events/EventNSProfileUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/events/EventNSProfileUpdateGUI.java
deleted file mode 100644
index d24c59e511..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/ProfileNS/events/EventNSProfileUpdateGUI.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.ProfileNS.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventNSProfileUpdateGUI extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboFragment.java
deleted file mode 100644
index e1ae0286de..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/ComboFragment.java
+++ /dev/null
@@ -1,234 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpCombo;
-
-
-import android.app.Activity;
-import android.app.AlertDialog;
-import android.graphics.Color;
-import android.graphics.Typeface;
-import android.os.Bundle;
-import android.support.annotation.NonNull;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import org.apache.commons.lang3.StringUtils;
-
-import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.PumpState;
-import info.nightscout.androidaps.plugins.PumpCombo.ruffyscripter.history.Bolus;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.PumpCombo.events.EventComboPumpUpdateGUI;
-import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.androidaps.queue.events.EventQueueChanged;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.SP;
-
-public class ComboFragment extends SubscriberFragment implements View.OnClickListener {
- private TextView stateView;
- private TextView activityView;
- private TextView batteryView;
- private TextView reservoirView;
- private TextView lastConnectionView;
- private TextView lastBolusView;
- private TextView baseBasalRate;
- private TextView tempBasalText;
- private Button refreshButton;
- private TextView bolusCount;
- private TextView tbrCount;
-
- @Override
- public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.combopump_fragment, container, false);
-
- stateView = view.findViewById(R.id.combo_state);
- activityView = view.findViewById(R.id.combo_activity);
- batteryView = view.findViewById(R.id.combo_pumpstate_battery);
- reservoirView = view.findViewById(R.id.combo_insulinstate);
- lastBolusView = view.findViewById(R.id.combo_last_bolus);
- lastConnectionView = view.findViewById(R.id.combo_lastconnection);
- baseBasalRate = view.findViewById(R.id.combo_base_basal_rate);
- tempBasalText = view.findViewById(R.id.combo_temp_basal);
- bolusCount = view.findViewById(R.id.combo_bolus_count);
- tbrCount = view.findViewById(R.id.combo_tbr_count);
-
- refreshButton = view.findViewById(R.id.combo_refresh_button);
- refreshButton.setOnClickListener(this);
-
- updateGUI();
- return view;
- }
-
- private void runOnUiThread(Runnable action) {
- Activity activity = getActivity();
- if (activity != null) {
- activity.runOnUiThread(action);
- }
- }
-
- @Override
- public void onClick(View view) {
- switch (view.getId()) {
- case R.id.combo_refresh_button:
- refreshButton.setEnabled(false);
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("User request", new Callback() {
- @Override
- public void run() {
- runOnUiThread(() -> refreshButton.setEnabled(true));
- }
- });
- break;
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventComboPumpUpdateGUI ignored) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventQueueChanged ignored) {
- updateGUI();
- }
-
-
- public void updateGUI() {
- runOnUiThread(() -> {
- ComboPlugin plugin = ComboPlugin.getPlugin();
-
- // state
- stateView.setText(plugin.getStateSummary());
- PumpState ps = plugin.getPump().state;
- if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY
- || ps.activeAlert != null && ps.activeAlert.errorCode != null) {
- stateView.setTextColor(Color.RED);
- stateView.setTypeface(null, Typeface.BOLD);
- } else if (plugin.getPump().state.suspended
- || ps.activeAlert != null && ps.activeAlert.warningCode != null) {
- stateView.setTextColor(Color.YELLOW);
- stateView.setTypeface(null, Typeface.BOLD);
- } else {
- stateView.setTextColor(Color.WHITE);
- stateView.setTypeface(null, Typeface.NORMAL);
- }
-
- // activity
- String activity = plugin.getPump().activity;
- if (activity != null) {
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(14);
- activityView.setText(activity);
- } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) {
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(14);
- activityView.setText("");
- } else if (plugin.isInitialized()){
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(20);
- activityView.setText("{fa-bed}");
- } else {
- activityView.setTextColor(Color.RED);
- activityView.setTextSize(14);
- activityView.setText(MainApp.gs(R.string.pump_unreachable));
- }
-
- if (plugin.isInitialized()) {
- // battery
- batteryView.setTextSize(20);
- if (ps.batteryState == PumpState.EMPTY) {
- batteryView.setText("{fa-battery-empty}");
- batteryView.setTextColor(Color.RED);
- } else if (ps.batteryState == PumpState.LOW) {
- batteryView.setText("{fa-battery-quarter}");
- batteryView.setTextColor(Color.YELLOW);
- } else {
- batteryView.setText("{fa-battery-full}");
- batteryView.setTextColor(Color.WHITE);
- }
-
- // reservoir
- int reservoirLevel = plugin.getPump().reservoirLevel;
- if (reservoirLevel != -1) {
- reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname));
- } else if (ps.insulinState == PumpState.LOW) {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low));
- } else if (ps.insulinState == PumpState.EMPTY) {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty));
- } else {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal));
- }
-
- if (ps.insulinState == PumpState.UNKNOWN) {
- reservoirView.setTextColor(Color.WHITE);
- reservoirView.setTypeface(null, Typeface.NORMAL);
- } else if (ps.insulinState == PumpState.LOW) {
- reservoirView.setTextColor(Color.YELLOW);
- reservoirView.setTypeface(null, Typeface.BOLD);
- } else if (ps.insulinState == PumpState.EMPTY) {
- reservoirView.setTextColor(Color.RED);
- reservoirView.setTypeface(null, Typeface.BOLD);
- } else {
- reservoirView.setTextColor(Color.WHITE);
- reservoirView.setTypeface(null, Typeface.NORMAL);
- }
-
- // last connection
- String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime);
- long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60;
- if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) {
- lastConnectionView.setText(R.string.combo_pump_connected_now);
- lastConnectionView.setTextColor(Color.WHITE);
- } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) {
- lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min));
- lastConnectionView.setTextColor(Color.RED);
- } else {
- lastConnectionView.setText(minAgo);
- lastConnectionView.setTextColor(Color.WHITE);
- }
-
- // last bolus
- Bolus bolus = plugin.getPump().lastBolus;
- if (bolus != null) {
- long agoMsc = System.currentTimeMillis() - bolus.timestamp;
- double bolusMinAgo = agoMsc / 60d / 1000d;
- String unit = MainApp.gs(R.string.insulin_unit_shortname);
- String ago;
- if ((agoMsc < 60 * 1000)) {
- ago = MainApp.gs(R.string.combo_pump_connected_now);
- } else if (bolusMinAgo < 60) {
- ago = DateUtil.minAgo(bolus.timestamp);
- } else {
- ago = DateUtil.hourAgo(bolus.timestamp);
- }
- lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago));
- } else {
- lastBolusView.setText("");
- }
-
- // base basal rate
- baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate()));
-
- // TBR
- String tbrStr = "";
- if (ps.tbrPercent != -1 && ps.tbrPercent != 100) {
- long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60;
- long remaining = ps.tbrRemainingDuration - minSinceRead;
- if (remaining >= 0) {
- tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining);
- }
- }
- tempBasalText.setText(tbrStr);
-
- // stats
- bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L)));
- tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L)));
- }
- });
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/events/EventComboPumpUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/events/EventComboPumpUpdateGUI.java
deleted file mode 100644
index e9bf3f8415..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpCombo/events/EventComboPumpUpdateGUI.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpCombo.events;
-
-/**
- * Created by mike on 24.05.2017.
- */
-
-public class EventComboPumpUpdateGUI {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java
deleted file mode 100644
index 33d371dca3..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/DanaRFragment.java
+++ /dev/null
@@ -1,304 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaR;
-
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.Handler;
-import android.support.v4.app.FragmentManager;
-import android.text.Spanned;
-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.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.OnClick;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.activities.TDDStatsActivity;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventPumpStatusChanged;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.PumpDanaR.Dialogs.ProfileViewDialog;
-import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRHistoryActivity;
-import info.nightscout.androidaps.plugins.PumpDanaR.activities.DanaRUserOptionsActivity;
-import info.nightscout.androidaps.plugins.PumpDanaR.events.EventDanaRNewStatus;
-import info.nightscout.androidaps.plugins.PumpDanaRKorean.DanaRKoreanPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.queue.events.EventQueueChanged;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.SetWarnColor;
-
-public class DanaRFragment extends SubscriberFragment {
- private static Logger log = LoggerFactory.getLogger(L.PUMP);
-
- private Handler loopHandler = new Handler();
- private Runnable refreshLoop = new Runnable() {
- @Override
- public void run() {
- updateGUI();
- loopHandler.postDelayed(refreshLoop, 60 * 1000L);
- }
- };
-
- @BindView(R.id.danar_lastconnection)
- TextView lastConnectionView;
- @BindView(R.id.danar_btconnection)
- TextView btConnectionView;
- @BindView(R.id.danar_lastbolus)
- TextView lastBolusView;
- @BindView(R.id.danar_dailyunits)
- TextView dailyUnitsView;
- @BindView(R.id.danar_basabasalrate)
- TextView basaBasalRateView;
- @BindView(R.id.danar_tempbasal)
- TextView tempBasalView;
- @BindView(R.id.danar_extendedbolus)
- TextView extendedBolusView;
- @BindView(R.id.danar_battery)
- TextView batteryView;
- @BindView(R.id.danar_reservoir)
- TextView reservoirView;
- @BindView(R.id.danar_iob)
- TextView iobView;
- @BindView(R.id.danar_firmware)
- TextView firmwareView;
- @BindView(R.id.danar_basalstep)
- TextView basalStepView;
- @BindView(R.id.danar_bolusstep)
- TextView bolusStepView;
- @BindView(R.id.danar_serialnumber)
- TextView serialNumberView;
- @BindView(R.id.danar_queue)
- TextView queueView;
-
- @BindView(R.id.overview_pumpstatuslayout)
- LinearLayout pumpStatusLayout;
- @BindView(R.id.overview_pumpstatus)
- TextView pumpStatusView;
- @BindView(R.id.danar_user_options)
- Button danar_user_options;
-
- public DanaRFragment() {
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- loopHandler.postDelayed(refreshLoop, 60 * 1000L);
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- loopHandler.removeCallbacks(refreshLoop);
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.danar_fragment, container, false);
- unbinder = ButterKnife.bind(this, view);
-
- pumpStatusView.setBackgroundColor(MainApp.gc(R.color.colorInitializingBorder));
-
- return view;
- }
-
- @OnClick(R.id.danar_history)
- void onHistoryClick() {
- startActivity(new Intent(getContext(), DanaRHistoryActivity.class));
- }
-
- @OnClick(R.id.danar_viewprofile)
- void onViewProfileClick() {
- FragmentManager manager = getFragmentManager();
- ProfileViewDialog profileViewDialog = new ProfileViewDialog();
- profileViewDialog.show(manager, "ProfileViewDialog");
- }
-
- @OnClick(R.id.danar_stats)
- void onStatsClick() {
- startActivity(new Intent(getContext(), TDDStatsActivity.class));
- }
-
- @OnClick(R.id.danar_user_options)
- void onUserOptionsClick() {
- startActivity(new Intent(getContext(), DanaRUserOptionsActivity.class));
- }
-
- @OnClick(R.id.danar_btconnection)
- void onBtConnectionClick() {
- if (L.isEnabled(L.PUMP))
- log.debug("Clicked connect to pump");
- DanaRPump.getInstance().lastConnection = 0;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Clicked connect to pump", null);
- }
-
- @Subscribe
- public void onStatusEvent(final EventPumpStatusChanged c) {
- Activity activity = getActivity();
- final String status = c.textStatus();
- if (activity != null) {
- activity.runOnUiThread(
- () -> {
- synchronized (DanaRFragment.this) {
-
- if (btConnectionView == null || pumpStatusView == null || pumpStatusLayout == null)
- return;
-
- if (c.sStatus == EventPumpStatusChanged.CONNECTING)
- btConnectionView.setText("{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s");
- else if (c.sStatus == EventPumpStatusChanged.CONNECTED)
- btConnectionView.setText("{fa-bluetooth}");
- else if (c.sStatus == EventPumpStatusChanged.DISCONNECTED)
- btConnectionView.setText("{fa-bluetooth-b}");
-
- if (!status.equals("")) {
- pumpStatusView.setText(status);
- pumpStatusLayout.setVisibility(View.VISIBLE);
- } else {
- pumpStatusLayout.setVisibility(View.GONE);
- }
- }
- }
- );
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventDanaRNewStatus s) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange s) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange s) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventQueueChanged s) {
- updateGUI();
- }
-
- // GUI functions
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null && basaBasalRateView != null)
- activity.runOnUiThread(() -> {
- synchronized (DanaRFragment.this) {
- if (!isBound()) return;
-
- DanaRPump pump = DanaRPump.getInstance();
- if (pump.lastConnection != 0) {
- Long agoMsec = System.currentTimeMillis() - pump.lastConnection;
- int agoMin = (int) (agoMsec / 60d / 1000d);
- lastConnectionView.setText(DateUtil.timeString(pump.lastConnection) + " (" + String.format(MainApp.gs(R.string.minago), agoMin) + ")");
- SetWarnColor.setColor(lastConnectionView, agoMin, 16d, 31d);
- }
- if (pump.lastBolusTime != 0) {
- Long agoMsec = System.currentTimeMillis() - pump.lastBolusTime;
- double agoHours = agoMsec / 60d / 60d / 1000d;
- if (agoHours < 6) // max 6h back
- lastBolusView.setText(DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime) + " " + DecimalFormatter.to2Decimal(DanaRPump.getInstance().lastBolusAmount) + " U");
- else lastBolusView.setText("");
- }
-
- dailyUnitsView.setText(DecimalFormatter.to0Decimal(pump.dailyTotalUnits) + " / " + pump.maxDailyTotalUnits + " U");
- SetWarnColor.setColor(dailyUnitsView, pump.dailyTotalUnits, pump.maxDailyTotalUnits * 0.75d, pump.maxDailyTotalUnits * 0.9d);
- basaBasalRateView.setText("( " + (pump.activeProfile + 1) + " ) " + DecimalFormatter.to2Decimal(ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate()) + " U/h");
- // DanaRPlugin, DanaRKoreanPlugin
- if (ConfigBuilderPlugin.getPlugin().getActivePump().isFakingTempsByExtendedBoluses()) {
- if (TreatmentsPlugin.getPlugin().isInHistoryRealTempBasalInProgress()) {
- tempBasalView.setText(TreatmentsPlugin.getPlugin().getRealTempBasalFromHistory(System.currentTimeMillis()).toStringFull());
- } else {
- tempBasalView.setText("");
- }
- } else {
- // v2 plugin
- TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (tb != null) {
- tempBasalView.setText(tb.toStringFull());
- } else {
- tempBasalView.setText("");
- }
- }
- ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
- if (activeExtendedBolus != null) {
- extendedBolusView.setText(activeExtendedBolus.toString());
- } else {
- extendedBolusView.setText("");
- }
- reservoirView.setText(DecimalFormatter.to0Decimal(pump.reservoirRemainingUnits) + " / 300 U");
- SetWarnColor.setColorInverse(reservoirView, pump.reservoirRemainingUnits, 50d, 20d);
- batteryView.setText("{fa-battery-" + (pump.batteryRemaining / 25) + "}");
- SetWarnColor.setColorInverse(batteryView, pump.batteryRemaining, 51d, 26d);
- iobView.setText(pump.iob + " U");
- if (pump.model != 0 || pump.protocol != 0 || pump.productCode != 0) {
- firmwareView.setText(String.format(MainApp.gs(R.string.danar_model), pump.model, pump.protocol, pump.productCode));
- } else {
- firmwareView.setText("OLD");
- }
- basalStepView.setText("" + pump.basalStep);
- bolusStepView.setText("" + pump.bolusStep);
- serialNumberView.setText("" + pump.serialNumber);
- if (queueView != null) {
- Spanned status = ConfigBuilderPlugin.getPlugin().getCommandQueue().spannedStatus();
- if (status.toString().equals("")) {
- queueView.setVisibility(View.GONE);
- } else {
- queueView.setVisibility(View.VISIBLE);
- queueView.setText(status);
- }
- }
- //hide user options button if not an RS pump or old firmware
- // also excludes pump with model 03 because of untested error
- boolean isKorean = DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PUMP);
- if (isKorean || firmwareView.getText() == "OLD" || pump.model == 3) {
- danar_user_options.setVisibility(View.GONE);
- }
- }
- });
- }
-
- private boolean isBound() {
- return lastConnectionView != null
- && lastBolusView != null
- && dailyUnitsView != null
- && basaBasalRateView != null
- && tempBasalView != null
- && extendedBolusView != null
- && reservoirView != null
- && batteryView != null
- && iobView != null
- && firmwareView != null
- && basalStepView != null
- && bolusStepView != null
- && serialNumberView != null
- && danar_user_options != null
- && queueView != null;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java
deleted file mode 100644
index 06906aa0b4..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/Dialogs/ProfileViewDialog.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaR.Dialogs;
-
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileStore;
-import info.nightscout.androidaps.interfaces.ProfileInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.Treatments.fragments.ProfileGraph;
-import info.nightscout.utils.DecimalFormatter;
-
-/**
- * Created by mike on 10.07.2016.
- */
-public class ProfileViewDialog extends DialogFragment {
- private TextView noProfile;
- private TextView units;
- private TextView dia;
- private TextView activeProfile;
- private TextView ic;
- private TextView isf;
- private TextView basal;
- private TextView target;
- private ProfileGraph basalGraph;
-
-
- private Button refreshButton;
-
- public ProfileViewDialog() {
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View layout = inflater.inflate(R.layout.profileviewer_fragment, container, false);
-
- noProfile = (TextView) layout.findViewById(R.id.profileview_noprofile);
- units = (TextView) layout.findViewById(R.id.profileview_units);
- dia = (TextView) layout.findViewById(R.id.profileview_dia);
- activeProfile = (TextView) layout.findViewById(R.id.profileview_activeprofile);
- ic = (TextView) layout.findViewById(R.id.profileview_ic);
- isf = (TextView) layout.findViewById(R.id.profileview_isf);
- basal = (TextView) layout.findViewById(R.id.profileview_basal);
- target = (TextView) layout.findViewById(R.id.profileview_target);
- refreshButton = (Button) layout.findViewById(R.id.profileview_reload);
- refreshButton.setVisibility(View.VISIBLE);
- refreshButton.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("ProfileViewDialog", null);
- dismiss();
- }
- });
- basalGraph = (ProfileGraph) layout.findViewById(R.id.basal_graph);
- setContent();
- return layout;
- }
-
- @Override
- public void onResume() {
- super.onResume();
- getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
- }
-
- private void setContent() {
- ProfileStore store = ((ProfileInterface)ConfigBuilderPlugin.getPlugin().getActivePump()).getProfile();
- if (store != null) {
- noProfile.setVisibility(View.GONE);
- Profile profile = store.getDefaultProfile();
- units.setText(profile.getUnits());
- dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
- activeProfile.setText(((ProfileInterface) ConfigBuilderPlugin.getPlugin().getActivePump()).getProfileName());
- ic.setText(profile.getIcList());
- isf.setText(profile.getIsfList());
- basal.setText(profile.getBasalList());
- target.setText(profile.getTargetList());
- basalGraph.show(store.getDefaultProfile());
- } else {
- noProfile.setVisibility(View.VISIBLE);
- }
- }
-
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java
deleted file mode 100644
index e7f1adca07..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/comm/MessageHashTable.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaR.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashMap;
-
-/**
- * Created by mike on 28.05.2016.
- */
-public class MessageHashTable {
- public static HashMap messages = null;
-
- static {
- if (messages == null) {
- messages = new HashMap();
- put(new MsgBolusStop()); // 0x0101 CMD_MEALINS_STOP
- put(new MsgBolusStart()); // 0x0102 CMD_MEALINS_START_DATA
- put(new MsgBolusStartWithSpeed()); // 0x0104 CMD_MEALINS_START_DATA_SPEED
- put(new MsgBolusProgress()); // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
- put(new MsgStatusProfile()); // 0x0204 CMD_PUMP_CALCULATION_SETTING
- put(new MsgStatusTempBasal()); // 0x0205 CMD_PUMP_EXERCISE_MODE
- put(new MsgStatusBolusExtended()); // 0x0207 CMD_PUMP_EXPANS_INS_I
- put(new MsgStatusBasic()); // 0x020A CMD_PUMP_INITVIEW_I
- put(new MsgStatus()); // 0x020B CMD_PUMP_STATUS
- put(new MsgInitConnStatusTime()); // 0x0301 CMD_PUMPINIT_TIME_INFO
- put(new MsgInitConnStatusBolus()); // 0x0302 CMD_PUMPINIT_BOLUS_INFO
- put(new MsgInitConnStatusBasic()); // 0x0303 CMD_PUMPINIT_INIT_INFO
- put(new MsgInitConnStatusOption()); // 0x0304 CMD_PUMPINIT_OPTION
- put(new MsgSetTempBasalStart()); // 0x0401 CMD_PUMPSET_EXERCISE_S
- put(new MsgSetCarbsEntry()); // 0x0402 CMD_PUMPSET_HIS_S
- put(new MsgSetTempBasalStop()); // 0x0403 CMD_PUMPSET_EXERCISE_STOP
- put(new MsgSetExtendedBolusStop()); // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP
- put(new MsgSetExtendedBolusStart()); // 0x0407 CMD_PUMPSET_EXPANS_INS_S
- put(new MsgError()); // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS
- put(new MsgPCCommStart()); // 0x3001 CMD_CONNECT
- put(new MsgPCCommStop()); // 0x3002 CMD_DISCONNECT
- put(new MsgHistoryBolus()); // 0x3101 CMD_HISTORY_MEAL_INS
- put(new MsgHistoryDailyInsulin()); // 0x3102 CMD_HISTORY_DAY_INS
- put(new MsgHistoryGlucose()); // 0x3104 CMD_HISTORY_GLUCOSE
- put(new MsgHistoryAlarm()); // 0x3105 CMD_HISTORY_ALARM
- put(new MsgHistoryError()); // 0x3106 CMD_HISTORY_ERROR
- put(new MsgHistoryCarbo()); // 0x3107 CMD_HISTORY_CARBOHY
- put(new MsgHistoryRefill()); // 0x3108 CMD_HISTORY_REFILL
- put(new MsgHistorySuspend()); // 0x3109 CMD_HISTORY_SUSPEND
- put(new MsgHistoryBasalHour()); // 0x310A CMD_HISTORY_BASAL_HOUR
- put(new MsgHistoryDone()); // 0x31F1 CMD_HISTORY_DONT_USED
- put(new MsgSettingBasal()); // 0x3202 CMD_SETTING_V_BASAL_INS_I
- put(new MsgSettingMeal()); // 0x3203 CMD_SETTING_V_MEAL_SETTING_I
- put(new MsgSettingProfileRatios()); // 0x3204 CMD_SETTING_V_CCC_I
- put(new MsgSettingMaxValues()); // 0x3205 CMD_SETTING_V_MAX_VALUE_I
- put(new MsgSettingBasalProfileAll()); // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL
- put(new MsgSettingShippingInfo()); // 0x3207 CMD_SETTING_V_SHIPPING_I
- put(new MsgSettingGlucose()); // 0x3209 CMD_SETTING_V_GLUCOSEandEASY
- put(new MsgSettingPumpTime()); // 0x320A CMD_SETTING_V_TIME_I
- put(new MsgSettingUserOptions()); // 0x320B CMD_SETTING_V_USER_OPTIONS
- put(new MsgSettingActiveProfile()); // 0x320C CMD_SETTING_V_PROFILE_NUMBER
- put(new MsgSettingProfileRatiosAll()); // 0x320D CMD_SETTING_V_CIR_CF_VALUE
- put(new MsgSetSingleBasalProfile()); // 0x3302 CMD_SETTING_BASAL_INS_S
- put(new MsgSetBasalProfile()); // 0x3306 CMD_SETTING_BASAL_PROFILE_S
- put(new MsgSetUserOptions()); // 0x330B CMD_SETTING_USER_OPTIONS_S
- put(new MsgSetActivateBasalProfile()); // 0x330C CMD_SETTING_PROFILE_NUMBER_S
- put(new MsgHistoryAllDone()); // 0x41F1 CMD_HISTORY_ALL_DONE
- put(new MsgHistoryAll()); // 0x41F2 CMD_HISTORY_ALL
- put(new MsgHistoryNewDone()); // 0x42F1 CMD_HISTORY_NEW_DONE
- put(new MsgHistoryNew()); // 0x42F2 CMD_HISTORY_NEW
- put(new MsgCheckValue()); // 0xF0F1 CMD_PUMP_CHECK_VALUE
- }
- }
-
- public static void put(MessageBase message) {
- int command = message.getCommand();
- //String name = MessageOriginalNames.getName(command);
- messages.put(command, message);
- //log.debug(String.format("%04x ", command) + " " + name);
- }
-
- public static MessageBase findMessage(Integer command) {
- if (messages.containsKey(command)) {
- return messages.get(command);
- } else {
- return new MessageBase();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRNewStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRNewStatus.java
deleted file mode 100644
index 55b0ab0998..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRNewStatus.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaR.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 08.07.2016.
- */
-public class EventDanaRNewStatus extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRSyncStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRSyncStatus.java
deleted file mode 100644
index f2a5dc7b2a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaR/events/EventDanaRSyncStatus.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaR.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 20.07.2016.
- */
-public class EventDanaRSyncStatus extends Event {
- public String message;
-
- public EventDanaRSyncStatus() {
- }
-
- }
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java
deleted file mode 100644
index ea12b2b9c4..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/SerialIOThread.java
+++ /dev/null
@@ -1,210 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRKorean;
-
-import android.bluetooth.BluetoothSocket;
-import android.os.SystemClock;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread;
-import info.nightscout.androidaps.plugins.PumpDanaRKorean.comm.MessageHashTable_k;
-import info.nightscout.utils.CRC;
-
-/**
- * Created by mike on 17.07.2016.
- */
-public class SerialIOThread extends AbstractSerialIOThread {
- private static Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM);
-
- private InputStream mInputStream = null;
- private OutputStream mOutputStream = null;
- private BluetoothSocket mRfCommSocket;
-
- private boolean mKeepRunning = true;
- private byte[] mReadBuff = new byte[0];
-
- private MessageBase processedMessage;
-
- public SerialIOThread(BluetoothSocket rfcommSocket) {
- super();
-
- mRfCommSocket = rfcommSocket;
- try {
- mOutputStream = mRfCommSocket.getOutputStream();
- mInputStream = mRfCommSocket.getInputStream();
- } catch (IOException e) {
- log.error("Unhandled exception", e);
- }
- this.start();
- }
-
- @Override
- public final void run() {
- try {
- while (mKeepRunning) {
- int availableBytes = mInputStream.available();
- // Ask for 1024 byte (or more if available)
- byte[] newData = new byte[Math.max(1024, availableBytes)];
- int gotBytes = mInputStream.read(newData);
- // When we are here there is some new data available
- appendToBuffer(newData, gotBytes);
-
- // process all messages we already got
- while (mReadBuff.length > 3) { // 3rd byte is packet size. continue only if we an determine packet size
- byte[] extractedBuff = cutMessageFromBuffer();
- if (extractedBuff == null)
- break; // message is not complete in buffer (wrong packet calls disconnection)
-
- int command = (extractedBuff[5] & 0xFF) | ((extractedBuff[4] << 8) & 0xFF00);
-
- MessageBase message;
- if (processedMessage != null && processedMessage.getCommand() == command) {
- message = processedMessage;
- } else {
- // get it from hash table
- message = MessageHashTable_k.findMessage(command);
- }
-
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff));
-
- // process the message content
- message.received = true;
- message.handleMessage(extractedBuff);
- synchronized (message) {
- message.notify();
- }
- }
- }
- } catch (Exception e) {
- if (e.getMessage().indexOf("bt socket closed") < 0)
- log.error("Thread exception: ", e);
- mKeepRunning = false;
- }
- disconnect("EndOfLoop");
- }
-
- void appendToBuffer(byte[] newData, int gotBytes) {
- // add newData to mReadBuff
- byte[] newReadBuff = new byte[mReadBuff.length + gotBytes];
- System.arraycopy(mReadBuff, 0, newReadBuff, 0, mReadBuff.length);
- System.arraycopy(newData, 0, newReadBuff, mReadBuff.length, gotBytes);
- mReadBuff = newReadBuff;
- }
-
- byte[] cutMessageFromBuffer() {
- if (mReadBuff[0] == (byte) 0x7E && mReadBuff[1] == (byte) 0x7E) {
- int length = (mReadBuff[2] & 0xFF) + 7;
- // Check if we have enough data
- if (mReadBuff.length < length) {
- return null;
- }
- if (mReadBuff[length - 2] != (byte) 0x2E || mReadBuff[length - 1] != (byte) 0x2E) {
- log.error("wrong packet lenght=" + length + " data " + MessageBase.toHexString(mReadBuff));
- disconnect("wrong packet");
- return null;
- }
-
- short crc = CRC.getCrc16(mReadBuff, 3, length - 7);
- byte crcByte0 = (byte) (crc >> 8 & 0xFF);
- byte crcByte1 = (byte) (crc & 0xFF);
-
- byte crcByte0received = mReadBuff[length - 4];
- byte crcByte1received = mReadBuff[length - 3];
-
- if (crcByte0 != crcByte0received || crcByte1 != crcByte1received) {
- log.error("CRC Error" + String.format("%02x ", crcByte0) + String.format("%02x ", crcByte1) + String.format("%02x ", crcByte0received) + String.format("%02x ", crcByte1received));
- disconnect("crc error");
- return null;
- }
- // Packet is verified here. extract data
- byte[] extractedBuff = new byte[length];
- System.arraycopy(mReadBuff, 0, extractedBuff, 0, length);
- // remove extracted data from read buffer
- byte[] unprocessedData = new byte[mReadBuff.length - length];
- System.arraycopy(mReadBuff, length, unprocessedData, 0, unprocessedData.length);
- mReadBuff = unprocessedData;
- return extractedBuff;
- } else {
- log.error("Wrong beginning of packet len=" + mReadBuff.length + " " + MessageBase.toHexString(mReadBuff));
- disconnect("Wrong beginning of packet");
- return null;
- }
- }
-
- @Override
- public synchronized void sendMessage(MessageBase message) {
- if (!mRfCommSocket.isConnected()) {
- log.error("Socket not connected on sendMessage");
- return;
- }
- processedMessage = message;
-
- byte[] messageBytes = message.getRawMessageBytes();
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes));
-
- try {
- mOutputStream.write(messageBytes);
- } catch (Exception e) {
- log.error("sendMessage write exception: ", e);
- }
-
- synchronized (message) {
- try {
- message.wait(5000);
- } catch (InterruptedException e) {
- log.error("sendMessage InterruptedException", e);
- }
- }
-
- SystemClock.sleep(200);
- if (!message.received) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.warn("Reply not received " + message.getMessageName());
- if (message.getCommand() == 0xF0F1) {
- DanaRPump.getInstance().isNewPump = false;
- log.error("Old firmware detected");
- }
- }
- }
-
- @Override
- public void disconnect(String reason) {
- mKeepRunning = false;
- try {
- mInputStream.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- mOutputStream.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- mRfCommSocket.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- System.runFinalization();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug("Disconnected: " + reason);
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MessageHashTable_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MessageHashTable_k.java
deleted file mode 100644
index 422391c127..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRKorean/comm/MessageHashTable_k.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRKorean.comm;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.HashMap;
-
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.*;
-
-/**
- * Created by mike on 28.05.2016.
- */
-public class MessageHashTable_k {
- private static Logger log = LoggerFactory.getLogger(MessageHashTable_k.class);
-
- public static HashMap messages = null;
-
- static {
- if (messages == null) {
- messages = new HashMap();
- put(new MsgBolusStop()); // 0x0101 CMD_MEALINS_STOP
- put(new MsgBolusStart()); // 0x0102 CMD_MEALINS_START_DATA
- put(new MsgBolusProgress()); // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
- put(new MsgStatusProfile()); // 0x0204 CMD_PUMP_CALCULATION_SETTING
- put(new MsgStatusTempBasal()); // 0x0205 CMD_PUMP_EXERCISE_MODE
- put(new MsgStatusBolusExtended()); // 0x0207 CMD_PUMP_EXPANS_INS_I
- put(new MsgStatusBasic_k()); // 0x020A CMD_PUMP_INITVIEW_I
- put(new MsgStatus_k()); // 0x020B CMD_PUMP_STATUS
- put(new MsgInitConnStatusTime_k()); // 0x0301 CMD_PUMPINIT_TIME_INFO
- put(new MsgInitConnStatusBolus_k()); // 0x0302 CMD_PUMPINIT_BOLUS_INFO
- put(new MsgInitConnStatusBasic_k()); // 0x0303 CMD_PUMPINIT_INIT_INFO
- put(new MsgSetTempBasalStart()); // 0x0401 CMD_PUMPSET_EXERCISE_S
- put(new MsgSetCarbsEntry()); // 0x0402 CMD_PUMPSET_HIS_S
- put(new MsgSetTempBasalStop()); // 0x0403 CMD_PUMPSET_EXERCISE_STOP
- put(new MsgSetExtendedBolusStop()); // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP
- put(new MsgSetExtendedBolusStart()); // 0x0407 CMD_PUMPSET_EXPANS_INS_S
- put(new MsgError()); // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS
- put(new MsgPCCommStart()); // 0x3001 CMD_CONNECT
- put(new MsgPCCommStop()); // 0x3002 CMD_DISCONNECT
- put(new MsgHistoryBolus()); // 0x3101 CMD_HISTORY_MEAL_INS
- put(new MsgHistoryDailyInsulin()); // 0x3102 CMD_HISTORY_DAY_INS
- put(new MsgHistoryGlucose()); // 0x3104 CMD_HISTORY_GLUCOSE
- put(new MsgHistoryAlarm()); // 0x3105 CMD_HISTORY_ALARM
- put(new MsgHistoryCarbo()); // 0x3107 CMD_HISTORY_CARBOHY
- put(new MsgSettingBasal_k()); // 0x3202 CMD_SETTING_V_BASAL_INS_I
- put(new MsgSettingMeal()); // 0x3203 CMD_SETTING_V_MEAL_SETTING_I
- put(new MsgSettingProfileRatios()); // 0x3204 CMD_SETTING_V_CCC_I
- put(new MsgSettingMaxValues()); // 0x3205 CMD_SETTING_V_MAX_VALUE_I
- put(new MsgSettingBasalProfileAll_k()); // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL
- put(new MsgSettingShippingInfo()); // 0x3207 CMD_SETTING_V_SHIPPING_I
- put(new MsgSettingGlucose()); // 0x3209 CMD_SETTING_V_GLUCOSEandEASY
- put(new MsgSettingPumpTime()); // 0x320A CMD_SETTING_V_TIME_I
- put(new MsgSetSingleBasalProfile()); // 0x3302 CMD_SETTING_BASAL_INS_S
- put(new MsgHistoryAll()); // 0x41F2 CMD_HISTORY_ALL
- put(new MsgHistoryNewDone()); // 0x42F1 CMD_HISTORY_NEW_DONE
- put(new MsgHistoryNew()); // 0x42F2 CMD_HISTORY_NEW
- put(new MsgCheckValue_k()); // 0xF0F1 CMD_PUMP_CHECK_VALUE
- }
- }
-
- public static void put(MessageBase message) {
- int command = message.getCommand();
- //String name = MessageOriginalNames.getName(command);
- messages.put(command, message);
- //log.debug(String.format("%04x ", command) + " " + name);
- }
-
- public static MessageBase findMessage(Integer command) {
- if (messages.containsKey(command)) {
- return messages.get(command);
- } else {
- return new MessageBase();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSDeviceChange.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSDeviceChange.java
deleted file mode 100644
index dd9b86ebce..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSDeviceChange.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 05.09.2017.
- */
-
-public class EventDanaRSDeviceChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPacket.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPacket.java
deleted file mode 100644
index e42b6b1440..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPacket.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-import info.nightscout.androidaps.plugins.PumpDanaRS.comm.DanaRS_Packet;
-
-/**
- * Created by mike on 01.09.2017.
- */
-
-public class EventDanaRSPacket extends Event{
- public EventDanaRSPacket(DanaRS_Packet data) {
- this.data = data;
- }
-
- public DanaRS_Packet data;
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPairingSuccess.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPairingSuccess.java
deleted file mode 100644
index 433cdec9bf..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/events/EventDanaRSPairingSuccess.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 01.09.2017.
- */
-
-public class EventDanaRSPairingSuccess extends Event{
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java
deleted file mode 100644
index 61047a8d5a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/SerialIOThread.java
+++ /dev/null
@@ -1,209 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRv2;
-
-import android.bluetooth.BluetoothSocket;
-import android.os.SystemClock;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.PumpDanaR.DanaRPump;
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.PumpDanaR.services.AbstractSerialIOThread;
-import info.nightscout.androidaps.plugins.PumpDanaRv2.comm.MessageHashTable_v2;
-import info.nightscout.utils.CRC;
-
-/**
- * Created by mike on 17.07.2016.
- */
-public class SerialIOThread extends AbstractSerialIOThread {
- private static Logger log = LoggerFactory.getLogger(L.PUMPBTCOMM);
-
- private InputStream mInputStream = null;
- private OutputStream mOutputStream = null;
- private BluetoothSocket mRfCommSocket;
-
- private boolean mKeepRunning = true;
- private byte[] mReadBuff = new byte[0];
-
- private MessageBase processedMessage;
-
- public SerialIOThread(BluetoothSocket rfcommSocket) {
- super();
-
- mRfCommSocket = rfcommSocket;
- try {
- mOutputStream = mRfCommSocket.getOutputStream();
- mInputStream = mRfCommSocket.getInputStream();
- } catch (IOException e) {
- log.error("Unhandled exception", e);
- }
- this.start();
- }
-
- @Override
- public final void run() {
- try {
- while (mKeepRunning) {
- int availableBytes = mInputStream.available();
- // Ask for 1024 byte (or more if available)
- byte[] newData = new byte[Math.max(1024, availableBytes)];
- int gotBytes = mInputStream.read(newData);
- // When we are here there is some new data available
- appendToBuffer(newData, gotBytes);
-
- // process all messages we already got
- while (mReadBuff.length > 3) { // 3rd byte is packet size. continue only if we an determine packet size
- byte[] extractedBuff = cutMessageFromBuffer();
- if (extractedBuff == null)
- break; // message is not complete in buffer (wrong packet calls disconnection)
-
- int command = (extractedBuff[5] & 0xFF) | ((extractedBuff[4] << 8) & 0xFF00);
-
- MessageBase message;
- if (processedMessage != null && processedMessage.getCommand() == command) {
- message = processedMessage;
- } else {
- // get it from hash table
- message = MessageHashTable_v2.findMessage(command);
- }
-
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug("<<<<< " + message.getMessageName() + " " + message.toHexString(extractedBuff));
-
- // process the message content
- message.received = true;
- message.handleMessage(extractedBuff);
- synchronized (message) {
- message.notify();
- }
- }
- }
- } catch (Exception e) {
- if (e.getMessage().indexOf("bt socket closed") < 0)
- log.error("Thread exception: ", e);
- mKeepRunning = false;
- }
- disconnect("EndOfLoop");
- }
-
- void appendToBuffer(byte[] newData, int gotBytes) {
- // add newData to mReadBuff
- byte[] newReadBuff = new byte[mReadBuff.length + gotBytes];
- System.arraycopy(mReadBuff, 0, newReadBuff, 0, mReadBuff.length);
- System.arraycopy(newData, 0, newReadBuff, mReadBuff.length, gotBytes);
- mReadBuff = newReadBuff;
- }
-
- byte[] cutMessageFromBuffer() {
- if (mReadBuff[0] == (byte) 0x7E && mReadBuff[1] == (byte) 0x7E) {
- int length = (mReadBuff[2] & 0xFF) + 7;
- // Check if we have enough data
- if (mReadBuff.length < length) {
- return null;
- }
- if (mReadBuff[length - 2] != (byte) 0x2E || mReadBuff[length - 1] != (byte) 0x2E) {
- log.error("wrong packet lenght=" + length + " data " + MessageBase.toHexString(mReadBuff));
- disconnect("wrong packet");
- return null;
- }
-
- short crc = CRC.getCrc16(mReadBuff, 3, length - 7);
- byte crcByte0 = (byte) (crc >> 8 & 0xFF);
- byte crcByte1 = (byte) (crc & 0xFF);
-
- byte crcByte0received = mReadBuff[length - 4];
- byte crcByte1received = mReadBuff[length - 3];
-
- if (crcByte0 != crcByte0received || crcByte1 != crcByte1received) {
- log.error("CRC Error" + String.format("%02x ", crcByte0) + String.format("%02x ", crcByte1) + String.format("%02x ", crcByte0received) + String.format("%02x ", crcByte1received));
- disconnect("crc error");
- return null;
- }
- // Packet is verified here. extract data
- byte[] extractedBuff = new byte[length];
- System.arraycopy(mReadBuff, 0, extractedBuff, 0, length);
- // remove extracted data from read buffer
- byte[] unprocessedData = new byte[mReadBuff.length - length];
- System.arraycopy(mReadBuff, length, unprocessedData, 0, unprocessedData.length);
- mReadBuff = unprocessedData;
- return extractedBuff;
- } else {
- log.error("Wrong beginning of packet len=" + mReadBuff.length + " " + MessageBase.toHexString(mReadBuff));
- disconnect("Wrong beginning of packet");
- return null;
- }
- }
-
- @Override
- public synchronized void sendMessage(MessageBase message) {
- if (!mRfCommSocket.isConnected()) {
- log.error("Socket not connected on sendMessage");
- return;
- }
- processedMessage = message;
-
- byte[] messageBytes = message.getRawMessageBytes();
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(">>>>> " + message.getMessageName() + " " + message.toHexString(messageBytes));
-
- try {
- mOutputStream.write(messageBytes);
- } catch (Exception e) {
- log.error("sendMessage write exception: ", e);
- }
-
- synchronized (message) {
- try {
- message.wait(5000);
- } catch (InterruptedException e) {
- log.error("sendMessage InterruptedException", e);
- }
- }
-
- SystemClock.sleep(200);
- if (!message.received) {
- log.error("Reply not received " + message.getMessageName());
- if (message.getCommand() == 0xF0F1) {
- DanaRPump.getInstance().isNewPump = false;
- log.error("Old firmware detected");
- }
- }
- }
-
- @Override
- public void disconnect(String reason) {
- mKeepRunning = false;
- try {
- mInputStream.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- mOutputStream.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- mRfCommSocket.close();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- try {
- System.runFinalization();
- } catch (Exception e) {
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug(e.getMessage());
- }
- if (L.isEnabled(L.PUMPBTCOMM))
- log.debug("Disconnected: " + reason);
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java
deleted file mode 100644
index c95a800128..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRv2/comm/MessageHashTable_v2.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpDanaRv2.comm;
-
-import java.util.HashMap;
-
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.MessageBase;
-import info.nightscout.androidaps.plugins.PumpDanaR.comm.*;
-
-
-/**
- * Created by mike on 28.05.2016.
- */
-public class MessageHashTable_v2 {
- public static HashMap messages = null;
-
- static {
- if (messages == null) {
- messages = new HashMap();
- put(new MsgBolusStop()); // 0x0101 CMD_MEALINS_STOP
- put(new MsgBolusStart()); // 0x0102 CMD_MEALINS_START_DATA
- put(new MsgBolusStartWithSpeed()); // 0x0104 CMD_MEALINS_START_DATA_SPEED
- put(new MsgBolusProgress()); // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS
- put(new MsgStatusProfile()); // 0x0204 CMD_PUMP_CALCULATION_SETTING
-
- put(new MsgStatusTempBasal_v2()); // 0x0205 CMD_PUMP_EXERCISE_MODE
- put(new MsgStatusBolusExtended_v2()); // 0x0207 CMD_PUMP_EXPANS_INS_I
-
- put(new MsgStatusBasic()); // 0x020A CMD_PUMP_INITVIEW_I
- put(new MsgStatus()); // 0x020B CMD_PUMP_STATUS
- put(new MsgInitConnStatusTime()); // 0x0301 CMD_PUMPINIT_TIME_INFO
- put(new MsgInitConnStatusBolus()); // 0x0302 CMD_PUMPINIT_BOLUS_INFO
- put(new MsgInitConnStatusBasic()); // 0x0303 CMD_PUMPINIT_INIT_INFO
- put(new MsgInitConnStatusOption()); // 0x0304 CMD_PUMPINIT_OPTION
- put(new MsgSetTempBasalStart()); // 0x0401 CMD_PUMPSET_EXERCISE_S
- put(new MsgSetCarbsEntry()); // 0x0402 CMD_PUMPSET_HIS_S
- put(new MsgSetTempBasalStop()); // 0x0403 CMD_PUMPSET_EXERCISE_STOP
- put(new MsgSetExtendedBolusStop()); // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP
- put(new MsgSetExtendedBolusStart()); // 0x0407 CMD_PUMPSET_EXPANS_INS_S
- put(new MsgError()); // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS
- put(new MsgPCCommStart()); // 0x3001 CMD_CONNECT
- put(new MsgPCCommStop()); // 0x3002 CMD_DISCONNECT
- put(new MsgHistoryBolus()); // 0x3101 CMD_HISTORY_MEAL_INS
- put(new MsgHistoryDailyInsulin()); // 0x3102 CMD_HISTORY_DAY_INS
- put(new MsgHistoryGlucose()); // 0x3104 CMD_HISTORY_GLUCOSE
- put(new MsgHistoryAlarm()); // 0x3105 CMD_HISTORY_ALARM
- put(new MsgHistoryError()); // 0x3106 CMD_HISTORY_ERROR
- put(new MsgHistoryCarbo()); // 0x3107 CMD_HISTORY_CARBOHY
- put(new MsgHistoryRefill()); // 0x3108 CMD_HISTORY_REFILL
- put(new MsgHistorySuspend()); // 0x3109 CMD_HISTORY_SUSPEND
- put(new MsgHistoryBasalHour()); // 0x310A CMD_HISTORY_BASAL_HOUR
- put(new MsgHistoryDone()); // 0x31F1 CMD_HISTORY_DONT_USED
- put(new MsgSettingBasal()); // 0x3202 CMD_SETTING_V_BASAL_INS_I
- put(new MsgSettingMeal()); // 0x3203 CMD_SETTING_V_MEAL_SETTING_I
- put(new MsgSettingProfileRatios()); // 0x3204 CMD_SETTING_V_CCC_I
- put(new MsgSettingMaxValues()); // 0x3205 CMD_SETTING_V_MAX_VALUE_I
- put(new MsgSettingBasalProfileAll()); // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL
- put(new MsgSettingShippingInfo()); // 0x3207 CMD_SETTING_V_SHIPPING_I
- put(new MsgSettingGlucose()); // 0x3209 CMD_SETTING_V_GLUCOSEandEASY
- put(new MsgSettingPumpTime()); // 0x320A CMD_SETTING_V_TIME_I
- put(new MsgSettingUserOptions()); // 0x320B CMD_SETTING_V_USER_OPTIONS
- put(new MsgSettingActiveProfile()); // 0x320C CMD_SETTING_V_PROFILE_NUMBER
- put(new MsgSettingProfileRatiosAll()); // 0x320D CMD_SETTING_V_CIR_CF_VALUE
- put(new MsgSetSingleBasalProfile()); // 0x3302 CMD_SETTING_BASAL_INS_S
- put(new MsgSetBasalProfile()); // 0x3306 CMD_SETTING_BASAL_PROFILE_S
- put(new MsgSetUserOptions()); // 0x330B CMD_SETTING_USER_OPTIONS_S
- put(new MsgSetActivateBasalProfile()); // 0x330C CMD_SETTING_PROFILE_NUMBER_S
- put(new MsgHistoryAllDone()); // 0x41F1 CMD_HISTORY_ALL_DONE
- put(new MsgHistoryAll()); // 0x41F2 CMD_HISTORY_ALL
- put(new MsgHistoryNewDone()); // 0x42F1 CMD_HISTORY_NEW_DONE
- put(new MsgHistoryNew()); // 0x42F2 CMD_HISTORY_NEW
- put(new MsgCheckValue_v2()); // 0xF0F1 CMD_PUMP_CHECK_VALUE
- put(new MsgStatusAPS_v2()); // 0xE001 CMD_PUMPSTATUS_APS
- put(new MsgSetAPSTempBasalStart_v2()); // 0xE002 CMD_PUMPSET_APSTEMP
- put(new MsgHistoryEvents_v2()); // 0xE003 CMD_GET_HISTORY
- put(new MsgSetHistoryEntry_v2()); // 0xE004 CMD_SET_HISTORY_ENTRY
- }
- }
-
- public static void put(MessageBase message) {
- int command = message.getCommand();
- //String name = MessageOriginalNames.getName(command);
- messages.put(command, message);
- //log.debug(String.format("%04x ", command) + " " + name);
- }
-
- public static MessageBase findMessage(Integer command) {
- if (messages.containsKey(command)) {
- return messages.get(command);
- } else {
- return new MessageBase();
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightFragment.java
deleted file mode 100644
index 5d3c3850b3..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightFragment.java
+++ /dev/null
@@ -1,114 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight;
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import android.support.annotation.Nullable;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.LinearLayout;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.ui.StatusItemViewAdapter;
-import info.nightscout.utils.FabricPrivacy;
-
-
-public class InsightFragment extends SubscriberFragment {
- private static final Logger log = LoggerFactory.getLogger(L.PUMP);
- private static final Handler sLoopHandler = new Handler();
- private static volatile boolean refresh = false;
- private static volatile boolean pending = false;
- StatusItemViewAdapter viewAdapter;
- LinearLayout holder;
- private final Runnable sRefreshLoop = new Runnable() {
- @Override
- public void run() {
- pending = false;
- updateGUI();
- if (refresh) {
- scheduleRefresh();
- }
- }
- };
-
- private synchronized void scheduleRefresh() {
- if (!pending) {
- pending = true;
- sLoopHandler.postDelayed(sRefreshLoop, 30 * 1000L);
- }
- }
-
- @Override
- public void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- final View view = inflater.inflate(R.layout.insightpump_fragment, container, false);
- holder = (LinearLayout) view.findViewById(R.id.insightholder);
- viewAdapter = new StatusItemViewAdapter(getActivity(), holder);
-
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
-
- @Override
- public void setUserVisibleHint(boolean visible) {
- super.setUserVisibleHint(visible);
- if (visible) {
- refresh = true;
- pending = false;
- updateGUI();
- scheduleRefresh();
- } else {
- refresh = false;
- //sLoopHandler.removeCallbacksAndMessages(null);
- }
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventInsightUpdateGui ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- final Activity activity = getActivity();
- if (activity != null && holder != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- final InsightPlugin insightPlugin = InsightPlugin.getPlugin();
- final List l = insightPlugin.getStatusItems(refresh);
-
- holder.removeAllViews();
-
- for (StatusItem row : l) {
- viewAdapter.inflateStatus(row);
- }
-
- }
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java
deleted file mode 100644
index c72da31fdf..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/InsightPlugin.java
+++ /dev/null
@@ -1,935 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight;
-
-import android.content.DialogInterface;
-import android.os.SystemClock;
-import android.support.v4.app.FragmentActivity;
-import android.support.v7.app.AlertDialog;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.text.DecimalFormat;
-import java.util.ArrayList;
-import java.util.List;
-
-import info.nightscout.androidaps.BuildConfig;
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.interfaces.ConstraintsInterface;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.PumpDescription;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderFragment;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.Overview.events.EventDismissNotification;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
-import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.CancelBolusSilentlyTaskRunner;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.CancelTBRSilentlyTaskRunner;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.Connector;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.SetTBRTaskRunner;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.StatusTaskRunner;
-import info.nightscout.androidaps.plugins.PumpInsight.connector.WriteBasalProfileTaskRunner;
-import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightCallback;
-import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
-import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver;
-import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
-import info.nightscout.androidaps.plugins.Treatments.Treatment;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.SP;
-import sugar.free.sightparser.applayer.descriptors.ActiveBolus;
-import sugar.free.sightparser.applayer.descriptors.ActiveBolusType;
-import sugar.free.sightparser.applayer.descriptors.MessagePriority;
-import sugar.free.sightparser.applayer.descriptors.PumpStatus;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.BolusMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.ExtendedBolusMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.StandardBolusMessage;
-import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
-import sugar.free.sightparser.handling.SingleMessageTaskRunner;
-import sugar.free.sightparser.handling.TaskRunner;
-import sugar.free.sightparser.pipeline.Status;
-
-import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.getRecordUniqueID;
-
-
-/**
- * Created by jamorham on 23/01/2018.
- *
- * Connects to SightRemote app service using SightParser library
- *
- * SightRemote and SightParser created by Tebbe Ubben
- *
- * Original proof of concept SightProxy by jamorham
- */
-
-@SuppressWarnings("AccessStaticViaInstance")
-public class InsightPlugin extends PluginBase implements PumpInterface, ConstraintsInterface {
- private Logger log = LoggerFactory.getLogger(L.PUMP);
-
- private static volatile InsightPlugin plugin;
-
- public static InsightPlugin getPlugin() {
- if (plugin == null) {
- plugin = new InsightPlugin();
- }
- return plugin;
- }
-
- private static final long BUSY_WAIT_TIME = 20000;
- private static Integer batteryPercent = 0;
- private static Integer reservoirInUnits = 0;
- private static boolean initialized = false;
- private static volatile boolean update_pending = false;
- private StatusTaskRunner.Result statusResult;
- private long statusResultTime = -1;
- private long lastDataTime = 0;
- private boolean fauxTBRcancel = true;
- private PumpDescription pumpDescription = new PumpDescription();
- private double basalRate = 0;
- private Connector connector;
- private volatile boolean connector_enabled = false;
- private List profileBlocks;
-
- private InsightPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.PUMP)
- .fragmentClass(InsightFragment.class.getName())
- .pluginName(R.string.insightpump)
- .shortName(R.string.insightpump_shortname)
- .preferencesId(R.xml.pref_insightpump)
- .description(R.string.description_pump_insight)
- );
- if (L.isEnabled(L.PUMP))
- log.debug("InsightPlugin instantiated");
- pumpDescription.setPumpDescription(PumpType.AccuChekInsight);
- }
-
-
- private static void updateGui() {
- update_pending = false;
- MainApp.bus().post(new EventInsightUpdateGui());
- }
-
- private static void pushCallbackEvent(EventInsightCallback e) {
- MainApp.bus().post(e);
- }
-
- @Override
- protected void onStart() {
- if (!connector_enabled) {
- synchronized (this) {
- if (!connector_enabled) {
- if (L.isEnabled(L.PUMP))
- log.debug("Instantiating connector");
- connector_enabled = true;
- this.connector = Connector.get();
- this.connector.init();
- }
- }
- }
- super.onStart();
- }
-
- protected void onStop() {
- if (connector_enabled) {
- synchronized (this) {
- if (connector_enabled) {
- if (L.isEnabled(L.PUMP))
- log.debug("Shutting down connector");
- Connector.get().shutdown();
- connector_enabled = false;
- }
- }
- }
- }
-
- @Override
- public boolean isFakingTempsByExtendedBoluses() {
- return true;
- }
-
- @Override
- public PumpEnactResult loadTDDs() {
- PumpEnactResult result = new PumpEnactResult();
- result.success = true;
- return result;
- }
-
- @Override
- public void switchAllowed(ConfigBuilderFragment.PluginViewHolder.PluginSwitcher pluginSwitcher, FragmentActivity context) {
- boolean allowHardwarePump = SP.getBoolean("allow_hardware_pump", false);
- if (allowHardwarePump || context == null) {
- pluginSwitcher.invoke();
- } else {
- AlertDialog.Builder builder = new AlertDialog.Builder(context);
- builder.setMessage(R.string.allow_hardware_pump_text)
- .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- pluginSwitcher.invoke();
- SP.putBoolean("allow_hardware_pump", true);
- log.debug("First time HW pump allowed!");
- }
- })
- .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int id) {
- pluginSwitcher.cancel();
- log.debug("User does not allow switching to HW pump!");
- }
- });
- builder.create().show();
- }
- }
-
- @Override
- public boolean isInitialized() {
- return initialized;
- }
-
- @Override
- public boolean isSuspended() {
- return !isPumpRunning();
- }
-
- @Override
- public boolean isBusy() {
- return false;
- }
-
- @Override
- public boolean isConnected() {
- return Connector.get().isPumpConnected();
- }
-
- @Override
- public boolean isConnecting() {
- return Connector.get().isPumpConnecting();
- }
-
- @Override
- public boolean isHandshakeInProgress() {
- return false;
- }
-
- @Override
- public void finishHandshaking() {
- }
-
- @Override
- public void connect(String reason) {
- if (L.isEnabled(L.PUMP))
- log.debug("InsightPlugin::connect()");
- try {
- if (!connector.isPumpConnected()) {
- if (Helpers.ratelimit("insight-connect-timer", 40)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Actually requesting a connect");
- connector.connectToPump();
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Already connected");
- }
- } catch (NullPointerException e) {
- log.error("Could not sconnect - null pointer: " + e);
- }
-
- // TODO review
- if (!Config.NSCLIENT)
- NSUpload.uploadDeviceStatus();
- }
-
- @Override
- public void disconnect(String reason) {
- if (L.isEnabled(L.PUMP))
- log.debug("InsightPlugin::disconnect()");
- try {
- if (!SP.getBoolean("insight_always_connected", false)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Requesting disconnect");
- connector.disconnectFromPump();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Not disconnecting due to preference");
- }
- } catch (NullPointerException e) {
- log.error("Could not disconnect - null pointer: " + e);
- }
- }
-
- @Override
- public void stopConnecting() {
- if (L.isEnabled(L.PUMP))
- log.debug("InsightPlugin::stopConnecting()");
- try {
- if (isConnecting()) {
- if (!SP.getBoolean("insight_always_connected", false)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Requesting disconnect");
- connector.disconnectFromPump();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Not disconnecting due to preference");
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Not currently trying to connect so not stopping connection");
- }
- } catch (NullPointerException e) {
- log.error("Could not stop connecting - null pointer: " + e);
- }
- }
-
- @Override
- public void getPumpStatus() {
- if (L.isEnabled(L.PUMP))
- log.debug("getPumpStatus");
- if (Connector.get().isPumpConnected()) {
- if (L.isEnabled(L.PUMP))
- log.debug("is connected.. requesting status");
- try {
- setStatusResult(fetchTaskRunner(new StatusTaskRunner(connector.getServiceConnector()), StatusTaskRunner.Result.class));
- if (L.isEnabled(L.PUMP))
- log.debug("GOT STATUS RESULT!!! PARTY WOOHOO!!!");
- statusResultTime = Helpers.tsl();
- processStatusResult();
- updateGui();
- connector.requestHistoryReSync();
- connector.requestHistorySync();
- } catch (Exception e) {
- log.error("StatusTaskRunner wasn't successful.");
- if (connector.getServiceConnector().isConnectedToService() && connector.getServiceConnector().getStatus() != Status.CONNECTED) {
- if (Helpers.ratelimit("insight-reconnect", 2)) {
- Connector.connectToPump();
- updateGui();
- }
- }
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("not connected.. not requesting status");
- }
- }
-
- public void setStatusResult(StatusTaskRunner.Result result) {
- this.statusResult = result;
- this.pumpDescription.basalMinimumRate = result.minimumBasalAmount;
- this.pumpDescription.basalMaximumRate = result.maximumBasalAmount;
- }
-
- @Override
- public PumpEnactResult setNewBasalProfile(Profile profile) {
- PumpEnactResult result = new PumpEnactResult();
- if (!isInitialized()) {
- log.error("setNewBasalProfile not initialized");
- Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, MainApp.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT);
- MainApp.bus().post(new EventNewNotification(notification));
- result.comment = MainApp.gs(R.string.pumpNotInitializedProfileNotSet);
- return result;
- }
- MainApp.bus().post(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED));
- List profileBlocks = new ArrayList<>();
- for (int i = 0; i < profile.getBasalValues().length; i++) {
- Profile.BasalValue basalValue = profile.getBasalValues()[i];
- Profile.BasalValue nextValue = null;
- if (profile.getBasalValues().length > i + 1)
- nextValue = profile.getBasalValues()[i + 1];
- profileBlocks.add(new BRProfileBlock.ProfileBlock((((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60), Helpers.roundDouble(basalValue.value, 2)));
- if (L.isEnabled(L.PUMP))
- log.debug("setNewBasalProfile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
- }
- try {
- fetchTaskRunner(new WriteBasalProfileTaskRunner(connector.getServiceConnector(), profileBlocks));
- MainApp.bus().post(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE));
- Notification notification = new Notification(Notification.PROFILE_SET_OK, MainApp.gs(R.string.profile_set_ok), Notification.INFO, 60);
- MainApp.bus().post(new EventNewNotification(notification));
- result.success = true;
- result.enacted = true;
- result.comment = "OK";
- this.profileBlocks = profileBlocks;
- } catch (Exception e) {
- Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, MainApp.gs(R.string.failedupdatebasalprofile), Notification.URGENT);
- MainApp.bus().post(new EventNewNotification(notification));
- result.comment = MainApp.gs(R.string.failedupdatebasalprofile);
- }
- return result;
- }
-
- @Override
- public boolean isThisProfileSet(Profile profile) {
- if (!isInitialized() || profileBlocks == null) return true;
- if (profile.getBasalValues().length != profileBlocks.size()) return false;
- for (int i = 0; i < profileBlocks.size(); i++) {
- BRProfileBlock.ProfileBlock profileBlock = profileBlocks.get(i);
- Profile.BasalValue basalValue = profile.getBasalValues()[i];
- Profile.BasalValue nextValue = null;
- if (profile.getBasalValues().length > i + 1)
- nextValue = profile.getBasalValues()[i + 1];
- if (L.isEnabled(L.PUMP))
- log.debug("isThisProfileSet - Comparing block: Pump: " + profileBlock.getAmount() + " for " + profileBlock.getDuration()
- + " Profile: " + basalValue.value + " for " + Integer.toString(((nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds) / 60));
- if (profileBlock.getDuration() * 60 != (nextValue != null ? nextValue.timeAsSeconds : 24 * 60 * 60) - basalValue.timeAsSeconds)
- return false;
- //Allow a little imprecision due to rounding errors
- if (Math.abs(profileBlock.getAmount() - Helpers.roundDouble(basalValue.value, 2)) >= 0.01D)
- return false;
- }
- return true;
- }
-
- @Override
- public long lastDataTime() {
- return lastDataTime;
- }
-
- @Override
- public double getBaseBasalRate() {
- return basalRate;
- }
-
- public String getBaseBasalRateString() {
- final DecimalFormat df = new DecimalFormat("#.##");
- return df.format(basalRate);
- }
-
- @Override
- public PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) {
- final PumpEnactResult result = new PumpEnactResult();
- result.bolusDelivered = detailedBolusInfo.insulin;
- result.carbsDelivered = detailedBolusInfo.carbs;
- result.enacted = result.bolusDelivered > 0 || result.carbsDelivered > 0;
- result.comment = MainApp.gs(R.string.virtualpump_resultok);
-
- result.percent = 100;
-
- int bolusId = 0;
-
- // is there an insulin component to the treatment?
- if (detailedBolusInfo.insulin > 0) {
- try {
- bolusId = deliverBolus(detailedBolusInfo.insulin);
- result.success = true;
- detailedBolusInfo.pumpId = getRecordUniqueID(bolusId);
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- } else {
- result.success = true; // always true with carb only treatments
- }
-
- if (result.success) {
- if (L.isEnabled(L.PUMP))
- log.debug("Success!");
-
- Treatment t = new Treatment();
- t.isSMB = detailedBolusInfo.isSMB;
- final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = t;
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), 0F);
- bolusingEvent.bolusId = bolusId;
- bolusingEvent.percent = 0;
- MainApp.bus().post(bolusingEvent);
- TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Failure to deliver treatment");
- }
-
- if (L.isEnabled(L.PUMP))
- log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
-
- updateGui();
- connector.tryToGetPumpStatusAgain();
-
- if (result.success) while (true) {
- try {
- Thread.sleep(500);
- final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- ActiveBolusesMessage activeBolusesMessage = fetchSingleMessage(new ActiveBolusesMessage(), ActiveBolusesMessage.class);
- ActiveBolus activeBolus = null;
- if (activeBolusesMessage.getBolus1() != null && activeBolusesMessage.getBolus1().getBolusID() == bolusingEvent.bolusId)
- activeBolus = activeBolusesMessage.getBolus1();
- else if (activeBolusesMessage.getBolus2() != null && activeBolusesMessage.getBolus2().getBolusID() == bolusingEvent.bolusId)
- activeBolus = activeBolusesMessage.getBolus2();
- else if (activeBolusesMessage.getBolus3() != null && activeBolusesMessage.getBolus3().getBolusID() == bolusingEvent.bolusId)
- activeBolus = activeBolusesMessage.getBolus3();
- if (activeBolus == null) break;
- else {
- int percentBefore = bolusingEvent.percent;
- bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount()));
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), activeBolus.getInitialAmount() - activeBolus.getLeftoverAmount());
- if (percentBefore != bolusingEvent.percent) MainApp.bus().post(bolusingEvent);
- }
- } catch (Exception e) {
- break;
- }
- }
-
- connector.requestHistorySync(2000);
- return result;
- }
-
- @Override
- public void stopBolusDelivering() {
- CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
- cancelBolusMessage.setMessagePriority(MessagePriority.HIGHEST);
- cancelBolusMessage.setBolusId(EventOverviewBolusProgress.getInstance().bolusId);
- try {
- fetchSingleMessage(cancelBolusMessage);
- } catch (Exception e) {
- }
- }
-
- // Temporary Basals
-
- @Override
- public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) {
- if (L.isEnabled(L.PUMP))
- log.debug("Set TBR absolute: " + absoluteRate);
- if (getBaseBasalRate() == 0) {
- if (L.isEnabled(L.PUMP))
- log.debug("Base basal rate appears to be zero!");
- return pumpEnactFailure();
- }
- double percent = 100D / getBaseBasalRate() * absoluteRate;
- if (L.isEnabled(L.PUMP))
- log.debug("Calculated requested rate: " + absoluteRate + " base rate: " + getBaseBasalRate() + " percentage: " + percent + "%");
- try {
- if (percent > 250) {
- if (L.isEnabled(L.PUMP))
- log.debug("Calculated rate is above 250%, switching to emulation using extended boluses");
- cancelTempBasal(true);
- if (!setExtendedBolus((absoluteRate - getBaseBasalRate()) / 60D * ((double) durationInMinutes), durationInMinutes).success) {
- //Fallback to TBR if setting an extended bolus didn't work
- if (L.isEnabled(L.PUMP))
- log.debug("Setting an extended bolus didn't work, falling back to normal TBR");
- return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
- }
- return new PumpEnactResult().success(true).enacted(true).absolute(absoluteRate).duration(durationInMinutes);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Calculated rate is below or equal to 250%, using normal TBRs");
- cancelExtendedBolus();
- return setTempBasalPercent((int) percent, durationInMinutes, profile, true);
- }
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- }
-
-
- @Override
- public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) {
- if (L.isEnabled(L.PUMP))
- log.debug("Set TBR %");
-
- percent = (int) Math.round(((double) percent) / 10d) * 10;
- if (percent == 100) {
- // This would cause a cancel if a tbr is in progress so treat as a cancel
- return cancelTempBasal(false);
- } else if (percent > 250) percent = 250;
-
- try {
- fetchTaskRunner(new SetTBRTaskRunner(connector.getServiceConnector(), percent, durationInMinutes));
- final TemporaryBasal tempBasal = new TemporaryBasal()
- .date(System.currentTimeMillis())
- .percent(percent)
- .duration(durationInMinutes)
- .source(Source.USER);
- TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
- updateGui();
- if (L.isEnabled(L.PUMP))
- log.debug("Set temp basal " + percent + "% for " + durationInMinutes + "m");
- connector.requestHistorySync(5000);
- connector.tryToGetPumpStatusAgain();
- return new PumpEnactResult().success(true).enacted(true).percent(percent);
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- }
-
-
- @Override
- public PumpEnactResult cancelTempBasal(boolean enforceNew) {
- if (L.isEnabled(L.PUMP))
- log.debug("Cancel TBR called");
-
- try {
- cancelExtendedBolus();
- SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS)
- realTBRCancel();
- SystemClock.sleep(1100); // to be sure db records are at least 1 sec off (for NS)
- updateGui();
- connector.requestHistorySync(5000);
- connector.tryToGetPumpStatusAgain();
- return new PumpEnactResult().success(true).enacted(true).isTempCancel(true);
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- }
-
- private void realTBRCancel() throws Exception {
- if (fetchTaskRunner(new CancelTBRSilentlyTaskRunner(connector.getServiceConnector()), Boolean.class) && TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
- TemporaryBasal tempStop = new TemporaryBasal().date(System.currentTimeMillis()).source(Source.USER);
- TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStop);
- }
- }
-
-
- // Extended Boluses
-
- @Override
- public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) {
- if (L.isEnabled(L.PUMP))
- log.debug("Set Extended bolus " + insulin + " " + durationInMinutes);
- try {
- ExtendedBolusMessage extendedBolusMessage = new ExtendedBolusMessage();
- extendedBolusMessage.setAmount(insulin);
- extendedBolusMessage.setDuration(durationInMinutes);
- BolusMessage bolusMessage = fetchSingleMessage(extendedBolusMessage, BolusMessage.class);
- final ExtendedBolus extendedBolus = new ExtendedBolus()
- .date(System.currentTimeMillis())
- .insulin(insulin)
- .durationInMinutes(durationInMinutes)
- .source(Source.USER)
- .pumpId(getRecordUniqueID(bolusMessage.getBolusId()));
- TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
- updateGui();
- connector.requestHistorySync(30000);
- connector.tryToGetPumpStatusAgain();
- return new PumpEnactResult().success(true).enacted(true).duration(durationInMinutes).bolusDelivered(insulin);
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- }
-
- @Override
- public PumpEnactResult cancelExtendedBolus() {
- if (L.isEnabled(L.PUMP))
- log.debug("Cancel Extended bolus called");
-
- Integer bolusId = null;
-
- try {
- bolusId = fetchTaskRunner(new CancelBolusSilentlyTaskRunner(connector.getServiceConnector(), ActiveBolusType.EXTENDED), Integer.class);
- if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- ExtendedBolus exStop = new ExtendedBolus(System.currentTimeMillis());
- exStop.source = Source.USER;
- TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(exStop);
- }
- if (bolusId != null) connector.requestHistorySync(5000);
- connector.tryToGetPumpStatusAgain();
- updateGui();
- return new PumpEnactResult().success(true).enacted(bolusId != null);
- } catch (Exception e) {
- return pumpEnactFailure();
- }
- }
-
-
- private int deliverBolus(double bolusValue) throws Exception {
- if (L.isEnabled(L.PUMP))
- log.debug("DeliverBolus: " + bolusValue);
-
- final StandardBolusMessage message = new StandardBolusMessage();
- message.setAmount(bolusValue);
-
- return fetchSingleMessage(message, BolusMessage.class).getBolusId();
- }
-
- @Override
- public JSONObject getJSONStatus(Profile profile, String profileName) {
- long now = System.currentTimeMillis();
- if (Helpers.msSince(connector.getLastContactTime()) > (60 * 60 * 1000)) {
- if (L.isEnabled(L.PUMP))
- log.debug("getJSONStatus not returning as data likely stale");
- return null;
- }
-
- final JSONObject pump = new JSONObject();
- final JSONObject battery = new JSONObject();
- final JSONObject status = new JSONObject();
- final JSONObject extended = new JSONObject();
- try {
- battery.put("percent", batteryPercent);
- status.put("status", isSuspended() ? "suspended" : "normal");
- status.put("timestamp", DateUtil.toISOString(connector.getLastContactTime()));
- extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION);
- try {
- extended.put("ActiveProfile", ProfileFunctions.getInstance().getProfileName());
- } catch (Exception e) {
- }
- TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(now);
- if (tb != null) {
- extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile));
- extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
- extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
- }
- ExtendedBolus eb = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(now);
- if (eb != null) {
- extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate());
- extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date));
- extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes());
- }
- extended.put("BaseBasalRate", getBaseBasalRate());
- status.put("timestamp", DateUtil.toISOString(now));
-
- pump.put("battery", battery);
- pump.put("status", status);
- pump.put("extended", extended);
- pump.put("reservoir", reservoirInUnits);
- pump.put("clock", DateUtil.toISOString(now));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
- }
- return pump;
- }
-
- @Override
- public String deviceID() {
- return "InsightPump";
- }
-
- @Override
- public PumpDescription getPumpDescription() {
- return pumpDescription;
- }
-
- @Override
- public String shortStatus(boolean veryShort) {
- String msg = gs(R.string.insightpump_shortname) + " Batt: " + batteryPercent + " Reserv: " + reservoirInUnits + " Basal: " + basalRate;
- if (LiveHistory.getStatus().length() > 0) {
- msg += LiveHistory.getStatus();
- }
- return msg;
- }
-
- private void processStatusResult() {
- if (statusResult != null) {
- batteryPercent = statusResult.battery;
- reservoirInUnits = (int) statusResult.cartridge;
- basalRate = statusResult.baseBasalRate;
- profileBlocks = statusResult.basalProfile;
- initialized = true; // basic communication test
- }
- }
-
- private String gs(int id) {
- return MainApp.gs(id);
- }
-
- private boolean isPumpRunning() {
- if (statusResult == null) return true; // assume running if we have no information
- return statusResult.pumpStatus == PumpStatus.STARTED;
- }
-
- List getStatusItems(boolean refresh) {
- final List l = new ArrayList<>();
-
- // Todo last contact time
-
- l.add(new StatusItem(gs(R.string.status_no_colon), connector.getLastStatusMessage()));
- l.add(new StatusItem(gs(R.string.changed), connector.getNiceLastStatusTime()));
-
- boolean pumpRunning;
- // also check time since received
- if (statusResult != null) {
-
- pumpRunning = isPumpRunning();
- if (pumpRunning) {
- l.add(new StatusItem(gs(R.string.pump_basebasalrate_label), getBaseBasalRateString() + "U"));
- } else {
- l.add(new StatusItem(gs(R.string.combo_warning), gs(R.string.pump_stopped_uppercase), StatusItem.Highlight.CRITICAL));
- }
- }
-
- final long offset_ms = Helpers.msSince(statusResultTime);
- final long offset_minutes = offset_ms / 60000;
-
- if (statusResult != null) {
- l.add(new StatusItem(gs(R.string.status_updated), Helpers.niceTimeScalar(Helpers.msSince(statusResultTime)) + " " + gs(R.string.ago)));
- l.add(new StatusItem(gs(R.string.pump_battery_label), batteryPercent + "%", batteryPercent < 100 ?
- (batteryPercent < 90 ?
- (batteryPercent < 70 ?
- (StatusItem.Highlight.BAD) : StatusItem.Highlight.NOTICE) : StatusItem.Highlight.NORMAL) : StatusItem.Highlight.GOOD));
- l.add(new StatusItem(gs(R.string.pump_reservoir_label), reservoirInUnits + "U"));
- try {
- if (statusResult.tbrAmount != 100) {
- l.add(new StatusItem(gs(R.string.insight_active_tbr), statusResult.tbrAmount + "% " + gs(R.string.with) + " "
- + Helpers.qs(statusResult.tbrLeftoverDuration - offset_minutes, 0)
- + " " + gs(R.string.insight_min_left), StatusItem.Highlight.NOTICE));
- }
- } catch (NullPointerException e) {
- // currentTBRMessage may be null
- }
-
- }
-
- if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
- try {
- l.add(new StatusItem(gs(R.string.pump_tempbasal_label), TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis()).toStringFull()));
- } catch (NullPointerException e) {
- //
- }
- }
-
- if (statusResult != null) {
- try {
- statusActiveBolus(statusResult.activeBolus1, offset_minutes, l);
- statusActiveBolus(statusResult.activeBolus2, offset_minutes, l);
- statusActiveBolus(statusResult.activeBolus3, offset_minutes, l);
- } catch (NullPointerException e) {
- // getActiveBolusesMessage() may be null
- }
- }
-
- if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- try {
-
- l.add(new StatusItem(gs(R.string.virtualpump_extendedbolus_label), TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis()).toString()));
- } catch (NullPointerException e) {
- //
- }
- }
-
- l.add(new StatusItem(gs(R.string.log_book), HistoryReceiver.getStatusString()));
-
- if (LiveHistory.getStatus().length() > 0) {
- l.add(new StatusItem(gs(R.string.insight_last_completed_action), LiveHistory.getStatus()));
- }
-
- final String keep_alive_status = Connector.getKeepAliveString();
- if (keep_alive_status != null) {
- l.add(new StatusItem(gs(R.string.insight_keep_alive_status), keep_alive_status));
- }
-
- final List status_statistics = connector.getStatusStatistics();
- if (status_statistics.size() > 0) {
- l.addAll(status_statistics);
- }
-
- if (Helpers.ratelimit("insight-status-ui-refresh", 10)) {
- connector.tryToGetPumpStatusAgain();
- }
- connector.requestHistorySync();
- if (refresh) scheduleGUIUpdate();
-
- return l;
- }
-
- private synchronized void scheduleGUIUpdate() {
- if (!update_pending && connector.uiFresh()) {
- update_pending = true;
- Helpers.runOnUiThreadDelayed(new Runnable() {
- @Override
- public void run() {
- updateGui();
- }
- }, 1000);
- }
- }
-
- private void statusActiveBolus(ActiveBolus activeBolus, long offset_mins, List l) {
- if (activeBolus == null) return;
- switch (activeBolus.getBolusType()) {
-
- case STANDARD:
- l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U", StatusItem.Highlight.NOTICE));
- break;
- case EXTENDED:
- l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_total_with) + " "
- + activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
- break;
- case MULTIWAVE:
- l.add(new StatusItem(activeBolus.getBolusType() + " " + gs(R.string.bolus), activeBolus.getInitialAmount() + "U " + gs(R.string.insight_upfront_with) + " "
- + activeBolus.getLeftoverAmount() + "U " + gs(R.string.insight_remaining_over) + " " + (activeBolus.getDuration() - offset_mins) + " " + gs(R.string.insight_min), StatusItem.Highlight.NOTICE));
-
- break;
- default:
- log.error("ERROR: unknown bolus type! " + activeBolus.getBolusType());
- }
- }
-
- private void fetchTaskRunner(TaskRunner taskRunner) throws Exception {
- fetchTaskRunner(taskRunner, Object.class);
- }
-
- private void fetchSingleMessage(AppLayerMessage message) throws Exception {
- fetchSingleMessage(message, AppLayerMessage.class);
- }
-
- private T fetchTaskRunner(TaskRunner taskRunner, Class resultType) throws Exception {
- try {
- T result = (T) taskRunner.fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
- lastDataTime = System.currentTimeMillis();
- return result;
- } catch (Exception e) {
- log.error("Error while fetching " + taskRunner.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
- throw e;
- }
- }
-
- private T fetchSingleMessage(AppLayerMessage message, Class resultType) throws Exception {
- try {
- T result = (T) new SingleMessageTaskRunner(connector.getServiceConnector(), message).fetchAndWaitUsingLatch(BUSY_WAIT_TIME);
- lastDataTime = System.currentTimeMillis();
- return result;
- } catch (Exception e) {
- log.error("Error while fetching " + message.getClass().getSimpleName() + ": " + e.getClass().getSimpleName());
- throw e;
- }
- }
-
-
- private PumpEnactResult pumpEnactFailure() {
- return new PumpEnactResult().success(false).enacted(false);
- }
-
- // Constraints
-
- @Override
- public Constraint applyBasalPercentConstraints(Constraint percentRate, Profile profile) {
- percentRate.setIfGreater(0, String.format(MainApp.gs(R.string.limitingpercentrate), 0, MainApp.gs(R.string.itmustbepositivevalue)), this);
- percentRate.setIfSmaller(getPumpDescription().maxTempPercent, String.format(MainApp.gs(R.string.limitingpercentrate), getPumpDescription().maxTempPercent, MainApp.gs(R.string.pumplimit)), this);
-
- return percentRate;
- }
-
- @Override
- public Constraint applyBolusConstraints(Constraint insulin) {
- if (statusResult != null) {
- insulin.setIfSmaller(statusResult.maximumBolusAmount, String.format(MainApp.gs(R.string.limitingbolus), statusResult.maximumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
- if (insulin.value() < statusResult.minimumBolusAmount) {
-
- //TODO: Add function to Constraints or use different approach
- // This only works if the interface of the InsightPlugin is called last.
- // If not, another contraint could theoretically set the value between 0 and minimumBolusAmount
-
- insulin.set(0d, String.format(MainApp.gs(R.string.limitingbolus), statusResult.minimumBolusAmount, MainApp.gs(R.string.pumplimit)), this);
- }
- }
- return insulin;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelBolusSilentlyTaskRunner.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelBolusSilentlyTaskRunner.java
deleted file mode 100644
index 7b3108602e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelBolusSilentlyTaskRunner.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import sugar.free.sightparser.applayer.descriptors.ActiveBolusType;
-import sugar.free.sightparser.applayer.descriptors.MessagePriority;
-import sugar.free.sightparser.applayer.descriptors.alerts.Warning38BolusCancelled;
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.CancelBolusMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.DismissAlertMessage;
-import sugar.free.sightparser.applayer.messages.status.ActiveAlertMessage;
-import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.TaskRunner;
-
-// by Tebbe Ubben
-
-public class CancelBolusSilentlyTaskRunner extends TaskRunner {
-
- private ActiveBolusType bolusType;
- private long cancelledAt;
- private int bolusId;
-
- public CancelBolusSilentlyTaskRunner(SightServiceConnector serviceConnector, ActiveBolusType bolusType) {
- super(serviceConnector);
- this.bolusType = bolusType;
- }
-
- @Override
- protected AppLayerMessage run(AppLayerMessage message) throws Exception {
- if (message == null) return new ActiveBolusesMessage();
- else if (message instanceof ActiveBolusesMessage) {
- ActiveBolusesMessage bolusesMessage = (ActiveBolusesMessage) message;
- CancelBolusMessage cancelBolusMessage = new CancelBolusMessage();
- if (bolusesMessage.getBolus1().getBolusType() == bolusType)
- bolusId = bolusesMessage.getBolus1().getBolusID();
- else if (bolusesMessage.getBolus2().getBolusType() == bolusType)
- bolusId = bolusesMessage.getBolus2().getBolusID();
- else if (bolusesMessage.getBolus3().getBolusType() == bolusType)
- bolusId = bolusesMessage.getBolus3().getBolusID();
- else finish(null);
- cancelBolusMessage.setBolusId(bolusId);
- return cancelBolusMessage;
- } else if (message instanceof CancelBolusMessage) {
- cancelledAt = System.currentTimeMillis();
- ActiveAlertMessage activeAlertMessage = new ActiveAlertMessage();
- activeAlertMessage.setMessagePriority(MessagePriority.HIGHER);
- return activeAlertMessage;
- } else if (message instanceof ActiveAlertMessage) {
- ActiveAlertMessage activeAlertMessage = (ActiveAlertMessage) message;
- if (activeAlertMessage.getAlert() == null) {
- if (System.currentTimeMillis() - cancelledAt >= 10000) finish(bolusId);
- else {
- ActiveAlertMessage activeAlertMessage2 = new ActiveAlertMessage();
- activeAlertMessage2.setMessagePriority(MessagePriority.HIGHER);
- return activeAlertMessage2;
- }
- } else if (!(activeAlertMessage.getAlert() instanceof Warning38BolusCancelled)) finish(bolusId);
- else {
- DismissAlertMessage dismissAlertMessage = new DismissAlertMessage();
- dismissAlertMessage.setAlertID(activeAlertMessage.getAlertID());
- dismissAlertMessage.setMessagePriority(MessagePriority.HIGHER);
- return dismissAlertMessage;
- }
- } else if (message instanceof DismissAlertMessage) finish(bolusId);
- return null;
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelTBRSilentlyTaskRunner.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelTBRSilentlyTaskRunner.java
deleted file mode 100644
index 9a3068aef9..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/CancelTBRSilentlyTaskRunner.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import sugar.free.sightparser.applayer.descriptors.MessagePriority;
-import sugar.free.sightparser.applayer.descriptors.alerts.Warning36TBRCancelled;
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.CancelTBRMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.DismissAlertMessage;
-import sugar.free.sightparser.applayer.messages.status.ActiveAlertMessage;
-import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.TaskRunner;
-
-public class CancelTBRSilentlyTaskRunner extends TaskRunner {
-
- private long cancelledAt;
-
- public CancelTBRSilentlyTaskRunner(SightServiceConnector serviceConnector) {
- super(serviceConnector);
- }
-
- @Override
- protected AppLayerMessage run(AppLayerMessage message) throws Exception {
- if (message == null) return new CurrentTBRMessage();
- else if (message instanceof CurrentTBRMessage) {
- if (((CurrentTBRMessage) message).getPercentage() == 100) finish(false);
- else return new CancelTBRMessage();
- } else if (message instanceof CancelTBRMessage) {
- ActiveAlertMessage activeAlertMessage = new ActiveAlertMessage();
- activeAlertMessage.setMessagePriority(MessagePriority.HIGHER);
- return activeAlertMessage;
- } else if (message instanceof ActiveAlertMessage) {
- ActiveAlertMessage activeAlertMessage = (ActiveAlertMessage) message;
- if (activeAlertMessage.getAlert() == null) {
- if (System.currentTimeMillis() - cancelledAt >= 10000) finish(true);
- else {
- ActiveAlertMessage activeAlertMessage2 = new ActiveAlertMessage();
- activeAlertMessage2.setMessagePriority(MessagePriority.HIGHER);
- return activeAlertMessage2;
- }
- } else if (!(activeAlertMessage.getAlert() instanceof Warning36TBRCancelled)) finish(true);
- else {
- DismissAlertMessage dismissAlertMessage = new DismissAlertMessage();
- dismissAlertMessage.setAlertID(activeAlertMessage.getAlertID());
- dismissAlertMessage.setMessagePriority(MessagePriority.HIGHER);
- return dismissAlertMessage;
- }
- } else if (message instanceof DismissAlertMessage) finish(true);
- return null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java
deleted file mode 100644
index fdc2aff0a6..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/Connector.java
+++ /dev/null
@@ -1,574 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import android.content.Intent;
-import android.os.PowerManager;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Formatter;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventFeatureRunning;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.PumpInsight.events.EventInsightUpdateGui;
-import info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver;
-import info.nightscout.androidaps.plugins.PumpInsight.history.LiveHistory;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
-import info.nightscout.utils.SP;
-import sugar.free.sightparser.handling.ServiceConnectionCallback;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.StatusCallback;
-import sugar.free.sightparser.pipeline.Status;
-
-import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_RESYNC;
-import static sugar.free.sightparser.handling.HistoryBroadcast.ACTION_START_SYNC;
-import static sugar.free.sightparser.handling.SightService.COMPATIBILITY_VERSION;
-
-/**
- * Created by jamorham on 23/01/2018.
- *
- * Connects to SightRemote app service using SightParser library
- *
- * SightRemote and SightParser created by Tebbe Ubben
- *
- * Original proof of concept SightProxy by jamorham
- */
-
-public class Connector {
- private static Logger log = LoggerFactory.getLogger(L.PUMP);
-
- // TODO connection statistics
-
- private static final String TAG = "InsightConnector";
- private static final String COMPANION_APP_PACKAGE = "sugar.free.sightremote";
- private final static long FRESH_MS = 70000;
- private static final Map statistics = new HashMap<>();
- private static volatile Connector instance;
- private static volatile HistoryReceiver historyReceiver;
- private static volatile long stayConnectedTill = -1;
- private static volatile long stayConnectedTime = 0;
- private static volatile boolean disconnect_thread_running = false;
- private volatile SightServiceConnector serviceConnector;
- private volatile Status lastStatus = null;
- private String compatabilityMessage = null;
- private volatile long lastStatusTime = -1;
- private volatile long lastContactTime = -1;
- private boolean companionAppInstalled = false;
- private int serviceReconnects = 0;
- private StatusCallback statusCallback = new StatusCallback() {
- @Override
- public synchronized void onStatusChange(Status status, long statusTime, long waitTime) {
-
- if ((status != lastStatus) || (Helpers.msSince(lastStatusTime) > 2000)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Status change: " + status);
-
- updateStatusStatistics(lastStatus, lastStatusTime);
- lastStatus = status;
- lastStatusTime = Helpers.tsl();
-
- if (status == Status.CONNECTED) {
- lastContactTime = lastStatusTime;
- extendKeepAliveIfActive();
- }
-
- MainApp.bus().post(new EventInsightUpdateGui());
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Same status as before: " + status);
- }
- }
-
- };
- private ServiceConnectionCallback connectionCallback = new ServiceConnectionCallback() {
-
- @Override
- public synchronized void onServiceConnected() {
- if (L.isEnabled(L.PUMP))
- log.debug("On service connected");
- try {
- final String remoteVersion = serviceConnector.getRemoteVersion();
- if (remoteVersion.equals(COMPATIBILITY_VERSION)) {
- serviceConnector.connect();
- } else {
- log.error("PROTOCOL VERSION MISMATCH! local: " + COMPATIBILITY_VERSION + " remote: " + remoteVersion);
- statusCallback.onStatusChange(Status.INCOMPATIBLE, 0, 0);
- compatabilityMessage = MainApp.gs(R.string.insight_incompatible_compantion_app_we_need_version) + " " + getLocalVersion();
- serviceConnector.disconnectFromService();
-
- }
- } catch (NullPointerException e) {
- log.error("ERROR: null pointer when trying to connect to pump");
- }
- statusCallback.onStatusChange(safeGetStatus(), 0, 0);
- }
-
- @Override
- public synchronized void onServiceDisconnected() {
- if (L.isEnabled(L.PUMP))
- log.debug("Disconnected from service");
- if (Helpers.ratelimit("insight-automatic-reconnect", 30)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Scheduling automatic service reconnection");
- Helpers.runOnUiThreadDelayed(new Runnable() {
- @Override
- public void run() {
- init();
- }
- }, 20000);
- }
- }
- };
-
- private Connector() {
- initializeHistoryReceiver();
- MainApp.bus().register(this);
- }
-
- public static Connector get() {
- if (instance == null) {
- init_instance();
- }
- return instance;
- }
-
- private synchronized static void init_instance() {
- if (instance == null) {
- instance = new Connector();
- }
- }
-
- private static boolean isCompanionAppInstalled() {
- return Helpers.checkPackageExists(MainApp.instance(), TAG, COMPANION_APP_PACKAGE);
- }
-
- public static void connectToPump() {
- connectToPump(0);
- }
-
- public synchronized static void connectToPump(long keep_alive) {
- if (L.isEnabled(L.PUMP))
- log.debug("Attempting to connect to pump.");
- if (keep_alive > 0 && Helpers.tsl() + keep_alive > stayConnectedTill) {
- stayConnectedTime = keep_alive;
- stayConnectedTill = Helpers.tsl() + keep_alive;
- if (L.isEnabled(L.PUMP))
- log.debug("Staying connected till: " + Helpers.dateTimeText(stayConnectedTill));
- delayedDisconnectionThread();
- }
- get().getServiceConnector().connect();
- }
-
- public static void disconnectFromPump() {
- if (Helpers.tsl() >= stayConnectedTill) {
- if (L.isEnabled(L.PUMP))
- log.debug("Requesting real pump disconnect");
- get().getServiceConnector().disconnect();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Cannot disconnect as due to keep alive till: " + Helpers.dateTimeText(stayConnectedTill));
- // TODO set a disconnection timer?
- }
- }
-
- static String getLocalVersion() {
- return COMPATIBILITY_VERSION;
- }
-
- private static String statusToString(Status status) {
- switch (status) {
-
- case EXCHANGING_KEYS:
- return MainApp.gs(R.string.connecting).toUpperCase();
- case WAITING_FOR_CODE_CONFIRMATION:
- return MainApp.gs(R.string.insight_waiting_for_code).toUpperCase();
- case CODE_REJECTED:
- return MainApp.gs(R.string.insight_code_rejected).toUpperCase();
- case APP_BINDING:
- return MainApp.gs(R.string.insight_app_binding).toUpperCase();
- case CONNECTING:
- return MainApp.gs(R.string.connecting).toUpperCase();
- case CONNECTED:
- return MainApp.gs(R.string.connected).toUpperCase();
- case DISCONNECTED:
- return MainApp.gs(R.string.disconnected).toUpperCase();
- case NOT_AUTHORIZED:
- return MainApp.gs(R.string.insight_not_authorized).toUpperCase();
- case INCOMPATIBLE:
- return MainApp.gs(R.string.insight_incompatible).toUpperCase();
-
- default:
- return status.toString();
- }
- }
-
- private static synchronized void extendKeepAliveIfActive() {
- if (keepAliveActive()) {
- if (Helpers.ratelimit("extend-insight-keepalive", 10)) {
- stayConnectedTill = Helpers.tsl() + stayConnectedTime;
- if (L.isEnabled(L.PUMP))
- log.debug("Keep-alive extended until: " + Helpers.dateTimeText(stayConnectedTill));
- }
- }
- }
-
- private static boolean keepAliveActive() {
- return Helpers.tsl() <= stayConnectedTill;
- }
-
- public static String getKeepAliveString() {
- if (keepAliveActive()) {
- return MainApp.gs(R.string.insight_keepalive_format_string,
- stayConnectedTime / 1000, Helpers.hourMinuteSecondString(stayConnectedTill));
-
- } else {
- return null;
- }
- }
-
- private static synchronized void delayedDisconnectionThread() {
- if (keepAliveActive()) {
- if (!disconnect_thread_running) {
- disconnect_thread_running = true;
- new Thread(new Runnable() {
- @Override
- public void run() {
- final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-disconnection-timer", 600000);
- try {
- while (disconnect_thread_running && keepAliveActive()) {
- if (Helpers.ratelimit("insight-expiry-notice", 5)) {
- if (L.isEnabled(L.PUMP))
- log.debug("Staying connected thread expires: " + Helpers.dateTimeText(stayConnectedTill));
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- //
- }
- }
-
- if (disconnect_thread_running) {
- if (L.isEnabled(L.PUMP))
- log.debug("Sending the real delayed disconnect");
- get().getServiceConnector().disconnect();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Disconnect thread already terminating");
- }
- } finally {
- Helpers.releaseWakeLock(wl);
- disconnect_thread_running = false;
- }
- }
- }).start();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Disconnect thread already running");
- }
- }
- }
-
- private static long percentage(long t, long total) {
- return (long) (Helpers.roundDouble(((double) t * 100) / total, 0));
- }
-
- public synchronized void shutdown() {
- if (instance != null) {
- if (L.isEnabled(L.PUMP))
- log.debug("Attempting to shut down connector");
- try {
- disconnect_thread_running = false;
- try {
- instance.serviceConnector.setConnectionCallback(null);
- } catch (Exception e) {
- //
- }
- try {
- instance.serviceConnector.removeStatusCallback(statusCallback);
- } catch (Exception e) {
- //
- }
- try {
- instance.serviceConnector.disconnect();
- } catch (Exception e) {
- log.error("Exception disconnecting: " + e);
- }
- try {
- instance.serviceConnector.disconnectFromService();
- } catch (Exception e) {
- log.error("Excpetion disconnecting service: " + e);
- }
- instance.serviceConnector = null;
- instance = null;
- } catch (Exception e) {
- log.error("Exception shutting down: " + e);
- }
- }
- }
-
- @SuppressWarnings("AccessStaticViaInstance")
- private synchronized void initializeHistoryReceiver() {
- if (historyReceiver == null) {
- historyReceiver = new HistoryReceiver();
- }
- historyReceiver.registerHistoryReceiver();
- }
-
- public synchronized void init() {
- if (L.isEnabled(L.PUMP))
- log.debug("Connector::init()");
- if (serviceConnector == null) {
- companionAppInstalled = isCompanionAppInstalled();
- if (companionAppInstalled) {
- serviceConnector = new SightServiceConnector(MainApp.instance());
- serviceConnector.removeStatusCallback(statusCallback);
- serviceConnector.addStatusCallback(statusCallback);
- serviceConnector.setConnectionCallback(connectionCallback);
- serviceConnector.connectToService();
- if (L.isEnabled(L.PUMP))
- log.debug("Trying to connect");
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Not trying init due to missing companion app");
- }
- } else {
- if (!serviceConnector.isConnectedToService()) {
- if (serviceReconnects > 0) {
- serviceConnector = null;
- init();
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Trying to reconnect to service (" + serviceReconnects + ")");
- serviceConnector.connectToService();
- serviceReconnects++;
- }
- } else {
- serviceReconnects = 0; // everything ok
- }
- }
- }
-
- public SightServiceConnector getServiceConnector() {
- init();
- return serviceConnector;
- }
-
- public String getCurrent() {
- init();
- return safeGetStatus().toString();
- }
-
- public Status safeGetStatus() {
- try {
- if (isConnected()) return serviceConnector.getStatus();
- return Status.DISCONNECTED;
- } catch (IllegalArgumentException e) {
- return Status.INCOMPATIBLE;
- }
- }
-
- public Status getLastStatus() {
- return lastStatus;
- }
-
- public boolean isConnected() {
- return serviceConnector != null && serviceConnector.isConnectedToService();
- }
-
- public boolean isPumpConnected() {
- return isConnected() && getLastStatus() == Status.CONNECTED;
- }
-
- public boolean isPumpConnecting() {
- return isConnected() && getLastStatus() == Status.CONNECTING;
- }
-
- public long getLastContactTime() {
- return lastContactTime;
- }
-
- public String getLastStatusMessage() {
-
- if (!companionAppInstalled) {
- return MainApp.gs(R.string.insight_companion_app_not_installed);
- }
-
- if (!isConnected()) {
- if (L.isEnabled(L.PUMP))
- log.debug("Not connected to companion");
- if (Helpers.ratelimit("insight-app-not-connected", 5)) {
- init();
- }
-
- if ((lastStatus == null) || (lastStatus != Status.INCOMPATIBLE)) {
- if (compatabilityMessage != null) {
- // if disconnected but previous state was incompatible
- return compatabilityMessage;
- } else {
- return MainApp.gs(R.string.insight_not_connected_to_companion_app);
- }
- }
- }
-
- if (lastStatus == null) {
- return MainApp.gs(R.string.insight_unknown);
- }
-
- switch (lastStatus) {
- case CONNECTED:
- if (Helpers.msSince(lastStatusTime) > (60 * 10 * 1000)) {
- tryToGetPumpStatusAgain();
- }
- break;
- case INCOMPATIBLE:
- return statusToString(lastStatus) + " " + MainApp.gs(R.string.insight_needs) + " " + getLocalVersion();
- }
- return statusToString(lastStatus);
- }
-
- public String getNiceLastStatusTime() {
- if (lastStatusTime < 1) {
- return MainApp.gs(R.string.insight_startup_uppercase);
- } else {
- return Helpers.niceTimeScalar(Helpers.msSince(lastStatusTime)) + " " + MainApp.gs(R.string.ago);
- }
- }
-
- public boolean uiFresh() {
- // todo check other changes
-
- if (Helpers.msSince(lastStatusTime) < FRESH_MS) {
- return true;
- }
- if (Helpers.msSince(LiveHistory.getStatusTime()) < FRESH_MS) {
- return true;
- }
- return false;
- }
-
- @SuppressWarnings("AccessStaticViaInstance")
- public void tryToGetPumpStatusAgain() {
- if (Helpers.ratelimit("insight-retry-status-request", 5)) {
- try {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Insight. Status missing", null);
- } catch (NullPointerException e) {
- //
- }
- }
- }
-
- public void requestHistorySync() {
- requestHistorySync(0);
- }
-
- public void requestHistoryReSync() {
- requestHistoryReSync(0);
- }
-
- public void requestHistorySync(long delay) {
- if (Helpers.ratelimit("insight-history-sync-request", 10)) {
- final Intent intent = new Intent(ACTION_START_SYNC);
- sendBroadcastToCompanion(intent, delay);
- }
- }
-
- public void requestHistoryReSync(long delay) {
- if (Helpers.ratelimit("insight-history-resync-request", 300)) {
- final Intent intent = new Intent(ACTION_START_RESYNC);
- sendBroadcastToCompanion(intent, delay);
- }
- }
-
- private void sendBroadcastToCompanion(final Intent intent, final long delay) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- final PowerManager.WakeLock wl = Helpers.getWakeLock("insight-companion-delay", 60000);
- intent.setPackage(COMPANION_APP_PACKAGE);
- intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
- try {
- if (delay > 0) {
-
- Thread.sleep(delay);
- }
- } catch (InterruptedException e) {
- //
- } finally {
- Helpers.releaseWakeLock(wl);
- }
- MainApp.instance().sendBroadcast(intent);
- }
- }).start();
- }
-
- public boolean lastStatusRecent() {
- return true; // TODO evaluate whether current
- }
-
- private void updateStatusStatistics(Status last, long since) {
- if ((last != null) && (since > 0)) {
- Long total = statistics.get(last);
- if (total == null) total = 0L;
- statistics.put(last, total + Helpers.msSince(since));
- if (L.isEnabled(L.PUMP))
- log.debug("Updated statistics for: " + last + " total: " + Helpers.niceTimeScalar(statistics.get(last)));
- // TODO persist data
- }
- }
-
- public List getStatusStatistics() {
- final List l = new ArrayList<>();
- long total = 0;
- for (Map.Entry entry : statistics.entrySet()) {
- total += getEntryTime(entry);
- }
- for (Map.Entry entry : statistics.entrySet()) {
- if ((long) entry.getValue() > 1000) {
- l.add(new StatusItem(MainApp.gs(R.string.statistics) + " " + Helpers.capitalize(entry.getKey().toString()),
- new Formatter().format("%4s %12s",
- percentage(getEntryTime(entry), total) + "%",
- Helpers.niceTimeScalar(getEntryTime(entry))).toString()));
- }
- }
- return l;
- }
-
- private long getEntryTime(Map.Entry entry) {
- return (long) entry.getValue() + (entry.getKey().equals(lastStatus) ? Helpers.msSince(lastStatusTime) : 0);
- }
-
- @Subscribe
- public void onStatusEvent(final EventFeatureRunning ev) {
- new Thread(new Runnable() {
- @Override
- public void run() {
- if (isConnected()) {
- if (SP.getBoolean("insight_preemptive_connect", true)) {
- switch (ev.getFeature()) {
- case WIZARD:
- if (L.isEnabled(L.PUMP))
- log.debug("Wizard feature detected, preconnecting to pump");
- connectToPump(120 * 1000);
- break;
- case MAIN:
- if (L.isEnabled(L.PUMP))
- log.debug("Main feature detected, preconnecting to pump");
- connectToPump(30 * 1000);
- break;
- }
- }
- }
- }
- }).start();
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/SetTBRTaskRunner.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/SetTBRTaskRunner.java
deleted file mode 100644
index f18bb0d487..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/SetTBRTaskRunner.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.ChangeTBRMessage;
-import sugar.free.sightparser.applayer.messages.remote_control.SetTBRMessage;
-import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.TaskRunner;
-
-// from Tebbe - note this uses 1 minute duration to silently cancel existing TBR
-
-public class SetTBRTaskRunner extends TaskRunner {
-
- private int amount;
- private int duration;
-
- public SetTBRTaskRunner(SightServiceConnector serviceConnector, int amount, int duration) {
- super(serviceConnector);
- this.amount = amount;
- this.duration = duration;
- }
-
- @Override
- protected AppLayerMessage run(AppLayerMessage message) throws Exception {
- if (message == null) return new CurrentTBRMessage();
- else if (message instanceof CurrentTBRMessage) {
- if (((CurrentTBRMessage) message).getPercentage() == 100) {
- SetTBRMessage setTBRMessage = new SetTBRMessage();
- setTBRMessage.setDuration(duration);
- setTBRMessage.setAmount(amount);
- return setTBRMessage;
- } else {
- ChangeTBRMessage changeTBRMessage = new ChangeTBRMessage();
- changeTBRMessage.setDuration(duration);
- changeTBRMessage.setAmount(amount);
- return changeTBRMessage;
- }
- } else if (message instanceof SetTBRMessage) finish(amount);
- return null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/StatusTaskRunner.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/StatusTaskRunner.java
deleted file mode 100644
index 1df56be468..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/StatusTaskRunner.java
+++ /dev/null
@@ -1,140 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import java.util.List;
-
-import sugar.free.sightparser.applayer.descriptors.ActiveBolus;
-import sugar.free.sightparser.applayer.descriptors.PumpStatus;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ActiveProfileBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile1Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile2Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile3Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile4Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile5Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ConfigurationBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.FactoryMinBRAmountBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.FactoryMinBolusAmountBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.MaxBRAmountBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.MaxBolusAmountBlock;
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.configuration.ReadConfigurationBlockMessage;
-import sugar.free.sightparser.applayer.messages.status.ActiveBolusesMessage;
-import sugar.free.sightparser.applayer.messages.status.BatteryAmountMessage;
-import sugar.free.sightparser.applayer.messages.status.CartridgeAmountMessage;
-import sugar.free.sightparser.applayer.messages.status.CurrentBasalMessage;
-import sugar.free.sightparser.applayer.messages.status.CurrentTBRMessage;
-import sugar.free.sightparser.applayer.messages.status.PumpStatusMessage;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.TaskRunner;
-
-/**
- * Created by Tebbe Ubben on 12.03.2018.
- */
-
-public class StatusTaskRunner extends TaskRunner {
-
- private Result result = new Result();
-
- public StatusTaskRunner(SightServiceConnector serviceConnector) {
- super(serviceConnector);
- }
-
- @Override
- protected AppLayerMessage run(AppLayerMessage message) throws Exception {
- if (message == null) return new PumpStatusMessage();
- else if (message instanceof PumpStatusMessage) {
- result.pumpStatus = ((PumpStatusMessage) message).getPumpStatus();
- if (result.pumpStatus == PumpStatus.STOPPED) return new BatteryAmountMessage();
- else return new CurrentTBRMessage();
- } else if (message instanceof CurrentTBRMessage) {
- CurrentTBRMessage currentTBRMessage = (CurrentTBRMessage) message;
- result.tbrAmount = currentTBRMessage.getPercentage();
- result.tbrInitialDuration = currentTBRMessage.getInitialTime();
- result.tbrLeftoverDuration = currentTBRMessage.getLeftoverTime();
- return new ActiveBolusesMessage();
- } else if (message instanceof ActiveBolusesMessage) {
- ActiveBolusesMessage activeBolusesMessage = (ActiveBolusesMessage) message;
- result.activeBolus1 = activeBolusesMessage.getBolus1();
- result.activeBolus2 = activeBolusesMessage.getBolus2();
- result.activeBolus3 = activeBolusesMessage.getBolus3();
- return new CurrentBasalMessage();
- } else if (message instanceof CurrentBasalMessage) {
- result.baseBasalRate = ((CurrentBasalMessage) message).getCurrentBasalAmount();
- return new BatteryAmountMessage();
- } else if (message instanceof BatteryAmountMessage) {
- result.battery = ((BatteryAmountMessage) message).getBatteryAmount();
- return new CartridgeAmountMessage();
- } else if (message instanceof CartridgeAmountMessage) {
- result.cartridge = ((CartridgeAmountMessage) message).getCartridgeAmount();
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(ActiveProfileBlock.ID);
- return readMessage;
- } else if (message instanceof ReadConfigurationBlockMessage) {
- ConfigurationBlock configurationBlock = ((ReadConfigurationBlockMessage) message).getConfigurationBlock();
- if (configurationBlock instanceof ActiveProfileBlock) {
- ActiveProfileBlock activeProfileBlock = (ActiveProfileBlock) configurationBlock;
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- switch (activeProfileBlock.getActiveProfile()) {
- case BR_PROFILE_1:
- readMessage.setConfigurationBlockID(BRProfile1Block.ID);
- break;
- case BR_PROFILE_2:
- readMessage.setConfigurationBlockID(BRProfile2Block.ID);
- break;
- case BR_PROFILE_3:
- readMessage.setConfigurationBlockID(BRProfile3Block.ID);
- break;
- case BR_PROFILE_4:
- readMessage.setConfigurationBlockID(BRProfile4Block.ID);
- break;
- case BR_PROFILE_5:
- readMessage.setConfigurationBlockID(BRProfile5Block.ID);
- break;
- }
- return readMessage;
- } else if (configurationBlock instanceof BRProfileBlock) {
- result.basalProfile = ((BRProfileBlock) configurationBlock).getProfileBlocks();
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(MaxBolusAmountBlock.ID);
- return readMessage;
- } else if (configurationBlock instanceof MaxBolusAmountBlock) {
- result.maximumBolusAmount = ((MaxBolusAmountBlock) configurationBlock).getMaximumAmount();
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(MaxBRAmountBlock.ID);
- return readMessage;
- } else if (configurationBlock instanceof MaxBRAmountBlock) {
- result.maximumBasalAmount = ((MaxBRAmountBlock) configurationBlock).getMaximumAmount();
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(FactoryMinBRAmountBlock.ID);
- return readMessage;
- } else if (configurationBlock instanceof FactoryMinBRAmountBlock) {
- result.minimumBasalAmount = ((FactoryMinBRAmountBlock) configurationBlock).getMinimumAmount();
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(FactoryMinBolusAmountBlock.ID);
- return readMessage;
- } else if (configurationBlock instanceof FactoryMinBolusAmountBlock) {
- result.minimumBolusAmount = ((FactoryMinBolusAmountBlock) configurationBlock).getMinimumAmount();
- finish(result);
- }
- }
- return null;
- }
-
- public static class Result {
- public PumpStatus pumpStatus;
- public double baseBasalRate;
- public int battery;
- public double cartridge ;
- public int tbrAmount = 100;
- public int tbrInitialDuration = 0;
- public int tbrLeftoverDuration = 0;
- public ActiveBolus activeBolus1;
- public ActiveBolus activeBolus2;
- public ActiveBolus activeBolus3;
- public List basalProfile;
- public double maximumBolusAmount;
- public double maximumBasalAmount;
- public double minimumBolusAmount;
- public double minimumBasalAmount;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/WriteBasalProfileTaskRunner.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/WriteBasalProfileTaskRunner.java
deleted file mode 100644
index 7012d200e7..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/connector/WriteBasalProfileTaskRunner.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.connector;
-
-import java.util.List;
-
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ActiveProfileBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile1Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile2Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile3Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile4Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfile5Block;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.BRProfileBlock;
-import sugar.free.sightparser.applayer.descriptors.configuration_blocks.ConfigurationBlock;
-import sugar.free.sightparser.applayer.messages.AppLayerMessage;
-import sugar.free.sightparser.applayer.messages.configuration.CloseWriteSessionMessage;
-import sugar.free.sightparser.applayer.messages.configuration.OpenWriteSessionMessage;
-import sugar.free.sightparser.applayer.messages.configuration.ReadConfigurationBlockMessage;
-import sugar.free.sightparser.applayer.messages.configuration.WriteConfigurationBlockMessage;
-import sugar.free.sightparser.handling.SightServiceConnector;
-import sugar.free.sightparser.handling.TaskRunner;
-
-/**
- * Created by Tebbe Ubben on 10.03.2018.
- */
-
-public class WriteBasalProfileTaskRunner extends TaskRunner {
-
- private List profileBlocks;
- private BRProfileBlock profileBlock;
-
- public WriteBasalProfileTaskRunner(SightServiceConnector serviceConnector, List profileBlocks) {
- super(serviceConnector);
- this.profileBlocks = profileBlocks;
- }
-
- @Override
- protected AppLayerMessage run(AppLayerMessage message) throws Exception {
- if (message == null) {
- ReadConfigurationBlockMessage readMessage = new ReadConfigurationBlockMessage();
- readMessage.setConfigurationBlockID(ActiveProfileBlock.ID);
- return readMessage;
- } else if (message instanceof ReadConfigurationBlockMessage) {
- ConfigurationBlock configurationBlock = ((ReadConfigurationBlockMessage) message).getConfigurationBlock();
- ActiveProfileBlock activeProfileBlock = (ActiveProfileBlock) configurationBlock;
- switch (activeProfileBlock.getActiveProfile()) {
- case BR_PROFILE_1:
- profileBlock = new BRProfile1Block();
- break;
- case BR_PROFILE_2:
- profileBlock = new BRProfile2Block();
- break;
- case BR_PROFILE_3:
- profileBlock = new BRProfile3Block();
- break;
- case BR_PROFILE_4:
- profileBlock = new BRProfile4Block();
- break;
- case BR_PROFILE_5:
- profileBlock = new BRProfile5Block();
- break;
- }
- profileBlock.setProfileBlocks(profileBlocks);
- return new OpenWriteSessionMessage();
- } else if (message instanceof OpenWriteSessionMessage) {
- WriteConfigurationBlockMessage writeMessage = new WriteConfigurationBlockMessage();
- writeMessage.setConfigurationBlock(profileBlock);
- return writeMessage;
- } else if (message instanceof WriteConfigurationBlockMessage) {
- return new CloseWriteSessionMessage();
- } else if (message instanceof CloseWriteSessionMessage) finish(null);
- return null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightCallback.java
deleted file mode 100644
index 753ac7f0e6..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightCallback.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.events;
-
-import java.util.UUID;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by jamorham on 23/01/2018.
- */
-public class EventInsightCallback extends Event {
-
- public UUID request_uuid;
- public boolean success = false;
- public String message = null;
- public Object response_object = null;
-
- public EventInsightCallback() {
- request_uuid = UUID.randomUUID();
- }
-
- @Override
- public String toString() {
- return "Event: " + request_uuid + " success: " + success + " msg: " + message + " Object: " + response_object;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightUpdateGui.java
deleted file mode 100644
index 3741c607c4..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/events/EventInsightUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by jamorham on 23/01/2018.
- */
-public class EventInsightUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java
deleted file mode 100644
index 49836e9f3b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryIntentAdapter.java
+++ /dev/null
@@ -1,243 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.history;
-
-import android.content.Intent;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.CareportalEvent;
-import info.nightscout.androidaps.db.TDD;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.utils.SP;
-
-import org.json.JSONException;
-import org.json.JSONObject;
-
-import sugar.free.sightparser.handling.HistoryBroadcast;
-
-import java.util.Date;
-
-import static info.nightscout.androidaps.plugins.PumpInsight.history.PumpIdCache.updatePumpSerialNumber;
-
-/**
- * Created by jamorham on 27/01/2018.
- *
- * Parse inbound logbook intents
- */
-
-class HistoryIntentAdapter {
- private Logger log = LoggerFactory.getLogger(L.PUMP);
-
- private HistoryLogAdapter logAdapter = new HistoryLogAdapter();
-
- private static long getDateExtra(Intent intent, String name) {
- return ((Date) intent.getSerializableExtra(name)).getTime();
- }
-
- static long getRecordUniqueID(long pump_serial_number, long pump_record_id) {
- updatePumpSerialNumber(pump_serial_number);
- return (pump_serial_number * 10000000) + pump_record_id;
- }
-
- void processTBRIntent(Intent intent) {
-
- final int pump_tbr_duration = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1);
- final int pump_tbr_percent = intent.getIntExtra(HistoryBroadcast.EXTRA_TBR_AMOUNT, -1);
- long pump_record_id = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
- if (pump_record_id == -1) {
- pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
- }
- final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
- final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
-
- if ((pump_tbr_duration == -1) || (pump_tbr_percent == -1) || (pump_record_id == -1)) {
- log.error("Invalid TBR record!!!");
- return;
- }
-
- final long record_unique_id = getRecordUniqueID(pump_serial_number, pump_record_id);
-
- if (L.isEnabled(L.PUMP))
- log.debug("Creating TBR record: " + pump_tbr_percent + "% " + pump_tbr_duration + "m" + " id:" + record_unique_id);
- logAdapter.createTBRrecord(start_time, pump_tbr_percent, pump_tbr_duration, record_unique_id);
- }
-
- void processDeliveredBolusIntent(Intent intent) {
-
- final String bolus_type = intent.getStringExtra(HistoryBroadcast.EXTRA_BOLUS_TYPE);
- final int bolus_id = intent.getIntExtra(HistoryBroadcast.EXTRA_BOLUS_ID, -1);
- long pump_record_id = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
- if (pump_record_id == -1) {
- pump_record_id = intent.getIntExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
- }
- final long pump_serial_number = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
- final long event_time = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- final long start_time = getDateExtra(intent, HistoryBroadcast.EXTRA_START_TIME);
- final double immediate_amount = intent.getDoubleExtra(HistoryBroadcast.EXTRA_IMMEDIATE_AMOUNT, -1);
- final double extended_insulin = intent.getDoubleExtra(HistoryBroadcast.EXTRA_EXTENDED_AMOUNT, -1);
- final int extended_minutes = intent.getIntExtra(HistoryBroadcast.EXTRA_DURATION, -1);
-
- final long record_unique_id = getRecordUniqueID(pump_serial_number, bolus_id > -1 ? bolus_id : pump_record_id);
-
- switch (bolus_type) {
- case "STANDARD":
- if (immediate_amount == -1) {
- log.error("ERROR Standard bolus fails sanity check");
- return;
- }
- LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U ", event_time);
- logAdapter.createStandardBolusRecord(start_time, immediate_amount, record_unique_id);
- break;
-
- case "EXTENDED":
- if ((extended_insulin == -1) || (extended_minutes == -1)) {
- log.error("ERROR: Extended bolus fails sanity check");
- return;
- }
- LiveHistory.setStatus(bolus_type + " BOLUS\n" + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
- logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
- break;
-
- case "MULTIWAVE":
- if ((immediate_amount == -1) || (extended_insulin == -1) || (extended_minutes == -1)) {
- log.error("ERROR: Multiwave bolus fails sanity check");
- return;
- }
- LiveHistory.setStatus(bolus_type + " BOLUS\n" + immediate_amount + "U + " + extended_insulin + "U over " + extended_minutes + " min, ", event_time);
- logAdapter.createStandardBolusRecord(start_time, immediate_amount, pump_serial_number + pump_record_id);
- logAdapter.createExtendedBolusRecord(start_time, extended_insulin, extended_minutes, record_unique_id);
- break;
- default:
- log.error("ERROR, UNKNWON BOLUS TYPE: " + bolus_type);
- }
- }
-
- void processDailyTotalIntent(Intent intent) {
- long date = getDateExtra(intent, HistoryBroadcast.EXTRA_TOTAL_DATE);
- double basal = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BASAL_TOTAL, 0D);
- double bolus = intent.getDoubleExtra(HistoryBroadcast.EXTRA_BOLUS_TOTAL, 0D);
- TDD tdd = new TDD(date, bolus, basal, bolus + basal);
- MainApp.getDbHelper().createOrUpdateTDD(tdd);
- }
-
- void processCannulaFilledIntent(Intent intent) {
- long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- uploadCareportalEvent(date, CareportalEvent.SITECHANGE);
- }
-
- void processCartridgeInsertedIntent(Intent intent) {
- long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- uploadCareportalEvent(date, CareportalEvent.INSULINCHANGE);
- }
-
- void processBatteryInsertedIntent(Intent intent) {
- long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- uploadCareportalEvent(date, CareportalEvent.PUMPBATTERYCHANGE);
- }
-
- private void uploadCareportalEvent(long date, String event) {
- if (SP.getBoolean("insight_automatic_careportal_events", false)) {
- if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
- return;
- try {
- JSONObject data = new JSONObject();
- String enteredBy = SP.getString("careportal_enteredby", "");
- if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
- data.put("created_at", DateUtil.toISOString(date));
- data.put("eventType", event);
- NSUpload.uploadCareportalEntryToNS(data);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- }
-
- void processOccurenceOfAlertIntent(Intent intent) {
- if (SP.getBoolean("insight_automatic_careportal_events", false)) {
- long date = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- String alertType = intent.getStringExtra(HistoryBroadcast.EXTRA_ALERT_TYPE);
- int alertText = getAlertText(alertType);
- if (alertText == 0) return;
- if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
- return;
- logNote(date, MainApp.gs(alertText));
- }
- }
-
- void processPumpStatusChangedIntent(Intent intent) {
- long newStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_EVENT_TIME);
- if (SP.getBoolean("insight_automatic_careportal_events", false)) {
- String newStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_NEW_STATUS);
- switch (newStatus) {
- case "STARTED":
- logNote(newStatusTime, MainApp.gs(R.string.pump_started));
- break;
- case "STOPPED":
- logNote(newStatusTime, MainApp.gs(R.string.pump_stopped));
- break;
- case "PAUSED":
- logNote(newStatusTime, MainApp.gs(R.string.pump_paused));
- break;
- }
- }
- if (intent.hasExtra(HistoryBroadcast.EXTRA_OLD_STATUS_TIME)) {
- String oldStatus = intent.getStringExtra(HistoryBroadcast.EXTRA_OLD_STATUS);
- if (oldStatus.equals("STOPPED")) {
- long oldStatusTime = getDateExtra(intent, HistoryBroadcast.EXTRA_OLD_STATUS_TIME);
- int duration = (int) ((newStatusTime - oldStatusTime) / 60000);
-
- long serialNumber = Long.parseLong(intent.getStringExtra(HistoryBroadcast.EXTRA_PUMP_SERIAL_NUMBER));
- long recordId = intent.getLongExtra(HistoryBroadcast.EXTRA_EVENT_NUMBER, -1);
- long uniqueRecordId = getRecordUniqueID(serialNumber, recordId);
-
- logAdapter.createTBRrecord(oldStatusTime, 0, duration, uniqueRecordId);
- }
- }
- }
-
- private void logNote(long date, String note) {
- try {
- if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
- return;
- JSONObject data = new JSONObject();
- String enteredBy = SP.getString("careportal_enteredby", "");
- if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
- data.put("created_at", DateUtil.toISOString(date));
- data.put("eventType", CareportalEvent.NOTE);
- data.put("notes", note);
- NSUpload.uploadCareportalEntryToNS(data);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
-
- private int getAlertText(String type) {
- if (type.equals("Error6MechanicalError")) return R.string.alert_e6;
- if (type.equals("Error7ElectronicError")) return R.string.alert_e7;
- if (type.equals("Error10RewindError")) return R.string.alert_e10;
- if (type.equals("Error13LanguageError")) return R.string.alert_e13;
- if (type.equals("Maintenance20CartridgeNotInserted")) return R.string.alert_m20;
- if (type.equals("Maintenance21CartridgeEmpty")) return R.string.alert_m21;
- if (type.equals("Maintenance22BatteryEmpty")) return R.string.alert_m22;
- if (type.equals("Maintenance23AutomaticOff")) return R.string.alert_m23;
- if (type.equals("Maintenance24Occlusion")) return R.string.alert_m24;
- if (type.equals("Maintenance25LoantimeOver")) return R.string.alert_m25;
- if (type.equals("Maintenance26CartridgeChangeNotCompleted")) return R.string.alert_m26;
- if (type.equals("Maintenance27DataDownloadFailed")) return R.string.alert_m27;
- if (type.equals("Maintenance28PauseModeTimeout")) return R.string.alert_m28;
- if (type.equals("Maintenance29BatteryTypeNotSet")) return R.string.alert_m29;
- if (type.equals("Maintenance30CartridgeTypeNotSet")) return R.string.alert_m30;
- if (type.equals("Warning31CartridgeLow")) return R.string.alert_w31;
- if (type.equals("Warning32BatteryLow")) return R.string.alert_w32;
- if (type.equals("Warning33InvalidDateTime")) return R.string.alert_w33;
- if (type.equals("Warning34EndOfWarranty")) return R.string.alert_w34;
- if (type.equals("Warning36TBRCancelled")) return 0;
- if (type.equals("Warning38BolusCancelled")) return 0;
- if (type.equals("Warning39LoantimeWarning")) return R.string.alert_w39;
- return 0;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryLogAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryLogAdapter.java
deleted file mode 100644
index fc44f25418..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryLogAdapter.java
+++ /dev/null
@@ -1,136 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.history;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.NSClientInternal.UploadQueue;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.T;
-
-/**
- * Created by jamorham on 27/01/2018.
- *
- * Write to the History Log
- */
-
-class HistoryLogAdapter {
- private Logger log = LoggerFactory.getLogger(L.PUMP);
-
- private static final long MAX_TIME_DIFFERENCE = T.secs(61).msecs();
-
- void createTBRrecord(long eventDate, int percent, int duration, long record_id) {
-
- TemporaryBasal temporaryBasal = new TemporaryBasal().date(eventDate);
-
- final TemporaryBasal temporaryBasalFromHistory = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(eventDate);
-
- if (temporaryBasalFromHistory == null) {
- if (L.isEnabled(L.PUMP))
- log.debug("Create new TBR: " + eventDate + " " + percent + " " + duration);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Loaded existing TBR record: " + temporaryBasalFromHistory.toString());
- if (Math.abs(eventDate - temporaryBasalFromHistory.date) < MAX_TIME_DIFFERENCE) {
- if (temporaryBasalFromHistory.source != Source.PUMP) {
- if (temporaryBasalFromHistory.percentRate == percent) {
- if (L.isEnabled(L.PUMP))
- log.debug("Things seem to match: %" + percent);
- temporaryBasal = temporaryBasalFromHistory;
- String _id = temporaryBasal._id;
- if (NSUpload.isIdValid(_id)) {
- NSUpload.removeCareportalEntryFromNS(_id);
- } else {
- UploadQueue.removeID("dbAdd", _id);
- }
- MainApp.getDbHelper().delete(temporaryBasalFromHistory);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("This record has different percent rates: " + temporaryBasalFromHistory.percentRate + " vs us: " + percent);
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("This record is already a pump record!");
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Time difference too big! : " + (eventDate - temporaryBasalFromHistory.date));
- }
- }
-
- temporaryBasal.source(Source.PUMP)
- .pumpId(record_id)
- .percent(percent)
- .duration(duration);
-
- TreatmentsPlugin.getPlugin().addToHistoryTempBasal(temporaryBasal);
- }
-
- void createExtendedBolusRecord(long eventDate, double insulin, int durationInMinutes, long record_id) {
-
- final ExtendedBolus extendedBolusFromHistory = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(eventDate);
-
- if (extendedBolusFromHistory == null) {
- if (L.isEnabled(L.PUMP))
- log.debug("Create new EB: " + eventDate + " " + insulin + " " + durationInMinutes);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Loaded existing EB record: " + extendedBolusFromHistory.log());
- if (Math.abs(eventDate - extendedBolusFromHistory.date) < MAX_TIME_DIFFERENCE) {
- if (extendedBolusFromHistory.source != Source.PUMP) {
- if (L.isEnabled(L.PUMP))
- log.debug("Date seem to match: " + DateUtil.dateAndTimeFullString(eventDate));
- String _id = extendedBolusFromHistory._id;
- if (NSUpload.isIdValid(_id)) {
- NSUpload.removeCareportalEntryFromNS(_id);
- } else {
- UploadQueue.removeID("dbAdd", _id);
- }
- MainApp.getDbHelper().delete(extendedBolusFromHistory);
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("This record is already a pump record!");
- }
- } else {
- if (L.isEnabled(L.PUMP))
- log.debug("Time difference too big! : " + (eventDate - extendedBolusFromHistory.date));
- }
- }
-
- // TODO trap items below minimum period
-
- // TODO (mike) find and remove ending record with Source.USER
-
- ExtendedBolus extendedBolus = new ExtendedBolus()
- .date(eventDate)
- .insulin(insulin)
- .durationInMinutes(durationInMinutes)
- .source(Source.PUMP)
- .pumpId(record_id);
-
- if (ProfileFunctions.getInstance().getProfile(extendedBolus.date) != null) // actual basal rate is needed for absolute rate calculation
- TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
- }
-
- void createStandardBolusRecord(long eventDate, double insulin, long record_id) {
-
- //DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.findDetailedBolusInfo(eventDate.getTime());
-
- // TODO do we need to do the same delete + insert that we are doing for temporary basals here too?
-
- final DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
- detailedBolusInfo.date = eventDate;
- detailedBolusInfo.source = Source.PUMP;
- detailedBolusInfo.pumpId = record_id;
- detailedBolusInfo.insulin = insulin;
- TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryReceiver.java
deleted file mode 100644
index a66378ba54..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/HistoryReceiver.java
+++ /dev/null
@@ -1,134 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.history;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-
-import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.BUSY;
-import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.SYNCED;
-import static info.nightscout.androidaps.plugins.PumpInsight.history.HistoryReceiver.Status.SYNCING;
-import static sugar.free.sightparser.handling.HistoryBroadcast.*;
-
-/**
- * Created by jamorham on 27/01/2018.
- */
-
-public class HistoryReceiver {
-
- private static BroadcastReceiver historyReceiver;
- private volatile static Status status = Status.IDLE;
- private volatile HistoryIntentAdapter intentAdapter;
-
- public HistoryReceiver() {
- initializeHistoryReceiver();
- }
-
- public static synchronized void registerHistoryReceiver() {
- try {
- MainApp.instance().unregisterReceiver(historyReceiver);
- } catch (Exception e) {
- //
- }
-
- final IntentFilter filter = new IntentFilter();
- filter.addAction(ACTION_PUMP_STATUS_CHANGED);
- filter.addAction(ACTION_BOLUS_PROGRAMMED);
- filter.addAction(ACTION_BOLUS_DELIVERED);
- filter.addAction(ACTION_END_OF_TBR);
- filter.addAction(ACTION_DAILY_TOTAL);
- filter.addAction(ACTION_SYNC_STARTED);
- filter.addAction(ACTION_STILL_SYNCING);
- filter.addAction(ACTION_SYNC_FINISHED);
- filter.addAction(ACTION_CANNULA_FILLED);
- filter.addAction(ACTION_CARTRIDGE_INSERTED);
- filter.addAction(ACTION_BATTERY_INSERTED);
- filter.addAction(ACTION_OCCURENCE_OF_ALERT);
- filter.addAction(ACTION_PUMP_STATUS_CHANGED);
-
- MainApp.instance().registerReceiver(historyReceiver, filter);
- }
-
- // History
-
- public static String getStatusString() {
- return status.toString();
- }
-
- private synchronized void initializeHistoryReceiver() {
- historyReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, final Intent intent) {
-
- final String action = intent.getAction();
- if (action == null) return;
-
- if (intentAdapter == null) {
- synchronized (this) {
- if (intentAdapter == null) {
- intentAdapter = new HistoryIntentAdapter();
- }
- }
- }
-
- switch (action) {
- case ACTION_SYNC_STARTED:
- status = SYNCING;
- break;
- case ACTION_STILL_SYNCING:
- status = BUSY;
- break;
- case ACTION_SYNC_FINISHED:
- status = SYNCED;
- break;
- case ACTION_BOLUS_DELIVERED:
- intentAdapter.processDeliveredBolusIntent(intent);
- break;
- case ACTION_END_OF_TBR:
- intentAdapter.processTBRIntent(intent);
- break;
- case ACTION_DAILY_TOTAL:
- intentAdapter.processDailyTotalIntent(intent);
- break;
- case ACTION_CANNULA_FILLED:
- intentAdapter.processCannulaFilledIntent(intent);
- break;
- case ACTION_CARTRIDGE_INSERTED:
- intentAdapter.processCartridgeInsertedIntent(intent);
- break;
- case ACTION_BATTERY_INSERTED:
- intentAdapter.processBatteryInsertedIntent(intent);
- break;
- case ACTION_OCCURENCE_OF_ALERT:
- intentAdapter.processOccurenceOfAlertIntent(intent);
- break;
- case ACTION_PUMP_STATUS_CHANGED:
- intentAdapter.processPumpStatusChangedIntent(intent);
- break;
- }
- }
- };
- }
-
- enum Status {
- IDLE(R.string.insight_history_idle),
- SYNCING(R.string.insight_history_syncing),
- BUSY(R.string.insight_history_busy),
- SYNCED(R.string.insight_history_synced);
-
- private final int string_id;
-
- Status(int string_id) {
- this.string_id = string_id;
- }
-
- @Override
- public String toString() {
- return MainApp.gs(string_id);
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/LiveHistory.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/LiveHistory.java
deleted file mode 100644
index 46af6bda98..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/LiveHistory.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.history;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.Helpers;
-
-/**
- * Created by jamorham on 27/01/2018.
- *
- * In memory status storage class
- */
-
-public class LiveHistory {
-
- private static String status = "";
- private static long status_time = -1;
-
- public static String getStatus() {
- if (status.equals("")) return status;
- return status + " " + Helpers.niceTimeScalar(Helpers.msSince(status_time)) + " " + MainApp.gs(R.string.ago);
- }
-
- public static long getStatusTime() {
- return status_time;
- }
-
- static void setStatus(String mystatus, long eventtime) {
- if (eventtime > status_time) {
- status_time = eventtime;
- status = mystatus;
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/PumpIdCache.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/PumpIdCache.java
deleted file mode 100644
index 9a2bcfeff5..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/history/PumpIdCache.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.history;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.utils.SP;
-
-/**
- * Created by jamorham on 01/02/2018.
- */
-
-public class PumpIdCache {
- private static Logger log = LoggerFactory.getLogger(L.PUMP);
-
- private static final String INSIGHT_PUMP_ID_PREF = "insight-pump-id";
- private static long cachedPumpSerialNumber = -1;
-
- static void updatePumpSerialNumber(long pump_serial_number) {
- if (pump_serial_number != cachedPumpSerialNumber) {
- cachedPumpSerialNumber = pump_serial_number;
- if (L.isEnabled(L.PUMP))
- log.debug("Updating pump serial number: " + pump_serial_number);
- SP.putLong(INSIGHT_PUMP_ID_PREF, cachedPumpSerialNumber);
- }
- }
-
- public static long getRecordUniqueID(long record_id) {
- if (cachedPumpSerialNumber == -1) {
- cachedPumpSerialNumber = SP.getLong(INSIGHT_PUMP_ID_PREF, 0L);
- }
- return HistoryIntentAdapter.getRecordUniqueID(cachedPumpSerialNumber, record_id);
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/Helpers.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/Helpers.java
deleted file mode 100644
index bfdca16588..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/Helpers.java
+++ /dev/null
@@ -1,197 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.utils;
-
-import android.content.Context;
-import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager;
-import android.os.Handler;
-import android.os.PowerManager;
-import android.util.Log;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.math.BigDecimal;
-import java.math.RoundingMode;
-import java.text.DecimalFormat;
-import java.text.DecimalFormatSymbols;
-import java.util.HashMap;
-import java.util.Map;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-
-/**
- * Created by jamorham on 24/01/2018.
- *
- * Useful utility methods from xDrip+
- */
-
-public class Helpers {
- private static Logger log = LoggerFactory.getLogger(L.PUMP);
-
-
- private static final Map rateLimits = new HashMap<>();
- // singletons to avoid repeated allocation
- private static DecimalFormatSymbols dfs;
- private static DecimalFormat df;
-
- // return true if below rate limit
- public static synchronized boolean ratelimit(String name, int seconds) {
- // check if over limit
- if ((rateLimits.containsKey(name)) && (tsl() - rateLimits.get(name) < (seconds * 1000))) {
- if (L.isEnabled(L.PUMP))
- log.debug(name + " rate limited: " + seconds + " seconds");
- return false;
- }
- // not over limit
- rateLimits.put(name, tsl());
- return true;
- }
-
- public static long tsl() {
- return System.currentTimeMillis();
- }
-
- public static long msSince(long when) {
- return (tsl() - when);
- }
-
- public static long msTill(long when) {
- return (when - tsl());
- }
-
- public static boolean checkPackageExists(Context context, String TAG, String packageName) {
- try {
- final PackageManager pm = context.getPackageManager();
- final PackageInfo pi = pm.getPackageInfo(packageName, 0);
- return pi.packageName.equals(packageName);
- } catch (PackageManager.NameNotFoundException e) {
- return false;
- } catch (Exception e) {
- log.error("Exception trying to determine packages! " + e);
- return false;
- }
- }
-
- public static boolean runOnUiThreadDelayed(Runnable theRunnable, long delay) {
- return new Handler(MainApp.instance().getMainLooper()).postDelayed(theRunnable, delay);
- }
-
- public static PowerManager.WakeLock getWakeLock(final String name, int millis) {
- final PowerManager pm = (PowerManager) MainApp.instance().getSystemService(Context.POWER_SERVICE);
- if (pm == null) return null;
- final PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, name);
- wl.acquire(millis);
- return wl;
- }
-
- public static void releaseWakeLock(PowerManager.WakeLock wl) {
- if (wl == null) return;
- if (wl.isHeld()) wl.release();
- }
-
- public static String niceTimeSince(long t) {
- return niceTimeScalar(msSince(t));
- }
-
- public static String niceTimeTill(long t) {
- return niceTimeScalar(-msSince(t));
- }
-
- public static String niceTimeScalar(long t) {
- String unit = MainApp.gs(R.string.second);
- t = t / 1000;
- if (t > 59) {
- unit = MainApp.gs(R.string.minute);
- t = t / 60;
- if (t > 59) {
- unit = MainApp.gs(R.string.hour);
- t = t / 60;
- if (t > 24) {
- unit = MainApp.gs(R.string.day);
- t = t / 24;
- if (t > 28) {
- unit = MainApp.gs(R.string.week);
- t = t / 7;
- }
- }
- }
- }
- if (t != 1) unit = unit + MainApp.gs(R.string.time_plural);
- return qs((double) t, 0) + " " + unit;
- }
-
- public static String qs(double x, int digits) {
-
- if (digits == -1) {
- digits = 0;
- if (((int) x != x)) {
- digits++;
- if ((((int) x * 10) / 10 != x)) {
- digits++;
- if ((((int) x * 100) / 100 != x)) digits++;
- }
- }
- }
-
- if (dfs == null) {
- final DecimalFormatSymbols local_dfs = new DecimalFormatSymbols();
- local_dfs.setDecimalSeparator('.');
- dfs = local_dfs; // avoid race condition
- }
-
- final DecimalFormat this_df;
- // use singleton if on ui thread otherwise allocate new as DecimalFormat is not thread safe
- if (Thread.currentThread().getId() == 1) {
- if (df == null) {
- final DecimalFormat local_df = new DecimalFormat("#", dfs);
- local_df.setMinimumIntegerDigits(1);
- df = local_df; // avoid race condition
- }
- this_df = df;
- } else {
- this_df = new DecimalFormat("#", dfs);
- }
-
- this_df.setMaximumFractionDigits(digits);
- return this_df.format(x);
- }
-
- public static String niceTimeScalarRedux(long t) {
- return niceTimeScalar(t).replaceFirst("^1 ", "");
- }
-
- public static String niceTimeScalarBrief(long t) {
- // TODO i18n wont work for non-latin characterset
- return niceTimeScalar(t).replaceFirst("([a-z])[a-z]*", "$1").replace(" ", "");
- }
-
- public static String hourMinuteString(long timestamp) {
- return android.text.format.DateFormat.format("kk:mm", timestamp).toString();
- }
-
- public static String hourMinuteSecondString(long timestamp) {
- return android.text.format.DateFormat.format("kk:mm:ss", timestamp).toString();
- }
-
- public static String dateTimeText(long timestamp) {
- return android.text.format.DateFormat.format("yyyy-MM-dd kk:mm:ss", timestamp).toString();
- }
-
- public static String dateText(long timestamp) {
- return android.text.format.DateFormat.format("yyyy-MM-dd", timestamp).toString();
- }
-
- public static String capitalize(String text) {
- return text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();
- }
-
- public static double roundDouble(double value, int places) {
- if (places < 0) throw new IllegalArgumentException("Invalid decimal places");
- BigDecimal bd = new BigDecimal(value);
- bd = bd.setScale(places, RoundingMode.HALF_UP);
- return bd.doubleValue();
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/StatusItem.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/StatusItem.java
deleted file mode 100644
index 395dd51084..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/StatusItem.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.utils;
-
-/**
- * Created by jamorham on 26/01/2018.
- *
- * For representing row status items
- */
-
-public class StatusItem {
-
- public enum Highlight {
- NORMAL,
- GOOD,
- BAD,
- NOTICE,
- CRITICAL
- }
-
- public String name;
- public String value;
- public Highlight highlight;
- public String button_name;
- public Runnable runnable;
-
-
- public StatusItem(String name, String value) {
- this(name, value, Highlight.NORMAL);
- }
-
- public StatusItem() {
- this("line-break", "", Highlight.NORMAL);
- }
-
- public StatusItem(String name, Highlight highlight) {
- this("heading-break", name, highlight);
- }
-
- public StatusItem(String name, Runnable runnable) {
- this("button-break", "", Highlight.NORMAL, name, runnable);
- }
-
- public StatusItem(String name, String value, Highlight highlight) {
- this(name, value, highlight, null, null);
- }
-
- public StatusItem(String name, String value, Highlight highlight, String button_name, Runnable runnable) {
- this.name = name;
- this.value = value;
- this.highlight = highlight;
- this.button_name = button_name;
- this.runnable = runnable;
- }
-
- public StatusItem(String name, Integer value) {
- this(name, value, Highlight.NORMAL);
- }
-
- public StatusItem(String name, Integer value, Highlight highlight) {
- this.name = name;
- this.value = Integer.toString(value);
- this.highlight = highlight;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/ui/StatusItemViewAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/ui/StatusItemViewAdapter.java
deleted file mode 100644
index 87c40c19de..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpInsight/utils/ui/StatusItemViewAdapter.java
+++ /dev/null
@@ -1,85 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpInsight.utils.ui;
-
-import android.app.Activity;
-import android.graphics.Color;
-import android.view.Gravity;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.PumpInsight.utils.StatusItem;
-
-/**
- * Created by jamorham on 26/01/2018.
- *
- * Convert StatusItem to View
- */
-
-public class StatusItemViewAdapter {
-
- private final Activity activity;
- private final ViewGroup holder;
-
- public StatusItemViewAdapter(Activity activity, ViewGroup holder) {
- this.activity = activity;
- this.holder = holder;
- }
-
- public View inflateStatus(StatusItem statusItem) {
- if (activity == null) return null;
- final View child = activity.getLayoutInflater().inflate(R.layout.insightpump_statuselements, null);
- final TextView name = (TextView) child.findViewById(R.id.insightstatuslabel);
- final TextView value = (TextView)child.findViewById(R.id.insightstatusvalue);
- final TextView spacer = (TextView)child.findViewById(R.id.insightstatusspacer);
- final LinearLayout layout = (LinearLayout)child.findViewById(R.id.insightstatuslayout);
-
- if (statusItem.name.equals("line-break")) {
- spacer.setVisibility(View.GONE);
- name.setVisibility(View.GONE);
- value.setVisibility(View.GONE);
- layout.setPadding(10, 10, 10, 10);
- } else if (statusItem.name.equals("heading-break")) {
- value.setVisibility(View.GONE);
- spacer.setVisibility(View.GONE);
- name.setText(statusItem.value);
- name.setGravity(Gravity.CENTER_HORIZONTAL);
- name.setTextColor(Color.parseColor("#fff9c4"));
- } else {
- name.setText(statusItem.name);
- value.setText(statusItem.value);
- }
-
- final int this_color = getHighlightColor(statusItem);
- name.setBackgroundColor(this_color);
- value.setBackgroundColor(this_color);
- spacer.setBackgroundColor(this_color);
-
- if (this_color != Color.TRANSPARENT) {
- name.setTextColor(Color.WHITE);
- spacer.setTextColor(Color.WHITE);
- }
-
- if (holder != null) {
- holder.addView(child);
- }
- return child;
- }
-
- private static int getHighlightColor(StatusItem row) {
- switch (row.highlight) {
- case BAD:
- return Color.parseColor("#480000");
- case NOTICE:
- return Color.parseColor("#403000");
- case GOOD:
- return Color.parseColor("#003000");
- case CRITICAL:
- return Color.parseColor("#770000");
- default:
- return Color.TRANSPARENT;
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java
deleted file mode 100644
index ef4c85e0a7..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/VirtualPumpFragment.java
+++ /dev/null
@@ -1,122 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpVirtual;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import android.support.annotation.Nullable;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.PumpCommon.defs.PumpType;
-import info.nightscout.androidaps.plugins.PumpVirtual.events.EventVirtualPumpUpdateGui;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.FabricPrivacy;
-
-public class VirtualPumpFragment extends SubscriberFragment {
- private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class);
-
- TextView basaBasalRateView;
- TextView tempBasalView;
- TextView extendedBolusView;
- TextView batteryView;
- TextView reservoirView;
- TextView pumpTypeView;
- TextView pumpSettingsView;
-
-
- private static Handler sLoopHandler = new Handler();
- private static Runnable sRefreshLoop = null;
-
- @Override
- public void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (sRefreshLoop == null) {
- sRefreshLoop = new Runnable() {
- @Override
- public void run() {
- updateGUI();
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- }
- };
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- }
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.virtualpump_fragment, container, false);
- basaBasalRateView = (TextView) view.findViewById(R.id.virtualpump_basabasalrate);
- tempBasalView = (TextView) view.findViewById(R.id.virtualpump_tempbasal);
- extendedBolusView = (TextView) view.findViewById(R.id.virtualpump_extendedbolus);
- batteryView = (TextView) view.findViewById(R.id.virtualpump_battery);
- reservoirView = (TextView) view.findViewById(R.id.virtualpump_reservoir);
- pumpTypeView = (TextView) view.findViewById(R.id.virtualpump_type);
- pumpSettingsView = (TextView) view.findViewById(R.id.virtualpump_type_def);
-
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Subscribe
- public void onStatusEvent(final EventVirtualPumpUpdateGui ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null && basaBasalRateView != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- VirtualPumpPlugin virtualPump = VirtualPumpPlugin.getPlugin();
- basaBasalRateView.setText(virtualPump.getBaseBasalRate() + "U");
- TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (activeTemp != null) {
- tempBasalView.setText(activeTemp.toStringFull());
- } else {
- tempBasalView.setText("");
- }
- ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
- if (activeExtendedBolus != null) {
- extendedBolusView.setText(activeExtendedBolus.toString());
- } else {
- extendedBolusView.setText("");
- }
- batteryView.setText(virtualPump.batteryPercent + "%");
- reservoirView.setText(virtualPump.reservoirInUnits + "U");
-
- virtualPump.refreshConfiguration();
-
- PumpType pumpType = virtualPump.getPumpType();
-
- pumpTypeView.setText(pumpType.getDescription());
-
- String template = MainApp.gs(R.string.virtualpump_pump_def);
-
-
- pumpSettingsView.setText(pumpType.getFullDescription(template, pumpType.hasExtendedBasals()));
-
- }
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/events/EventVirtualPumpUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/events/EventVirtualPumpUpdateGui.java
deleted file mode 100644
index e035ea3aba..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/PumpVirtual/events/EventVirtualPumpUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.PumpVirtual.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventVirtualPumpUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java
deleted file mode 100644
index 3f218063ef..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorFragment.java
+++ /dev/null
@@ -1,92 +0,0 @@
-package info.nightscout.androidaps.plugins.SmsCommunicator;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.support.v4.app.Fragment;
-import android.text.Html;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collections;
-import java.util.Comparator;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.FabricPrivacy;
-
-/**
- * A simple {@link Fragment} subclass.
- */
-public class SmsCommunicatorFragment extends SubscriberFragment {
- private static Logger log = LoggerFactory.getLogger(SmsCommunicatorFragment.class);
-
- TextView logView;
-
- public SmsCommunicatorFragment() {
- super();
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false);
-
- logView = (TextView) view.findViewById(R.id.smscommunicator_log);
-
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Subscribe
- public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) {
- updateGUI();
- }
-
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- class CustomComparator implements Comparator {
- public int compare(SmsCommunicatorPlugin.Sms object1, SmsCommunicatorPlugin.Sms object2) {
- return (int) (object1.date - object2.date);
- }
- }
- Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator());
- int messagesToShow = 40;
-
- int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow);
-
- String logText = "";
- for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) {
- SmsCommunicatorPlugin.Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x);
- if (sms.received) {
- logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
";
- } else if (sms.sent) {
- logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + "
";
- }
- }
- logView.setText(Html.fromHtml(logText));
- }
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java
deleted file mode 100644
index b3800cbe82..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/SmsCommunicatorPlugin.java
+++ /dev/null
@@ -1,605 +0,0 @@
-package info.nightscout.androidaps.plugins.SmsCommunicator;
-
-import android.content.Intent;
-import android.content.pm.ResolveInfo;
-import android.os.Bundle;
-import android.os.SystemClock;
-import android.telephony.SmsManager;
-import android.telephony.SmsMessage;
-
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.text.Normalizer;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.services.Intents;
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.GlucoseStatus;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.DatabaseHelper;
-import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.Overview.notifications.Notification;
-import info.nightscout.androidaps.plugins.SmsCommunicator.events.EventSmsCommunicatorUpdateGui;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
-import info.nightscout.utils.T;
-import info.nightscout.utils.XdripCalibrations;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class SmsCommunicatorPlugin extends PluginBase {
- private static Logger log = LoggerFactory.getLogger(SmsCommunicatorPlugin.class);
-
- private static SmsCommunicatorPlugin smsCommunicatorPlugin;
-
- public static SmsCommunicatorPlugin getPlugin() {
-
- if (smsCommunicatorPlugin == null) {
- smsCommunicatorPlugin = new SmsCommunicatorPlugin();
- }
- return smsCommunicatorPlugin;
- }
-
- private List allowedNumbers = new ArrayList<>();
-
- class Sms {
- String phoneNumber;
- String text;
- long date;
- boolean received = false;
- boolean sent = false;
- boolean processed = false;
-
- String confirmCode;
- double bolusRequested = 0d;
- double tempBasal = 0d;
- double calibrationRequested = 0d;
- int duration = 0;
-
- Sms(SmsMessage message) {
- phoneNumber = message.getOriginatingAddress();
- text = message.getMessageBody();
- date = message.getTimestampMillis();
- received = true;
- }
-
- Sms(String phoneNumber, String text, long date) {
- this.phoneNumber = phoneNumber;
- this.text = text;
- this.date = date;
- sent = true;
- }
-
- Sms(String phoneNumber, String text, long date, String confirmCode) {
- this.phoneNumber = phoneNumber;
- this.text = text;
- this.date = date;
- this.confirmCode = confirmCode;
- sent = true;
- }
-
- public String toString() {
- return "SMS from " + phoneNumber + ": " + text;
- }
- }
-
- private Sms cancelTempBasalWaitingForConfirmation = null;
- private Sms tempBasalWaitingForConfirmation = null;
- private Sms bolusWaitingForConfirmation = null;
- private Sms calibrationWaitingForConfirmation = null;
- private Sms suspendWaitingForConfirmation = null;
- private Date lastRemoteBolusTime = new Date(0);
-
- ArrayList messages = new ArrayList<>();
-
- private SmsCommunicatorPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(SmsCommunicatorFragment.class.getName())
- .pluginName(R.string.smscommunicator)
- .shortName(R.string.smscommunicator_shortname)
- .preferencesId(R.xml.pref_smscommunicator)
- .description(R.string.description_sms_communicator)
- );
- processSettings(null);
- }
-
- @Override
- protected void onStart() {
- MainApp.bus().register(this);
- super.onStart();
- }
-
- @Override
- protected void onStop() {
- MainApp.bus().unregister(this);
- }
-
- @Subscribe
- public void processSettings(final EventPreferenceChange ev) {
- if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) {
- String settings = SP.getString(R.string.key_smscommunicator_allowednumbers, "");
-
- String pattern = ";";
-
- String[] substrings = settings.split(pattern);
- for (String number : substrings) {
- String cleaned = number.replaceAll("\\s+", "");
- allowedNumbers.add(cleaned);
- log.debug("Found allowed number: " + cleaned);
- }
- }
- }
-
- private boolean isAllowedNumber(String number) {
- for (String num : allowedNumbers) {
- if (num.equals(number)) return true;
- }
- return false;
- }
-
- public void handleNewData(Intent intent) {
- Bundle bundle = intent.getExtras();
- if (bundle == null) return;
-
- Object[] pdus = (Object[]) bundle.get("pdus");
- if (pdus != null) {
- // For every SMS message received
- for (Object pdu : pdus) {
- SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
- processSms(new Sms(message));
- }
- }
- }
-
- private void processSms(final Sms receivedSms) {
- if (!isEnabled(PluginType.GENERAL)) {
- log.debug("Ignoring SMS. Plugin disabled.");
- return;
- }
- if (!isAllowedNumber(receivedSms.phoneNumber)) {
- log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed");
- return;
- }
-
- String reply = "";
-
- messages.add(receivedSms);
- log.debug(receivedSms.toString());
-
- String[] splited = receivedSms.text.split("\\s+");
- Double amount;
- Double tempBasal;
- int duration = 0;
- String passCode;
- boolean remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false);
-
- if (splited.length > 0) {
- switch (splited[0].toUpperCase()) {
- case "BG":
- BgReading actualBG = DatabaseHelper.actualBg();
- BgReading lastBG = DatabaseHelper.lastBg();
-
- String units = ProfileFunctions.getInstance().getProfileUnits();
-
- if (actualBG != null) {
- reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", ";
- } else if (lastBG != null) {
- Long agoMsec = System.currentTimeMillis() - lastBG.date;
- int agoMin = (int) (agoMsec / 60d / 1000d);
- reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", ";
- }
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- if (glucoseStatus != null)
- reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", ";
-
- TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
- IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
- TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
- IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
-
- reply += MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
- + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
- + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U)";
-
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bg"));
- break;
- case "LOOP":
- if (splited.length > 1)
- switch (splited[1].toUpperCase()) {
- case "DISABLE":
- case "STOP":
- LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) {
- loopPlugin.setPluginEnabled(PluginType.LOOP, false);
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP"));
- String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
- MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- });
- }
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Stop"));
- break;
- case "ENABLE":
- case "START":
- loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) {
- loopPlugin.setPluginEnabled(PluginType.LOOP, true);
- reply = MainApp.gs(R.string.smscommunicator_loophasbeenenabled);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START"));
- }
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Start"));
- break;
- case "STATUS":
- loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null) {
- if (loopPlugin.isEnabled(PluginType.LOOP)) {
- if (loopPlugin.isSuspended())
- reply = String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend());
- else
- reply = MainApp.gs(R.string.smscommunicator_loopisenabled);
- } else {
- reply = MainApp.gs(R.string.smscommunicator_loopisdisabled);
- }
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Status"));
- break;
- case "RESUME":
- LoopPlugin.getPlugin().suspendTo(0);
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME"));
- NSUpload.uploadOpenAPSOffline(0);
- reply = MainApp.gs(R.string.smscommunicator_loopresumed);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Resume"));
- break;
- case "SUSPEND":
- if (splited.length >= 3)
- duration = SafeParse.stringToInt(splited[2]);
- duration = Math.max(0, duration);
- duration = Math.min(180, duration);
- if (duration == 0) {
- reply = MainApp.gs(R.string.smscommunicator_wrongduration);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else if (remoteCommandsAllowed) {
- passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode);
- receivedSms.processed = true;
- resetWaitingMessages();
- sendSMS(suspendWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
- suspendWaitingForConfirmation.duration = duration;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Loop_Suspend"));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_remotecommandnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- break;
- }
- break;
- case "TREATMENTS":
- if (splited.length > 1)
- switch (splited[1].toUpperCase()) {
- case "REFRESH":
- Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
- TreatmentsPlugin.getPlugin().getService().resetTreatments();
- MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
- List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
- reply = "TERATMENTS REFRESH " + q.size() + " receivers";
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Treatments_Refresh"));
- break;
- }
- break;
- case "NSCLIENT":
- if (splited.length > 1)
- switch (splited[1].toUpperCase()) {
- case "RESTART":
- Intent restartNSClient = new Intent(Intents.ACTION_RESTART);
- MainApp.instance().getApplicationContext().sendBroadcast(restartNSClient);
- List q = MainApp.instance().getApplicationContext().getPackageManager().queryBroadcastReceivers(restartNSClient, 0);
- reply = "NSCLIENT RESTART " + q.size() + " receivers";
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Nsclient_Restart"));
- break;
- }
- break;
- case "PUMP":
- case "DANAR":
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() {
- @Override
- public void run() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- if (result.success) {
- if (pump != null) {
- String reply = pump.shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- } else {
- String reply = MainApp.gs(R.string.readstatusfailed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- });
- receivedSms.processed = true;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Pump"));
- break;
- case "BASAL":
- if (splited.length > 1) {
- if (splited[1].toUpperCase().equals("CANCEL") || splited[1].toUpperCase().equals("STOP")) {
- if (remoteCommandsAllowed) {
- passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode);
- receivedSms.processed = true;
- resetWaitingMessages();
- sendSMS(cancelTempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- } else {
- tempBasal = SafeParse.stringToDouble(splited[1]);
- Profile profile = ProfileFunctions.getInstance().getProfile();
- if (profile == null) {
- reply = MainApp.gs(R.string.noprofile);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value();
- if (remoteCommandsAllowed) {
- passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, passCode);
- receivedSms.processed = true;
- resetWaitingMessages();
- sendSMS(tempBasalWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
- tempBasalWaitingForConfirmation.tempBasal = tempBasal;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Basal"));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_remotebasalnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- }
- }
- break;
- case "BOLUS":
- if (System.currentTimeMillis() - lastRemoteBolusTime.getTime() < Constants.remoteBolusMinDistance) {
- reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else if (ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended()) {
- reply = MainApp.gs(R.string.pumpsuspended);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else if (splited.length > 1) {
- amount = SafeParse.stringToDouble(splited[1]);
- amount = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(amount)).value();
- if (amount > 0d && remoteCommandsAllowed) {
- passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), amount, passCode);
- receivedSms.processed = true;
- resetWaitingMessages();
- sendSMS(bolusWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
- bolusWaitingForConfirmation.bolusRequested = amount;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Bolus"));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_remotebolusnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- break;
- case "CAL":
- if (splited.length > 1) {
- amount = SafeParse.stringToDouble(splited[1]);
- if (amount > 0d && remoteCommandsAllowed) {
- passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), amount, passCode);
- receivedSms.processed = true;
- resetWaitingMessages();
- sendSMS(calibrationWaitingForConfirmation = new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis(), passCode));
- calibrationWaitingForConfirmation.calibrationRequested = amount;
- FabricPrivacy.getInstance().logCustom(new CustomEvent("SMS_Cal"));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_remotecalibrationnotallowed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- break;
- default: // expect passCode here
- if (bolusWaitingForConfirmation != null && !bolusWaitingForConfirmation.processed &&
- bolusWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - bolusWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
- bolusWaitingForConfirmation.processed = true;
- DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
- detailedBolusInfo.insulin = bolusWaitingForConfirmation.bolusRequested;
- detailedBolusInfo.source = Source.USER;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
- @Override
- public void run() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- if (result.success) {
- SystemClock.sleep(T.secs(15).msecs()); // wait some time to get history
- String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), result.bolusDelivered);
- if (pump != null)
- reply += "\n" + pump.shortStatus(true);
- lastRemoteBolusTime = new Date();
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- SystemClock.sleep(T.secs(60).msecs()); // wait some time to get history
- String reply = MainApp.gs(R.string.smscommunicator_bolusfailed);
- if (pump != null)
- reply += "\n" + pump.shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- });
- } else if (tempBasalWaitingForConfirmation != null && !tempBasalWaitingForConfirmation.processed &&
- tempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - tempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
- tempBasalWaitingForConfirmation.processed = true;
- Profile profile = ProfileFunctions.getInstance().getProfile();
- if (profile != null)
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(tempBasalWaitingForConfirmation.tempBasal, 30, true, profile, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- });
- } else if (cancelTempBasalWaitingForConfirmation != null && !cancelTempBasalWaitingForConfirmation.processed &&
- cancelTempBasalWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - cancelTempBasalWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
- cancelTempBasalWaitingForConfirmation.processed = true;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- });
- } else if (calibrationWaitingForConfirmation != null && !calibrationWaitingForConfirmation.processed &&
- calibrationWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - calibrationWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
- calibrationWaitingForConfirmation.processed = true;
- boolean result = XdripCalibrations.sendIntent(calibrationWaitingForConfirmation.calibrationRequested);
- if (result) {
- reply = MainApp.gs(R.string.smscommunicator_calibrationsent);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- reply = MainApp.gs(R.string.smscommunicator_calibrationfailed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- } else if (suspendWaitingForConfirmation != null && !suspendWaitingForConfirmation.processed &&
- suspendWaitingForConfirmation.confirmCode.equals(splited[0]) && System.currentTimeMillis() - suspendWaitingForConfirmation.date < Constants.SMS_CONFIRM_TIMEOUT) {
- suspendWaitingForConfirmation.processed = true;
- final int dur = suspendWaitingForConfirmation.duration;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + dur * 60L * 1000);
- NSUpload.uploadOpenAPSOffline(dur * 60);
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED"));
- String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " +
- MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply, System.currentTimeMillis()));
- }
- }
- });
- } else {
- sendSMS(new Sms(receivedSms.phoneNumber, MainApp.gs(R.string.smscommunicator_unknowncommand), System.currentTimeMillis()));
- }
- resetWaitingMessages();
- break;
- }
- }
-
- MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
- }
-
- public void sendNotificationToAllNumbers(String text) {
- for (int i = 0; i < allowedNumbers.size(); i++) {
- Sms sms = new Sms(allowedNumbers.get(i), text, System.currentTimeMillis());
- sendSMS(sms);
- }
- }
-
- private void sendSMSToAllNumbers(Sms sms) {
- for (String number : allowedNumbers) {
- sms.phoneNumber = number;
- sendSMS(sms);
- }
- }
-
- private void sendSMS(Sms sms) {
- SmsManager smsManager = SmsManager.getDefault();
- sms.text = stripAccents(sms.text);
- if (sms.text.length() > 140) sms.text = sms.text.substring(0, 139);
- try {
- log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text);
- smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null);
- messages.add(sms);
- } catch (IllegalArgumentException e) {
- Notification notification = new Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL);
- MainApp.bus().post(new EventNewNotification(notification));
- } catch (java.lang.SecurityException e) {
- Notification notification = new Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL);
- MainApp.bus().post(new EventNewNotification(notification));
- }
- }
-
- private String generatePasscode() {
- int startChar1 = 'A'; // on iphone 1st char is uppercase :)
- String passCode = Character.toString((char) (startChar1 + Math.random() * ('z' - 'a' + 1)));
- int startChar2 = Math.random() > 0.5 ? 'a' : 'A';
- passCode += Character.toString((char) (startChar2 + Math.random() * ('z' - 'a' + 1)));
- int startChar3 = Math.random() > 0.5 ? 'a' : 'A';
- passCode += Character.toString((char) (startChar3 + Math.random() * ('z' - 'a' + 1)));
- return passCode;
- }
-
- private void resetWaitingMessages() {
- tempBasalWaitingForConfirmation = null;
- cancelTempBasalWaitingForConfirmation = null;
- bolusWaitingForConfirmation = null;
- calibrationWaitingForConfirmation = null;
- suspendWaitingForConfirmation = null;
- }
-
- private static String stripAccents(String s) {
- s = Normalizer.normalize(s, Normalizer.Form.NFD);
- s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
- return s;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventSmsCommunicatorUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventSmsCommunicatorUpdateGui.java
deleted file mode 100644
index 02956a5d67..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/SmsCommunicator/events/EventSmsCommunicatorUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.SmsCommunicator.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventSmsCommunicatorUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java
deleted file mode 100644
index 460e550b8e..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Source/SourceDexcomG5Plugin.java
+++ /dev/null
@@ -1,95 +0,0 @@
-package info.nightscout.androidaps.plugins.Source;
-
-import android.content.Intent;
-import android.os.Bundle;
-
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.interfaces.BgSourceInterface;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.utils.SP;
-
-/**
- * Created by mike on 28.11.2017.
- */
-
-public class SourceDexcomG5Plugin extends PluginBase implements BgSourceInterface {
- private static Logger log = LoggerFactory.getLogger(L.BGSOURCE);
-
- private static SourceDexcomG5Plugin plugin = null;
-
- public static SourceDexcomG5Plugin getPlugin() {
- if (plugin == null)
- plugin = new SourceDexcomG5Plugin();
- return plugin;
- }
-
- private SourceDexcomG5Plugin() {
- super(new PluginDescription()
- .mainType(PluginType.BGSOURCE)
- .fragmentClass(BGSourceFragment.class.getName())
- .pluginName(R.string.DexcomG5)
- .shortName(R.string.dexcomG5_shortname)
- .preferencesId(R.xml.pref_dexcomg5)
- .description(R.string.description_source_dexcom_g5)
- );
- }
-
- @Override
- public boolean advancedFilteringSupported() {
- return true;
- }
-
- @Override
- public void handleNewData(Intent intent) {
- // onHandleIntent Bundle{ data => [{"m_time":1511939180,"m_trend":"NotComputable","m_value":335}]; android.support.content.wakelockid => 95; }Bundle
-
- if (!isEnabled(PluginType.BGSOURCE)) return;
-
- Bundle bundle = intent.getExtras();
- if (bundle == null) return;
-
- BgReading bgReading = new BgReading();
-
- String data = bundle.getString("data");
- if (L.isEnabled(L.BGSOURCE))
- log.debug("Received Dexcom Data", data);
-
- if (data == null) return;
-
- try {
- JSONArray jsonArray = new JSONArray(data);
- if (L.isEnabled(L.BGSOURCE))
- log.debug("Received Dexcom Data size:" + jsonArray.length());
- for (int i = 0; i < jsonArray.length(); i++) {
- JSONObject json = jsonArray.getJSONObject(i);
- bgReading.value = json.getInt("m_value");
- bgReading.direction = json.getString("m_trend");
- bgReading.date = json.getLong("m_time") * 1000L;
- bgReading.raw = 0;
- boolean isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "DexcomG5");
- if (isNew && SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
- NSUpload.uploadBg(bgReading);
- }
- if (isNew && SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
- NSUpload.sendToXdrip(bgReading);
- }
- }
-
- } catch (JSONException e) {
- log.error("Exception: ", e);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/dialogs/WizardInfoDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/dialogs/WizardInfoDialog.java
deleted file mode 100644
index 25ffc946a2..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/dialogs/WizardInfoDialog.java
+++ /dev/null
@@ -1,88 +0,0 @@
-package info.nightscout.androidaps.plugins.Treatments.dialogs;
-
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.view.Window;
-import android.view.WindowManager;
-import android.widget.CheckBox;
-import android.widget.TextView;
-
-import org.json.JSONObject;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.JsonHelper;
-
-public class WizardInfoDialog extends DialogFragment implements OnClickListener {
- JSONObject json;
-
- public WizardInfoDialog() {
- super();
- }
-
- public void setData(JSONObject json) {
- this.json = json;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.treatments_wizardinfo_dialog, container, false);
-
- getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
-
- view.findViewById(R.id.ok).setOnClickListener(this);
-
- // BG
- ((TextView) view.findViewById(R.id.treatments_wizard_bg)).setText(DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "bg")) + " ISF: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "isf")));
- ((TextView) view.findViewById(R.id.treatments_wizard_bginsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulinbg")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_bgcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "insulinbgused"));
- ((CheckBox) view.findViewById(R.id.treatments_wizard_ttcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "ttused"));
- // Trend
- ((TextView) view.findViewById(R.id.treatments_wizard_bgtrend)).setText(JsonHelper.safeGetString(json, "trend"));
- ((TextView) view.findViewById(R.id.treatments_wizard_bgtrendinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulintrend")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_bgtrendcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "trendused"));
- // COB
- ((TextView) view.findViewById(R.id.treatments_wizard_cob)).setText(DecimalFormatter.to0Decimal(JsonHelper.safeGetDouble(json, "cob")) + "g IC: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "ic")));
- ((TextView) view.findViewById(R.id.treatments_wizard_cobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulincob")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_cobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "cobused"));
- // Bolus IOB
- ((TextView) view.findViewById(R.id.treatments_wizard_bolusiobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "bolusiob")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_bolusiobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "bolusiobused"));
- // Basal IOB
- ((TextView) view.findViewById(R.id.treatments_wizard_basaliobinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "basaliob")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_basaliobcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "basaliobused"));
- // Superbolus
- ((TextView) view.findViewById(R.id.treatments_wizard_sbinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulinsuperbolus")) + "U");
- ((CheckBox) view.findViewById(R.id.treatments_wizard_sbcheckbox)).setChecked(JsonHelper.safeGetBoolean(json, "superbolusused"));
- // Carbs
- ((TextView) view.findViewById(R.id.treatments_wizard_carbs)).setText(DecimalFormatter.to0Decimal(JsonHelper.safeGetDouble(json, "carbs")) + "g IC: " + DecimalFormatter.to1Decimal(JsonHelper.safeGetDouble(json, "ic")));
- ((TextView) view.findViewById(R.id.treatments_wizard_carbsinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulincarbs")) + "U");
- // Correction
- ((TextView) view.findViewById(R.id.treatments_wizard_correctioninsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "othercorrection")) + "U");
- // Profile
- ((TextView) view.findViewById(R.id.treatments_wizard_profile)).setText(JsonHelper.safeGetString(json, "profile"));
- // Notes
- ((TextView) view.findViewById(R.id.treatments_wizard_notes)).setText(JsonHelper.safeGetString(json, "notes"));
- // Total
- ((TextView) view.findViewById(R.id.treatments_wizard_totalinsulin)).setText(DecimalFormatter.to2Decimal(JsonHelper.safeGetDouble(json, "insulin")) + "U");
-
- setCancelable(true);
- return view;
- }
-
- @Override
- public synchronized void onClick(View view) {
- switch (view.getId()) {
- case R.id.ok:
- dismiss();
- break;
- }
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java
deleted file mode 100644
index c2263d81b5..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Treatments/fragments/ProfileViewerDialog.java
+++ /dev/null
@@ -1,139 +0,0 @@
-package info.nightscout.androidaps.plugins.Treatments.fragments;
-
-import android.os.Bundle;
-import android.support.v4.app.DialogFragment;
-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 org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import butterknife.BindView;
-import butterknife.ButterKnife;
-import butterknife.Unbinder;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.db.ProfileSwitch;
-import info.nightscout.androidaps.plugins.PumpDanaR.Dialogs.ProfileViewDialog;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.DecimalFormatter;
-
-/**
- * Created by adrian on 17/08/17.
- */
-
-public class ProfileViewerDialog extends DialogFragment {
-
- private long time;
-
- @BindView(R.id.profileview_noprofile)
- TextView noProfile;
- @BindView(R.id.profileview_invalidprofile)
- TextView invalidProfile;
- @BindView(R.id.profileview_units)
- TextView units;
- @BindView(R.id.profileview_dia)
- TextView dia;
- @BindView(R.id.profileview_activeprofile)
- TextView activeProfile;
- @BindView(R.id.profileview_ic)
- TextView ic;
- @BindView(R.id.profileview_isf)
- TextView isf;
- @BindView(R.id.profileview_basal)
- TextView basal;
- @BindView(R.id.profileview_target)
- TextView target;
- @BindView(R.id.profileview_datedelimiter)
- View dateDelimiter;
- @BindView(R.id.profileview_datelayout)
- LinearLayout dateLayout;
- @BindView(R.id.profileview_date)
- TextView dateTextView;
- @BindView(R.id.profileview_reload)
- Button refreshButton;
- @BindView(R.id.basal_graph)
- ProfileGraph basalGraph;
-
- private Unbinder unbinder;
-
- public static ProfileViewerDialog newInstance(long time) {
- ProfileViewerDialog dialog = new ProfileViewerDialog();
-
- Bundle args = new Bundle();
- args.putLong("time", time);
- dialog.setArguments(args);
-
- return dialog;
- }
-
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- time = getArguments().getLong("time");
- }
-
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- if (unbinder != null)
- unbinder.unbind();
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.profileviewer_fragment, container, false);
-
- unbinder = ButterKnife.bind(this, view);
-
- refreshButton.setVisibility(View.GONE);
- dateDelimiter.setVisibility(View.VISIBLE);
- dateLayout.setVisibility(View.VISIBLE);
-
- setContent();
- return view;
- }
-
- @Override
- public void onResume() {
- ViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();
- params.width = ViewGroup.LayoutParams.MATCH_PARENT;
- params.height = ViewGroup.LayoutParams.MATCH_PARENT;
- getDialog().getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
- super.onResume();
- }
-
- private void setContent() {
- Profile profile = null;
- ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time);
- if (profileSwitch != null && profileSwitch.profileJson != null) {
- profile = profileSwitch.getProfileObject();
- }
- if (profile != null) {
- noProfile.setVisibility(View.GONE);
- units.setText(profile.getUnits());
- dia.setText(DecimalFormatter.to2Decimal(profile.getDia()) + " h");
- activeProfile.setText(profileSwitch.getCustomizedName());
- dateTextView.setText(DateUtil.dateAndTimeString(profileSwitch.date));
- ic.setText(profile.getIcList());
- isf.setText(profile.getIsfList());
- basal.setText(profile.getBasalList());
- target.setText(profile.getTargetList());
- basalGraph.show(profile);
-
- if (profile.isValid("ProfileViewDialog"))
- invalidProfile.setVisibility(View.GONE);
- else
- invalidProfile.setVisibility(View.VISIBLE);
- } else {
- noProfile.setVisibility(View.VISIBLE);
- }
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java
deleted file mode 100644
index 72b2397213..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/WearPlugin.java
+++ /dev/null
@@ -1,217 +0,0 @@
-package info.nightscout.androidaps.plugins.Wear;
-
-import android.content.Context;
-import android.content.Intent;
-
-import com.squareup.otto.Subscribe;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventBolusRequested;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventNewBG;
-import info.nightscout.androidaps.events.EventNewBasalProfile;
-import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.events.EventTreatmentChange;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.plugins.Loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.Overview.events.EventDismissBolusprogressIfRunning;
-import info.nightscout.androidaps.plugins.Overview.events.EventOverviewBolusProgress;
-import info.nightscout.androidaps.plugins.Wear.wearintegration.WatchUpdaterService;
-import info.nightscout.utils.SP;
-
-/**
- * Created by adrian on 17/11/16.
- */
-
-public class WearPlugin extends PluginBase {
-
- private static WatchUpdaterService watchUS;
- private final Context ctx;
-
- private static WearPlugin wearPlugin;
-
- public static WearPlugin getPlugin() {
- return wearPlugin;
- }
-
- public static WearPlugin initPlugin(Context ctx) {
-
- if (wearPlugin == null) {
- wearPlugin = new WearPlugin(ctx);
- }
-
- return wearPlugin;
- }
-
- WearPlugin(Context ctx) {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(WearFragment.class.getName())
- .pluginName(R.string.wear)
- .shortName(R.string.wear_shortname)
- .preferencesId(R.xml.pref_wear)
- .description(R.string.description_wear)
- );
- this.ctx = ctx;
- }
-
- @Override
- protected void onStart() {
- MainApp.bus().register(this);
- if (watchUS != null) {
- watchUS.setSettings();
- }
- super.onStart();
- }
-
- @Override
- protected void onStop() {
- MainApp.bus().unregister(this);
- }
-
- private void sendDataToWatch(boolean status, boolean basals, boolean bgValue) {
- if (isEnabled(getType())) { //only start service when this plugin is enabled
-
- if (bgValue) {
- ctx.startService(new Intent(ctx, WatchUpdaterService.class));
- }
-
- if (basals) {
- ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BASALS));
- }
-
- if (status) {
- ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_STATUS));
- }
- }
- }
-
- void resendDataToWatch() {
- ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_RESEND));
- }
-
- void openSettings() {
- ctx.startService(new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_OPEN_SETTINGS));
- }
-
- void requestNotificationCancel(String actionstring) {
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_CANCEL_NOTIFICATION);
- intent.putExtra("actionstring", actionstring);
- ctx.startService(intent);
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- // possibly new high or low mark
- resendDataToWatch();
- // status may be formated differently
- sendDataToWatch(true, false, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventOpenAPSUpdateGui ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBG ev) {
- sendDataToWatch(true, true, true);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBasalProfile ev) {
- sendDataToWatch(false, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) {
- sendDataToWatch(true, false, false);
- }
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventOverviewBolusProgress ev) {
- if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) {
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", ev.percent);
- intent.putExtra("progressstatus", ev.status);
- ctx.startService(intent);
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventBolusRequested ev) {
- String status = String.format(MainApp.gs(R.string.bolusrequested), ev.getAmount());
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", 0);
- intent.putExtra("progressstatus", status);
- ctx.startService(intent);
-
- }
-
- @Subscribe
- public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) {
- if (ev.result == null) return;
-
- String status;
- if (ev.result.success) {
- status = MainApp.gs(R.string.success);
- } else {
- status = MainApp.gs(R.string.nosuccess);
- }
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", 100);
- intent.putExtra("progressstatus", status);
- ctx.startService(intent);
- }
-
- public void requestActionConfirmation(String title, String message, String actionstring) {
-
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST);
- intent.putExtra("title", title);
- intent.putExtra("message", message);
- intent.putExtra("actionstring", actionstring);
- ctx.startService(intent);
- }
-
- public void requestChangeConfirmation(String title, String message, String actionstring) {
-
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_CHANGECONFIRMATIONREQUEST);
- intent.putExtra("title", title);
- intent.putExtra("message", message);
- intent.putExtra("actionstring", actionstring);
- ctx.startService(intent);
- }
-
- public static void registerWatchUpdaterService(WatchUpdaterService wus) {
- watchUS = wus;
- }
-
- public static void unRegisterWatchUpdaterService() {
- watchUS = null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/SendToDataLayerThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/SendToDataLayerThread.java
deleted file mode 100644
index 02c74defca..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Wear/wearintegration/SendToDataLayerThread.java
+++ /dev/null
@@ -1,52 +0,0 @@
-package info.nightscout.androidaps.plugins.Wear.wearintegration;
-
-import android.os.AsyncTask;
-import android.util.Log;
-
-import com.google.android.gms.common.api.GoogleApiClient;
-import com.google.android.gms.wearable.DataApi;
-import com.google.android.gms.wearable.DataMap;
-import com.google.android.gms.wearable.Node;
-import com.google.android.gms.wearable.NodeApi;
-import com.google.android.gms.wearable.PutDataMapRequest;
-import com.google.android.gms.wearable.PutDataRequest;
-import com.google.android.gms.wearable.Wearable;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * Created by emmablack on 12/26/14.
- */
-class SendToDataLayerThread extends AsyncTask {
- private GoogleApiClient googleApiClient;
- private static final String TAG = "SendDataThread";
- String path;
-
- SendToDataLayerThread(String path, GoogleApiClient pGoogleApiClient) {
- this.path = path;
- googleApiClient = pGoogleApiClient;
- }
-
- @Override
- protected Void doInBackground(DataMap... params) {
- try {
- final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(15, TimeUnit.SECONDS);
- for (Node node : nodes.getNodes()) {
- for (DataMap dataMap : params) {
- PutDataMapRequest putDMR = PutDataMapRequest.create(path);
- putDMR.getDataMap().putAll(dataMap);
- PutDataRequest request = putDMR.asPutDataRequest();
- DataApi.DataItemResult result = Wearable.DataApi.putDataItem(googleApiClient, request).await(15, TimeUnit.SECONDS);
- if (result.getStatus().isSuccess()) {
- Log.d(TAG, "DataMap: " + dataMap + " sent to: " + node.getDisplayName());
- } else {
- Log.d(TAG, "ERROR: failed to send DataMap");
- }
- }
- }
- } catch (Exception e) {
- Log.e(TAG, "Got exception sending data to wear: " + e.toString());
- }
- return null;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
similarity index 97%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
index 3678617c96..b3b0c091d5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/APSResult.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Loop;
+package info.nightscout.androidaps.plugins.aps.loop;
import android.text.Html;
import android.text.Spanned;
@@ -22,11 +22,11 @@ import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DecimalFormatter;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.SP;
/**
* Created by mike on 09.06.2016.
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java
similarity index 99%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java
index 2c2bb1a2ee..69afe3d8e7 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/DeviceStatus.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Loop;
+package info.nightscout.androidaps.plugins.aps.loop;
import org.json.JSONException;
import org.json.JSONObject;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt
new file mode 100644
index 0000000000..b7549fcfed
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt
@@ -0,0 +1,109 @@
+package info.nightscout.androidaps.plugins.aps.loop
+
+
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.interfaces.Constraint
+import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui
+import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.utils.*
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.loop_fragment.*
+
+class LoopFragment : Fragment() {
+
+ private var disposable: CompositeDisposable = CompositeDisposable()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.loop_fragment, container, false)
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+
+ loop_run.setOnClickListener {
+ loop_lastrun.text = MainApp.gs(R.string.executing)
+ Thread { LoopPlugin.getPlugin().invoke("Loop button", true) }.start()
+ }
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+ disposable += RxBus
+ .toObservable(EventLoopUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+
+ disposable += RxBus
+ .toObservable(EventLoopSetLastRunGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ clearGUI()
+ loop_lastrun.text = it.text
+ }, {
+ FabricPrivacy.logException(it)
+ })
+
+ updateGUI()
+ SP.putBoolean(R.string.key_objectiveuseloop, true)
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ @Synchronized
+ fun updateGUI() {
+ if (loop_request == null) return
+ LoopPlugin.lastRun?.let {
+ loop_request.text = it.request?.toSpanned() ?: ""
+ loop_constraintsprocessed.text = it.constraintsProcessed?.toSpanned() ?: ""
+ loop_source.text = it.source ?: ""
+ loop_lastrun.text = it.lastAPSRun?.let { lastRun -> DateUtil.dateAndTimeString(lastRun.time) }
+ ?: ""
+ loop_lastenact.text = it.lastAPSRun?.let { lastEnact -> DateUtil.dateAndTimeString(lastEnact.time) }
+ ?: ""
+ loop_tbrsetbypump.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml()) }
+ ?: ""
+ loop_smbsetbypump.text = it.smbSetByPump?.let { smbSetByPump -> HtmlHelper.fromHtml(smbSetByPump.toHtml()) }
+ ?: ""
+
+ val constraints =
+ it.constraintsProcessed?.let { constraintsProcessed ->
+ val allConstraints = Constraint(0.0)
+ constraintsProcessed.rateConstraint?.let { rateConstraint -> allConstraints.copyReasons(rateConstraint) }
+ constraintsProcessed.smbConstraint?.let { smbConstraint -> allConstraints.copyReasons(smbConstraint) }
+ allConstraints.mostLimitedReasons
+ } ?: ""
+ loop_constraints.text = constraints
+ }
+ }
+
+ @Synchronized
+ private fun clearGUI() {
+ if (loop_request == null) return
+ loop_request.text = ""
+ loop_constraints.text = ""
+ loop_constraintsprocessed.text = ""
+ loop_source.text = ""
+ loop_lastrun.text = ""
+ loop_lastenact.text = ""
+ loop_tbrsetbypump.text = ""
+ loop_smbsetbypump.text = ""
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java
similarity index 79%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java
index 0b20ddf582..f339bd3771 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/LoopPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Loop;
+package info.nightscout.androidaps.plugins.aps.loop;
import android.annotation.SuppressLint;
import android.app.Notification;
@@ -10,11 +10,9 @@ import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.SystemClock;
-import android.support.annotation.NonNull;
-import android.support.v4.app.NotificationCompat;
-import com.crashlytics.android.answers.CustomEvent;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
+import androidx.core.app.NotificationCompat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -33,7 +31,9 @@ import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
+import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
import info.nightscout.androidaps.events.EventNewBG;
+import info.nightscout.androidaps.events.EventTempTargetChange;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginBase;
@@ -43,30 +43,33 @@ import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConstraintsObjectives.ObjectivesPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
-import info.nightscout.androidaps.plugins.Loop.events.EventLoopSetLastRunGui;
-import info.nightscout.androidaps.plugins.Loop.events.EventLoopUpdateGui;
-import info.nightscout.androidaps.plugins.Loop.events.EventNewOpenLoopNotification;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.PumpVirtual.VirtualPumpPlugin;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.plugins.Wear.ActionStringHandler;
-import info.nightscout.androidaps.events.EventAcceptOpenLoopChange;
+import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopSetLastRunGui;
+import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
+import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
+import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
+import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
-import info.nightscout.utils.FabricPrivacy;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.T;
-import info.nightscout.utils.ToastUtils;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.utils.T;
+import info.nightscout.androidaps.utils.ToastUtils;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 05.08.2016.
*/
public class LoopPlugin extends PluginBase {
private static Logger log = LoggerFactory.getLogger(L.APS);
+ private CompositeDisposable disposable = new CompositeDisposable();
private static final String CHANNEL_ID = "AndroidAPS-Openloop";
@@ -115,9 +118,39 @@ public class LoopPlugin extends PluginBase {
@Override
protected void onStart() {
- MainApp.bus().register(this);
createNotificationChannel();
super.onStart();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempTargetChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ invoke("EventTempTargetChange", true);
+ }, FabricPrivacy::logException)
+ );
+ /**
+ * This method is triggered once autosens calculation has completed, so the LoopPlugin
+ * has current data to work with. However, autosens calculation can be triggered by multiple
+ * sources and currently only a new BG should trigger a loop run. Hence we return early if
+ * the event causing the calculation is not EventNewBg.
+ *
+ */
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ // Autosens calculation not triggered by a new BG
+ if (!(event.getCause() instanceof EventNewBG)) return;
+
+ BgReading bgReading = DatabaseHelper.actualBg();
+ // BG outdated
+ if (bgReading == null) return;
+ // already looped with that value
+ if (bgReading.date <= lastBgTriggeredRun) return;
+
+ lastBgTriggeredRun = bgReading.date;
+ invoke("AutosenseCalculation for " + bgReading, true);
+ }, FabricPrivacy::logException)
+ );
}
private void createNotificationChannel() {
@@ -134,8 +167,8 @@ public class LoopPlugin extends PluginBase {
@Override
protected void onStop() {
+ disposable.clear();
super.onStop();
- MainApp.bus().unregister(this);
}
@Override
@@ -144,33 +177,6 @@ public class LoopPlugin extends PluginBase {
return pump == null || pump.getPumpDescription().isTempBasalCapable;
}
- /**
- * This method is triggered once autosens calculation has completed, so the LoopPlugin
- * has current data to work with. However, autosens calculation can be triggered by multiple
- * sources and currently only a new BG should trigger a loop run. Hence we return early if
- * the event causing the calculation is not EventNewBg.
- *
- */
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- if (!(ev.cause instanceof EventNewBG)) {
- // Autosens calculation not triggered by a new BG
- return;
- }
- BgReading bgReading = DatabaseHelper.actualBg();
- if (bgReading == null) {
- // BG outdated
- return;
- }
- if (bgReading.date <= lastBgTriggeredRun) {
- // already looped with that value
- return;
- }
-
- lastBgTriggeredRun = bgReading.date;
- invoke("AutosenseCalculation for " + bgReading, true);
- }
-
public long suspendedTo() {
return loopSuspendedTill;
}
@@ -272,7 +278,7 @@ public class LoopPlugin extends PluginBase {
String message = MainApp.gs(R.string.loopdisabled) + "\n" + loopEnabled.getReasons();
if (L.isEnabled(L.APS))
log.debug(message);
- MainApp.bus().post(new EventLoopSetLastRunGui(message));
+ RxBus.INSTANCE.send(new EventLoopSetLastRunGui(message));
return;
}
final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
@@ -283,10 +289,10 @@ public class LoopPlugin extends PluginBase {
Profile profile = ProfileFunctions.getInstance().getProfile();
- if (!ProfileFunctions.getInstance().isProfileValid("Loop")) {
+ if (profile == null || !ProfileFunctions.getInstance().isProfileValid("Loop")) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
- MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
+ RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noprofileselected)));
return;
}
@@ -301,7 +307,7 @@ public class LoopPlugin extends PluginBase {
// Check if we have any result
if (result == null) {
- MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
+ RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.noapsselected)));
return;
}
@@ -343,14 +349,14 @@ public class LoopPlugin extends PluginBase {
if (isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.loopsuspended));
- MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
+ RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.loopsuspended)));
return;
}
if (pump.isSuspended()) {
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.pumpsuspended));
- MainApp.bus().post(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
+ RxBus.INSTANCE.send(new EventLoopSetLastRunGui(MainApp.gs(R.string.pumpsuspended)));
return;
}
@@ -366,8 +372,8 @@ public class LoopPlugin extends PluginBase {
lastRun.tbrSetByPump = waiting;
if (resultAfterConstraints.bolusRequested)
lastRun.smbSetByPump = waiting;
- MainApp.bus().post(new EventLoopUpdateGui());
- FabricPrivacy.getInstance().logCustom(new CustomEvent("APSRequest"));
+ RxBus.INSTANCE.send(new EventLoopUpdateGui());
+ FabricPrivacy.getInstance().logCustom("APSRequest");
applyTBRRequest(resultAfterConstraints, profile, new Callback() {
@Override
public void run() {
@@ -386,13 +392,12 @@ public class LoopPlugin extends PluginBase {
SystemClock.sleep(1000);
LoopPlugin.getPlugin().invoke("tempBasalFallback", allowNotification, true);
}).start();
- FabricPrivacy.getInstance().logCustom(new CustomEvent("Loop_Run_TempBasalFallback"));
}
- MainApp.bus().post(new EventLoopUpdateGui());
+ RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
}
- MainApp.bus().post(new EventLoopUpdateGui());
+ RxBus.INSTANCE.send(new EventLoopUpdateGui());
}
});
} else {
@@ -409,7 +414,7 @@ public class LoopPlugin extends PluginBase {
.setAutoCancel(true)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_ALARM)
- .setVisibility(Notification.VISIBILITY_PUBLIC);
+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
if (SP.getBoolean("wearcontrol", false)) {
builder.setLocalOnly(true);
}
@@ -433,7 +438,7 @@ public class LoopPlugin extends PluginBase {
(NotificationManager) MainApp.instance().getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(Constants.notificationID, builder.build());
- MainApp.bus().post(new EventNewOpenLoopNotification());
+ RxBus.INSTANCE.send(new EventNewOpenLoopNotification());
// Send to Wear
ActionStringHandler.handleInitiate("changeRequest");
@@ -446,7 +451,7 @@ public class LoopPlugin extends PluginBase {
}
}
- MainApp.bus().post(new EventLoopUpdateGui());
+ RxBus.INSTANCE.send(new EventLoopUpdateGui());
} finally {
if (L.isEnabled(L.APS))
log.debug("invoke end");
@@ -464,16 +469,12 @@ public class LoopPlugin extends PluginBase {
lastRun.lastEnact = new Date();
lastRun.lastOpenModeAccept = new Date();
NSUpload.uploadDeviceStatus();
- ObjectivesPlugin objectivesPlugin = MainApp.getSpecificPlugin(ObjectivesPlugin.class);
- if (objectivesPlugin != null) {
- ObjectivesPlugin.getPlugin().manualEnacts++;
- ObjectivesPlugin.getPlugin().saveProgress();
- }
+ SP.incInt(R.string.key_ObjectivesmanualEnacts);
}
- MainApp.bus().post(new EventAcceptOpenLoopChange());
+ RxBus.INSTANCE.send(new EventAcceptOpenLoopChange());
}
});
- FabricPrivacy.getInstance().logCustom(new CustomEvent("AcceptTemp"));
+ FabricPrivacy.getInstance().logCustom("AcceptTemp");
}
/**
@@ -639,20 +640,48 @@ public class LoopPlugin extends PluginBase {
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
LoopPlugin.getPlugin().disconnectTo(System.currentTimeMillis() + durationInMinutes * 60 * 1000L);
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
- @Override
- public void run() {
- if (!result.success) {
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
+
+ if (pump.getPumpDescription().tempBasalStyle == PumpDescription.ABSOLUTE) {
+ ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(0, durationInMinutes, true, profile, new Callback() {
+ @Override
+ public void run() {
+ if (!result.success) {
+ Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ i.putExtra("soundid", R.raw.boluserror);
+ i.putExtra("status", result.comment);
+ i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ MainApp.instance().startActivity(i);
+ }
}
- }
- });
+ });
+ } else {
+ ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(0, durationInMinutes, true, profile, new Callback() {
+ @Override
+ public void run() {
+ if (!result.success) {
+ Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ i.putExtra("soundid", R.raw.boluserror);
+ i.putExtra("status", result.comment);
+ i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ MainApp.instance().startActivity(i);
+ }
+ }
+ });
+ }
+
if (pump.getPumpDescription().isExtendedBolusCapable && activeTreatments.isInHistoryExtendedBoluslInProgress()) {
ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() {
@Override
public void run() {
if (!result.success) {
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.extendedbolusdeliveryerror));
+ Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ i.putExtra("soundid", R.raw.boluserror);
+ i.putExtra("status", result.comment);
+ i.putExtra("title", MainApp.gs(R.string.extendedbolusdeliveryerror));
+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ MainApp.instance().startActivity(i);
}
}
});
@@ -666,7 +695,12 @@ public class LoopPlugin extends PluginBase {
@Override
public void run() {
if (!result.success) {
- ToastUtils.showToastInUiThread(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.tempbasaldeliveryerror));
+ Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class);
+ i.putExtra("soundid", R.raw.boluserror);
+ i.putExtra("status", result.comment);
+ i.putExtra("title", MainApp.gs(R.string.tempbasaldeliveryerror));
+ i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ MainApp.instance().startActivity(i);
}
}
});
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/ScriptReader.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/ScriptReader.java
similarity index 94%
rename from app/src/main/java/info/nightscout/androidaps/plugins/Loop/ScriptReader.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/ScriptReader.java
index 988d08fb84..e3a64dbece 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/Loop/ScriptReader.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/ScriptReader.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.Loop;
+package info.nightscout.androidaps.plugins.aps.loop;
import android.content.Context;
import android.content.res.AssetManager;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopSetLastRunGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopSetLastRunGui.kt
new file mode 100644
index 0000000000..19c7e92c5c
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopSetLastRunGui.kt
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.plugins.aps.loop.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+/**
+ * Created by mike on 05.08.2016.
+ */
+class EventLoopSetLastRunGui(val text: String) : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopUpdateGui.kt
new file mode 100644
index 0000000000..89507d85f8
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventLoopUpdateGui.kt
@@ -0,0 +1,8 @@
+package info.nightscout.androidaps.plugins.aps.loop.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+/**
+ * Created by mike on 05.08.2016.
+ */
+class EventLoopUpdateGui : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt
new file mode 100644
index 0000000000..2933318dd6
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.aps.loop.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventNewOpenLoopNotification : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
similarity index 94%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
index 50e79d1e37..703dc4255b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalAdapterAMAJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
+package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONArray;
import org.json.JSONException;
@@ -16,22 +16,25 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
+import java.nio.charset.StandardCharsets;
+
+import javax.annotation.Nullable;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback;
-import info.nightscout.androidaps.plugins.OpenAPSSMB.SMBDefaults;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
+import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.SP;
public class DetermineBasalAdapterAMAJS {
private static Logger log = LoggerFactory.getLogger(L.APS);
@@ -59,6 +62,7 @@ public class DetermineBasalAdapterAMAJS {
mScriptReader = scriptReader;
}
+ @Nullable
public DetermineBasalResultAMA invoke() {
if (L.isEnabled(L.APS)) {
@@ -277,7 +281,7 @@ public class DetermineBasalAdapterAMAJS {
private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename);
- String string = new String(bytes, "UTF-8");
+ String string = new String(bytes, StandardCharsets.UTF_8);
if (string.startsWith("#!/usr/bin/env node")) {
string = string.substring(20);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
similarity index 92%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
index 77c8d8a860..46f1057e27 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/DetermineBasalResultAMA.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalResultAMA.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
+package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException;
import org.json.JSONObject;
@@ -7,8 +7,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.utils.DateUtil;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
+import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultAMA extends APSResult {
private static Logger log = LoggerFactory.getLogger(L.APS);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
new file mode 100644
index 0000000000..94747a4597
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt
@@ -0,0 +1,115 @@
+package info.nightscout.androidaps.plugins.aps.openAPSAMA
+
+import android.os.Bundle
+import android.text.TextUtils
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.FabricPrivacy
+import info.nightscout.androidaps.utils.JSONFormatter
+import info.nightscout.androidaps.utils.plusAssign
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.openapsama_fragment.*
+import org.json.JSONArray
+import org.json.JSONException
+import org.slf4j.LoggerFactory
+
+class OpenAPSAMAFragment : Fragment() {
+ private val log = LoggerFactory.getLogger(L.APS)
+ private var disposable: CompositeDisposable = CompositeDisposable()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.openapsama_fragment, container, false)
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+
+ openapsma_run.setOnClickListener {
+ OpenAPSAMAPlugin.getPlugin().invoke("OpenAPSAMA button", false)
+ }
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateResultGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateResultGUI(it.text)
+ }, {
+ FabricPrivacy.logException(it)
+ })
+
+ updateGUI()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ @Synchronized
+ private fun updateGUI() {
+ if (openapsma_result == null) return
+ OpenAPSAMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult ->
+ openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
+ openapsma_request.text = lastAPSResult.toSpanned()
+ }
+ OpenAPSAMAPlugin.getPlugin().lastDetermineBasalAdapterAMAJS?.let { determineBasalAdapterAMAJS ->
+ openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterAMAJS.glucoseStatusParam)
+ openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterAMAJS.currentTempParam)
+ try {
+ val iobArray = JSONArray(determineBasalAdapterAMAJS.iobDataParam)
+ openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
+ } catch (e: JSONException) {
+ log.error("Unhandled exception", e)
+ openapsma_iobdata.text = "JSONException see log for details"
+ }
+
+ openapsma_profile.text = JSONFormatter.format(determineBasalAdapterAMAJS.profileParam)
+ openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterAMAJS.mealDataParam)
+ openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug
+ }
+ if (OpenAPSAMAPlugin.getPlugin().lastAPSRun != 0L) {
+ openapsma_lastrun.text = DateUtil.dateAndTimeFullString(OpenAPSAMAPlugin.getPlugin().lastAPSRun)
+ }
+ OpenAPSAMAPlugin.getPlugin().lastAutosensResult?.let {
+ openapsma_autosensdata.text = JSONFormatter.format(it.json())
+ }
+ }
+
+ private fun updateResultGUI(text: String) {
+ openapsma_result.text = text
+ openapsma_glucosestatus.text = ""
+ openapsma_currenttemp.text = ""
+ openapsma_iobdata.text = ""
+ openapsma_profile.text = ""
+ openapsma_mealdata.text = ""
+ openapsma_autosensdata.text = ""
+ openapsma_scriptdebugdata.text = ""
+ openapsma_request.text = ""
+ openapsma_lastrun.text = ""
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
similarity index 74%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
index 3bf1301416..ef31ad599e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSAMA/OpenAPSAMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSAMA;
+package info.nightscout.androidaps.plugins.aps.openAPSAMA;
import org.json.JSONException;
import org.slf4j.Logger;
@@ -6,32 +6,33 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
-import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.HardLimits;
-import info.nightscout.utils.Profiler;
-import info.nightscout.utils.Round;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.HardLimits;
+import info.nightscout.androidaps.utils.Profiler;
+import info.nightscout.androidaps.utils.Round;
/**
* Created by mike on 05.08.2016.
@@ -100,21 +101,21 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return;
@@ -172,7 +173,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@@ -193,7 +194,8 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
isTempTarget
);
} catch (JSONException e) {
- log.error("Unable to set data: " + e.toString());
+ FabricPrivacy.logException(e);
+ return;
}
@@ -201,23 +203,31 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
if (L.isEnabled(L.APS))
Profiler.log(log, "AMA calculation", start);
// Fix bug determine basal
- if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
- determineBasalResultAMA.tempBasalRequested = false;
+ if (determineBasalResultAMA == null) {
+ if (L.isEnabled(L.APS))
+ log.error("SMB calculation returned null");
+ lastDetermineBasalAdapterAMAJS = null;
+ lastAPSResult = null;
+ lastAPSRun = 0;
+ } else {
+ if (determineBasalResultAMA.rate == 0d && determineBasalResultAMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
+ determineBasalResultAMA.tempBasalRequested = false;
- determineBasalResultAMA.iob = iobArray[0];
+ determineBasalResultAMA.iob = iobArray[0];
- long now = System.currentTimeMillis();
+ long now = System.currentTimeMillis();
- try {
- determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
+ try {
+ determineBasalResultAMA.json.put("timestamp", DateUtil.toISOString(now));
+ } catch (JSONException e) {
+ log.error("Unhandled exception", e);
+ }
+
+ lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS;
+ lastAPSResult = determineBasalResultAMA;
+ lastAPSRun = now;
}
-
- lastDetermineBasalAdapterAMAJS = determineBasalAdapterAMAJS;
- lastAPSResult = determineBasalResultAMA;
- lastAPSRun = now;
- MainApp.bus().post(new EventOpenAPSUpdateGui());
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java
similarity index 94%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java
index 1574665dc4..1ded34b7cb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalAdapterMAJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalAdapterMAJS.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA;
+package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException;
import org.json.JSONObject;
@@ -14,18 +14,21 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
+import java.nio.charset.StandardCharsets;
+
+import javax.annotation.Nullable;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.SP;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.SP;
public class DetermineBasalAdapterMAJS {
private static Logger log = LoggerFactory.getLogger(L.APS);
@@ -47,6 +50,7 @@ public class DetermineBasalAdapterMAJS {
mScriptReader = scriptReader;
}
+ @Nullable
public DetermineBasalResultMA invoke() {
DetermineBasalResultMA determineBasalResultMA = null;
@@ -207,7 +211,7 @@ public class DetermineBasalAdapterMAJS {
private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename);
- String string = new String(bytes, "UTF-8");
+ String string = new String(bytes, StandardCharsets.UTF_8);
if (string.startsWith("#!/usr/bin/env node")) {
string = string.substring(20);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java
similarity index 94%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java
index d3e1869f87..bbbcf7f893 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/DetermineBasalResultMA.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/DetermineBasalResultMA.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA;
+package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException;
import org.json.JSONObject;
@@ -7,7 +7,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
public class DetermineBasalResultMA extends APSResult {
private static Logger log = LoggerFactory.getLogger(L.APS);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java
similarity index 87%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java
index 8907166951..a2596d9174 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/LoggerCallback.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/LoggerCallback.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA;
+package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.mozilla.javascript.ScriptableObject;
import org.slf4j.Logger;
@@ -36,16 +36,14 @@ public class LoggerCallback extends ScriptableObject {
public void jsFunction_log(Object obj1) {
if (L.isEnabled(L.APS))
- log.debug(obj1.toString());
+ log.debug(obj1.toString().trim());
logBuffer.append(obj1.toString());
- logBuffer.append(' ');
}
public void jsFunction_error(Object obj1) {
if (L.isEnabled(L.APS))
- log.error(obj1.toString());
+ log.error(obj1.toString().trim());
errorBuffer.append(obj1.toString());
- errorBuffer.append(' ');
}
@@ -60,4 +58,4 @@ public class LoggerCallback extends ScriptableObject {
}
return ret;
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt
new file mode 100644
index 0000000000..1b72f57365
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAFragment.kt
@@ -0,0 +1,100 @@
+package info.nightscout.androidaps.plugins.aps.openAPSMA
+
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.FabricPrivacy
+import info.nightscout.androidaps.utils.JSONFormatter
+import info.nightscout.androidaps.utils.plusAssign
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.openapsama_fragment.*
+import org.slf4j.LoggerFactory
+
+class OpenAPSMAFragment : Fragment() {
+ private val log = LoggerFactory.getLogger(L.APS)
+ private var disposable: CompositeDisposable = CompositeDisposable()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.openapsma_fragment, container, false)
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+
+ openapsma_run.setOnClickListener {
+ OpenAPSMAPlugin.getPlugin().invoke("OpenAPSMA button", false)
+ }
+
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateResultGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateResultGUI(it.text)
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ updateGUI()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ @Synchronized
+ private fun updateGUI() {
+ if (openapsma_result == null) return
+ OpenAPSMAPlugin.getPlugin().lastAPSResult?.let { lastAPSResult ->
+ openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
+ openapsma_request.text = lastAPSResult.toSpanned()
+ }
+ OpenAPSMAPlugin.getPlugin().lastDetermineBasalAdapterMAJS?.let { determineBasalAdapterMAJS ->
+ openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterMAJS.glucoseStatusParam)
+ openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterMAJS.currentTempParam)
+ openapsma_iobdata.text = JSONFormatter.format(determineBasalAdapterMAJS.iobDataParam)
+ openapsma_profile.text = JSONFormatter.format(determineBasalAdapterMAJS.profileParam)
+ openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterMAJS.mealDataParam)
+ }
+ if (OpenAPSMAPlugin.getPlugin().lastAPSRun != 0L) {
+ openapsma_lastrun.text = DateUtil.dateAndTimeString(OpenAPSMAPlugin.getPlugin().lastAPSRun)
+ }
+ }
+
+ @Synchronized
+ private fun updateResultGUI(text: String) {
+ if (openapsma_result == null) return
+ openapsma_result.text = text
+ openapsma_glucosestatus.text = ""
+ openapsma_currenttemp.text = ""
+ openapsma_iobdata.text = ""
+ openapsma_profile.text = ""
+ openapsma_mealdata.text = ""
+ openapsma_request.text = ""
+ openapsma_lastrun.text = ""
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
similarity index 73%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
index 5b59252ea1..899c0151d8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSMA/OpenAPSMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSMA;
+package info.nightscout.androidaps.plugins.aps.openAPSMA;
import org.json.JSONException;
import org.slf4j.Logger;
@@ -6,32 +6,33 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.HardLimits;
-import info.nightscout.utils.Profiler;
-import info.nightscout.utils.Round;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.HardLimits;
+import info.nightscout.androidaps.utils.Profiler;
+import info.nightscout.androidaps.utils.Round;
-import static info.nightscout.utils.HardLimits.checkOnlyHardLimits;
-import static info.nightscout.utils.HardLimits.verifyHardLimits;
+import static info.nightscout.androidaps.utils.HardLimits.checkOnlyHardLimits;
+import static info.nightscout.androidaps.utils.HardLimits.verifyHardLimits;
/**
* Created by mike on 05.08.2016.
@@ -99,21 +100,21 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return;
@@ -170,7 +171,8 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
try {
determineBasalAdapterMAJS.setData(profile, maxIob, maxBasal, minBg, maxBg, targetBg, ConfigBuilderPlugin.getPlugin().getActivePump().getBaseBasalRate(), iobTotal, glucoseStatus, mealData);
} catch (JSONException e) {
- log.error("Unhandled exception", e);
+ FabricPrivacy.logException(e);
+ return;
}
if (L.isEnabled(L.APS))
Profiler.log(log, "MA calculation", start);
@@ -179,22 +181,30 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
long now = System.currentTimeMillis();
DetermineBasalResultMA determineBasalResultMA = determineBasalAdapterMAJS.invoke();
- // Fix bug determinef basal
- if (determineBasalResultMA.rate == 0d && determineBasalResultMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
- determineBasalResultMA.tempBasalRequested = false;
+ if (determineBasalResultMA == null) {
+ if (L.isEnabled(L.APS))
+ log.error("MA calculation returned null");
+ lastDetermineBasalAdapterMAJS = null;
+ lastAPSResult = null;
+ lastAPSRun = 0;
+ } else {
+ // Fix bug determinef basal
+ if (determineBasalResultMA.rate == 0d && determineBasalResultMA.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
+ determineBasalResultMA.tempBasalRequested = false;
- determineBasalResultMA.iob = iobTotal;
+ determineBasalResultMA.iob = iobTotal;
- try {
- determineBasalResultMA.json.put("timestamp", DateUtil.toISOString(now));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
+ try {
+ determineBasalResultMA.json.put("timestamp", DateUtil.toISOString(now));
+ } catch (JSONException e) {
+ log.error("Unhandled exception", e);
+ }
+
+ lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS;
+ lastAPSResult = determineBasalResultMA;
+ lastAPSRun = now;
}
-
- lastDetermineBasalAdapterMAJS = determineBasalAdapterMAJS;
- lastAPSResult = determineBasalResultMA;
- lastAPSRun = now;
- MainApp.bus().post(new EventOpenAPSUpdateGui());
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateGui.kt
new file mode 100644
index 0000000000..2b642c6880
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateGui.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.aps.openAPSMA.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventOpenAPSUpdateGui : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateResultGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateResultGui.kt
new file mode 100644
index 0000000000..4ba02b8755
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/events/EventOpenAPSUpdateResultGui.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.aps.openAPSMA.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventOpenAPSUpdateResultGui(val text: String) : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
similarity index 87%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
index bdd06372d9..b7b6d82e5e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalAdapterSMBJS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSSMB;
+package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONArray;
import org.json.JSONException;
@@ -16,22 +16,25 @@ import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
+import java.nio.charset.StandardCharsets;
+
+import javax.annotation.Nullable;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.OpenAPSMA.LoggerCallback;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.SP;
-import info.nightscout.utils.SafeParse;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.LoggerCallback;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.SP;
+import info.nightscout.androidaps.utils.SafeParse;
public class DetermineBasalAdapterSMBJS {
private static Logger log = LoggerFactory.getLogger(L.APS);
@@ -68,6 +71,7 @@ public class DetermineBasalAdapterSMBJS {
}
+ @Nullable
public DetermineBasalResultSMB invoke() {
@@ -232,8 +236,13 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("max_daily_safety_multiplier", SP.getInt(R.string.key_openapsama_max_daily_safety_multiplier, 3));
mProfile.put("current_basal_safety_multiplier", SP.getDouble(R.string.key_openapsama_current_basal_safety_multiplier, 4d));
- mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity));
- mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity));
+ // TODO AS-FIX
+ // mProfile.put("high_temptarget_raises_sensitivity", SP.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity));
+ mProfile.put("high_temptarget_raises_sensitivity", false);
+ //mProfile.put("low_temptarget_lowers_sensitivity", SP.getBoolean(R.string.key_low_temptarget_lowers_sensitivity, SMBDefaults.low_temptarget_lowers_sensitivity));
+ mProfile.put("low_temptarget_lowers_sensitivity", false);
+
+
mProfile.put("sensitivity_raises_target", SMBDefaults.sensitivity_raises_target);
mProfile.put("resistance_lowers_target", SMBDefaults.resistance_lowers_target);
mProfile.put("adv_target_adjustments", SMBDefaults.adv_target_adjustments);
@@ -250,12 +259,14 @@ public class DetermineBasalAdapterSMBJS {
mProfile.put("remainingCarbsCap", SMBDefaults.remainingCarbsCap);
mProfile.put("enableUAM", uamAllowed);
mProfile.put("A52_risk_enable", SMBDefaults.A52_risk_enable);
- mProfile.put("enableSMB_with_COB", SP.getBoolean(R.string.key_enableSMB_with_COB, false));
- mProfile.put("enableSMB_with_temptarget", SP.getBoolean(R.string.key_enableSMB_with_temptarget, false));
- mProfile.put("allowSMB_with_high_temptarget", SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
- mProfile.put("enableSMB_always", SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
- mProfile.put("enableSMB_after_carbs", SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
- mProfile.put("maxSMBBasalMinutes", SP.getInt("key_smbmaxminutes", SMBDefaults.maxSMBBasalMinutes));
+
+ boolean smbEnabled = SP.getBoolean(MainApp.gs(R.string.key_use_smb), false);
+ mProfile.put("enableSMB_with_COB", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_COB, false));
+ mProfile.put("enableSMB_with_temptarget", smbEnabled && SP.getBoolean(R.string.key_enableSMB_with_temptarget, false));
+ mProfile.put("allowSMB_with_high_temptarget", smbEnabled && SP.getBoolean(R.string.key_allowSMB_with_high_temptarget, false));
+ mProfile.put("enableSMB_always", smbEnabled && SP.getBoolean(R.string.key_enableSMB_always, false) && advancedFiltering);
+ mProfile.put("enableSMB_after_carbs", smbEnabled && SP.getBoolean(R.string.key_enableSMB_after_carbs, false) && advancedFiltering);
+ mProfile.put("maxSMBBasalMinutes", SP.getInt(R.string.key_smbmaxminutes, SMBDefaults.maxSMBBasalMinutes));
mProfile.put("carbsReqThreshold", SMBDefaults.carbsReqThreshold);
mProfile.put("current_basal", basalrate);
@@ -333,7 +344,7 @@ public class DetermineBasalAdapterSMBJS {
private String readFile(String filename) throws IOException {
byte[] bytes = mScriptReader.readFile(filename);
- String string = new String(bytes, "UTF-8");
+ String string = new String(bytes, StandardCharsets.UTF_8);
if (string.startsWith("#!/usr/bin/env node")) {
string = string.substring(20);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
similarity index 93%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
index 364731bea5..9d0bd22557 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/DetermineBasalResultSMB.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSSMB;
+package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException;
import org.json.JSONObject;
@@ -6,8 +6,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.utils.DateUtil;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
+import info.nightscout.androidaps.utils.DateUtil;
public class DetermineBasalResultSMB extends APSResult {
private static final Logger log = LoggerFactory.getLogger(L.APS);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt
new file mode 100644
index 0000000000..06ad0d01fd
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt
@@ -0,0 +1,122 @@
+package info.nightscout.androidaps.plugins.aps.openAPSSMB
+
+import android.annotation.SuppressLint
+import android.os.Bundle
+import android.text.TextUtils
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.FabricPrivacy
+import info.nightscout.androidaps.utils.JSONFormatter
+import info.nightscout.androidaps.utils.plusAssign
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.openapsama_fragment.*
+import org.json.JSONArray
+import org.json.JSONException
+import org.slf4j.LoggerFactory
+
+class OpenAPSSMBFragment : Fragment() {
+ private val log = LoggerFactory.getLogger(L.APS)
+ private var disposable: CompositeDisposable = CompositeDisposable()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.openapsama_fragment, container, false)
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+
+ openapsma_run.setOnClickListener {
+ OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false)
+ }
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGUI()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventOpenAPSUpdateResultGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateResultGUI(it.text)
+ }, {
+ FabricPrivacy.logException(it)
+ })
+
+ updateGUI()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ @Synchronized
+ fun updateGUI() {
+ if (openapsma_result == null) return
+ val plugin = OpenAPSSMBPlugin.getPlugin()
+ plugin.lastAPSResult?.let { lastAPSResult ->
+ openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
+ openapsma_request.text = lastAPSResult.toSpanned()
+ }
+ plugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS ->
+ openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam)
+ openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
+ try {
+ val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam)
+ openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
+ } catch (e: JSONException) {
+ log.error("Unhandled exception", e)
+ @SuppressLint("SetTextl18n")
+ openapsma_iobdata.text = "JSONException see log for details"
+ }
+
+ openapsma_profile.text = JSONFormatter.format(determineBasalAdapterSMBJS.profileParam)
+ openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam)
+ openapsma_scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug
+ plugin.lastAPSResult?.inputConstraints?.let {
+ openapsma_constraints.text = it.reasons
+ }
+ }
+ if (plugin.lastAPSRun != 0L) {
+ openapsma_lastrun.text = DateUtil.dateAndTimeFullString(plugin.lastAPSRun)
+ }
+ plugin.lastAutosensResult?.let {
+ openapsma_autosensdata.text = JSONFormatter.format(it.json())
+ }
+ }
+
+ @Synchronized
+ private fun updateResultGUI(text: String) {
+ if (openapsma_result == null) return
+ openapsma_result.text = text
+ openapsma_glucosestatus.text = ""
+ openapsma_currenttemp.text = ""
+ openapsma_iobdata.text = ""
+ openapsma_profile.text = ""
+ openapsma_mealdata.text = ""
+ openapsma_autosensdata.text = ""
+ openapsma_scriptdebugdata.text = ""
+ openapsma_request.text = ""
+ openapsma_lastrun.text = ""
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
similarity index 73%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
index 1d6b558c74..d410eba291 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/OpenAPSSMBPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
@@ -1,47 +1,47 @@
-package info.nightscout.androidaps.plugins.OpenAPSSMB;
+package info.nightscout.androidaps.plugins.aps.openAPSSMB;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import java.util.Date;
-
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.GlucoseStatus;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.MealData;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.interfaces.APSInterface;
import info.nightscout.androidaps.interfaces.Constraint;
+import info.nightscout.androidaps.interfaces.ConstraintsInterface;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.ConfigBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensData;
-import info.nightscout.androidaps.plugins.IobCobCalculator.AutosensResult;
-import info.nightscout.androidaps.plugins.IobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.Loop.APSResult;
-import info.nightscout.androidaps.plugins.Loop.ScriptReader;
-import info.nightscout.androidaps.plugins.NSClientInternal.NSUpload;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateGui;
-import info.nightscout.androidaps.plugins.OpenAPSMA.events.EventOpenAPSUpdateResultGui;
-import info.nightscout.androidaps.plugins.Treatments.TreatmentsPlugin;
-import info.nightscout.utils.DateUtil;
-import info.nightscout.utils.HardLimits;
-import info.nightscout.utils.Profiler;
-import info.nightscout.utils.Round;
-import info.nightscout.utils.ToastUtils;
+import info.nightscout.androidaps.plugins.aps.loop.APSResult;
+import info.nightscout.androidaps.plugins.aps.loop.ScriptReader;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
+import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.utils.HardLimits;
+import info.nightscout.androidaps.utils.Profiler;
+import info.nightscout.androidaps.utils.Round;
+import info.nightscout.androidaps.utils.ToastUtils;
/**
* Created by mike on 05.08.2016.
*/
-public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
+public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface {
private static Logger log = LoggerFactory.getLogger(L.APS);
private static OpenAPSSMBPlugin openAPSSMBPlugin;
@@ -105,21 +105,21 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.noprofileselected)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.noprofileselected));
return;
}
if (!isEnabled(PluginType.APS)) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_disabled)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_disabled));
return;
}
if (glucoseStatus == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openapsma_noglucosedata)));
if (L.isEnabled(L.APS))
log.debug(MainApp.gs(R.string.openapsma_noglucosedata));
return;
@@ -141,16 +141,14 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
long start = System.currentTimeMillis();
long startPart = System.currentTimeMillis();
- IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(profile);
- if (L.isEnabled(L.APS))
- Profiler.log(log, "calculateIobArrayInDia()", startPart);
- startPart = System.currentTimeMillis();
MealData mealData = TreatmentsPlugin.getPlugin().getMealData();
if (L.isEnabled(L.APS))
Profiler.log(log, "getMealData()", startPart);
- double maxIob = MainApp.getConstraintChecker().getMaxIOBAllowed().value();
+ Constraint maxIOBAllowedConstraint = MainApp.getConstraintChecker().getMaxIOBAllowed();
+ inputConstraints.copyReasons(maxIOBAllowedConstraint);
+ double maxIob = maxIOBAllowedConstraint.value();
minBg = verifyHardLimits(minBg, "minBg", HardLimits.VERY_HARD_LIMIT_MIN_BG[0], HardLimits.VERY_HARD_LIMIT_MIN_BG[1]);
maxBg = verifyHardLimits(maxBg, "maxBg", HardLimits.VERY_HARD_LIMIT_MAX_BG[0], HardLimits.VERY_HARD_LIMIT_MAX_BG[1]);
@@ -181,7 +179,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
if (MainApp.getConstraintChecker().isAutosensModeEnabled().value()) {
AutosensData autosensData = IobCobCalculatorPlugin.getPlugin().getLastAutosensDataSynchronized("OpenAPSPlugin");
if (autosensData == null) {
- MainApp.bus().post(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateResultGui(MainApp.gs(R.string.openaps_noasdata)));
return;
}
lastAutosensResult = autosensData.autosensResult;
@@ -190,6 +188,11 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
lastAutosensResult.sensResult = "autosens disabled";
}
+ IobTotal[] iobArray = IobCobCalculatorPlugin.getPlugin().calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget);
+ if (L.isEnabled(L.APS))
+ Profiler.log(log, "calculateIobArrayInDia()", startPart);
+
+ startPart = System.currentTimeMillis();
Constraint smbAllowed = new Constraint<>(!tempBasalFallback);
MainApp.getConstraintChecker().isSMBModeEnabled(smbAllowed);
inputConstraints.copyReasons(smbAllowed);
@@ -217,7 +220,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
advancedFiltering.value()
);
} catch (JSONException e) {
- log.error(e.getMessage());
+ FabricPrivacy.logException(e);
return;
}
@@ -226,25 +229,33 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke();
if (L.isEnabled(L.APS))
Profiler.log(log, "SMB calculation", start);
- // TODO still needed with oref1?
- // Fix bug determine basal
- if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
- determineBasalResultSMB.tempBasalRequested = false;
+ if (determineBasalResultSMB == null) {
+ if (L.isEnabled(L.APS))
+ log.error("SMB calculation returned null");
+ lastDetermineBasalAdapterSMBJS = null;
+ lastAPSResult = null;
+ lastAPSRun = 0;
+ } else {
+ // TODO still needed with oref1?
+ // Fix bug determine basal
+ if (determineBasalResultSMB.rate == 0d && determineBasalResultSMB.duration == 0 && !TreatmentsPlugin.getPlugin().isTempBasalInProgress())
+ determineBasalResultSMB.tempBasalRequested = false;
- determineBasalResultSMB.iob = iobArray[0];
+ determineBasalResultSMB.iob = iobArray[0];
- try {
- determineBasalResultSMB.json.put("timestamp", DateUtil.toISOString(now));
- } catch (JSONException e) {
- log.error("Unhandled exception", e);
+ try {
+ determineBasalResultSMB.json.put("timestamp", DateUtil.toISOString(now));
+ } catch (JSONException e) {
+ log.error("Unhandled exception", e);
+ }
+
+ determineBasalResultSMB.inputConstraints = inputConstraints;
+
+ lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS;
+ lastAPSResult = determineBasalResultSMB;
+ lastAPSRun = now;
}
-
- determineBasalResultSMB.inputConstraints = inputConstraints;
-
- lastDetermineBasalAdapterSMBJS = determineBasalAdapterSMBJS;
- lastAPSResult = determineBasalResultSMB;
- lastAPSRun = now;
- MainApp.bus().post(new EventOpenAPSUpdateGui());
+ RxBus.INSTANCE.send(new EventOpenAPSUpdateGui());
//deviceStatus.suggested = determineBasalResultAMA.json;
}
@@ -269,4 +280,9 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface {
return newvalue;
}
+ public Constraint isSuperBolusEnabled(Constraint value) {
+ value.set(false);
+ return value;
+ }
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
similarity index 98%
rename from app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
index 0ce8d2bb94..f6b8f20233 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/OpenAPSSMB/SMBDefaults.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/SMBDefaults.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.OpenAPSSMB;
+package info.nightscout.androidaps.plugins.aps.openAPSSMB;
/**
* Created by mike on 10.12.2017.
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt
new file mode 100644
index 0000000000..1774df1471
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt
@@ -0,0 +1,23 @@
+package info.nightscout.androidaps.plugins.bus
+
+import info.nightscout.androidaps.events.Event
+import io.reactivex.Observable
+import io.reactivex.schedulers.Schedulers
+import io.reactivex.subjects.PublishSubject
+
+// Use object so we have a singleton instance
+object RxBus {
+
+ private val publisher = PublishSubject.create()
+
+ fun send(event: Event) {
+ publisher.onNext(event)
+ }
+
+ // Listen should return an Observable and not the publisher
+ // Using ofType we filter only events that match that class type
+ fun toObservable(eventType: Class