diff --git a/app/build.gradle b/app/build.gradle index b43a768ed4..858fe354fc 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -109,7 +109,7 @@ android { targetSdkVersion 28 multiDexEnabled true versionCode 1500 - version "2.4-dev-f" + version "2.6-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' @@ -240,8 +240,6 @@ dependencies { implementation 'androidx.percentlayout:percentlayout:1.0.0' implementation "com.wdullaer:materialdatetimepicker:2.3.0" - // Otto bus will be replaced by rx - implementation "com.squareup:otto:1.3.7" implementation "io.reactivex.rxjava2:rxandroid:2.1.1" implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}" @@ -286,14 +284,13 @@ dependencies { testImplementation("com.google.truth:truth:0.39") { exclude group: "com.google.guava", module: "guava" } - testImplementation("org.robolectric:robolectric:4.2.1") { - exclude group: "com.google.guava", module: "guava" - } testImplementation "org.skyscreamer:jsonassert:1.5.0" testImplementation "org.hamcrest:hamcrest-all:1.3" +/* testImplementation("uk.org.lidalia:slf4j-test:1.2.0") { exclude group: "com.google.guava", module: "guava" } +*/ androidTestImplementation "org.mockito:mockito-core:2.8.47" androidTestImplementation "com.google.dexmaker:dexmaker:${dexmakerVersion}" 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 adb3be4dc0..21a89d8920 100644 --- a/app/src/main/java/info/nightscout/androidaps/Constants.java +++ b/app/src/main/java/info/nightscout/androidaps/Constants.java @@ -36,6 +36,8 @@ public class Constants { 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; diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java index 47cf8ba1ae..64c2656086 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.java @@ -6,7 +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.text.SpannableString; import android.text.method.LinkMovementMethod; import android.text.util.Linkify; @@ -21,6 +20,7 @@ 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; @@ -33,7 +33,6 @@ 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; @@ -45,16 +44,16 @@ 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.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.plugins.general.versionChecker.VersionCheckerUtilsKt; import info.nightscout.androidaps.setupwizard.SetupWizardActivity; import info.nightscout.androidaps.tabs.TabPageAdapter; import info.nightscout.androidaps.utils.AndroidPermission; @@ -63,11 +62,12 @@ 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 NoSplashAppCompatActivity { private static Logger log = LoggerFactory.getLogger(L.CORE); - - protected PowerManager.WakeLock mWakeLock; + private CompositeDisposable disposable = new CompositeDisposable(); private ActionBarDrawerToggle actionBarDrawerToggle; @@ -77,11 +77,8 @@ public class MainActivity extends NoSplashAppCompatActivity { 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)); @@ -95,14 +92,10 @@ public class MainActivity extends NoSplashAppCompatActivity { 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 @@ -124,6 +117,43 @@ public class MainActivity extends NoSplashAppCompatActivity { 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) { @@ -139,86 +169,29 @@ public class MainActivity extends NoSplashAppCompatActivity { 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, "AndroidAPS:MainActivity_onEventPreferenceChange"); - 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()) { @@ -237,8 +210,8 @@ public class MainActivity extends NoSplashAppCompatActivity { } 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); } @@ -264,15 +237,6 @@ public class MainActivity extends NoSplashAppCompatActivity { } } - 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); @@ -289,10 +253,10 @@ public class MainActivity extends NoSplashAppCompatActivity { // 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)); } @@ -308,19 +272,16 @@ public class MainActivity extends NoSplashAppCompatActivity { 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) { @@ -405,7 +366,7 @@ public class MainActivity extends NoSplashAppCompatActivity { 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 89696ad12f..55f4897652 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -6,16 +6,12 @@ import android.content.IntentFilter; import android.content.res.Resources; import android.os.SystemClock; -import androidx.annotation.Nullable; import androidx.annotation.PluralsRes; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.crashlytics.android.Crashlytics; 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; @@ -39,7 +35,9 @@ 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; @@ -52,10 +50,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.receivers.AckAlarmRec 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.signatureVerifier.SignatureVerifier; import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin; -import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin; -import info.nightscout.androidaps.plugins.general.versionChecker.VersionCheckerPlugin; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin; import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin; @@ -73,7 +68,6 @@ 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.omnipod.OmnipodPumpPlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin; @@ -94,16 +88,16 @@ import info.nightscout.androidaps.receivers.NSAlarmReceiver; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.LocaleHelper; import io.fabric.sdk.android.Fabric; -import static info.nightscout.androidaps.plugins.general.versionChecker.VersionCheckerUtilsKt.triggerCheckVersion; +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; @@ -131,6 +125,7 @@ public class MainApp extends Application { log.debug("onCreate"); sInstance = this; sResources = getResources(); + LocaleHelper.INSTANCE.update(this); sConstraintsChecker = new ConstraintChecker(); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); @@ -159,8 +154,6 @@ public class MainApp extends Application { engineeringMode = engineeringModeSemaphore.exists() && engineeringModeSemaphore.isFile(); devBranch = BuildConfig.VERSION.contains("-") || BuildConfig.VERSION.matches(".*[a-zA-Z]+.*"); - sBus = L.isEnabled(L.EVENTS) && devBranch ? new LoggingBus(ThreadEnforcer.ANY) : new Bus(ThreadEnforcer.ANY); - registerLocalBroadcastReceiver(); //trigger here to see the new version on app start after an update @@ -170,9 +163,9 @@ public class MainApp extends Application { 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(ActionsPlugin.INSTANCE); + if (!Config.NSCLIENT) pluginsList.add(ActionsPlugin.INSTANCE); pluginsList.add(InsulinOrefRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefUltraRapidActingPlugin.getPlugin()); pluginsList.add(InsulinOrefFreePeakPlugin.getPlugin()); @@ -185,26 +178,25 @@ public class MainApp extends Application { if (Config.PUMPDRIVERS) pluginsList.add(DanaRv2Plugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(DanaRSPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(LocalInsightPlugin.getPlugin()); - pluginsList.add(CareportalPlugin.getPlugin()); if (Config.PUMPDRIVERS) pluginsList.add(ComboPlugin.getPlugin()); - if (Config.PUMPDRIVERS && engineeringMode) - pluginsList.add(MedtronicPumpPlugin.getPlugin()); + if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin()); if (Config.PUMPDRIVERS && engineeringMode) pluginsList.add(OmnipodPumpPlugin.getPlugin()); - if (Config.MDI) pluginsList.add(MDIPlugin.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.SAFETY) pluginsList.add(VersionCheckerPlugin.INSTANCE); - if (Config.SAFETY) pluginsList.add(StorageConstraintPlugin.getPlugin()); - if (Config.SAFETY) pluginsList.add(SignatureVerifier.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()); @@ -214,7 +206,7 @@ public class MainApp extends Application { pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourceTomatoPlugin.getPlugin()); pluginsList.add(SourceEversensePlugin.getPlugin()); - if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); + if (!Config.NSCLIENT) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(WearPlugin.initPlugin(this)); @@ -289,10 +281,6 @@ public class MainApp extends Application { KeepAliveReceiver.cancelAlarm(this); } - public static Bus bus() { - return sBus; - } - public static String gs(int id) { return sResources.getString(id); } @@ -394,19 +382,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; 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 db7a86e7f4..79f3fbf4d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.java @@ -16,7 +16,6 @@ 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; @@ -30,6 +29,7 @@ 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.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.general.overview.OverviewFragment; @@ -39,12 +39,15 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP 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 NoSplashActivity { private static Logger log = LoggerFactory.getLogger(HistoryBrowseActivity.class); - + private CompositeDisposable disposable = new CompositeDisposable(); ImageButton chartButton; @@ -165,14 +168,33 @@ public class HistoryBrowseActivity extends NoSplashActivity { @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()); @@ -193,26 +215,6 @@ public class HistoryBrowseActivity extends NoSplashActivity { iobCobCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished); } - @Subscribe - public void onStatusEvent(final EventAutosensCalculationFinished e) { - if (e.getCause() == 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); @@ -230,8 +232,8 @@ public class HistoryBrowseActivity extends NoSplashActivity { } 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)); 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 c5539f29d2..367429dbbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -17,7 +17,7 @@ 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.general.careportal.CareportalPlugin; @@ -68,17 +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); @@ -209,6 +206,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre 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))); } } 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 487def0241..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 androidx.recyclerview.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,6 +37,7 @@ 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.bus.RxBus; import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; @@ -49,11 +48,15 @@ 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.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 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 NoSplashActivity { @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 @@ -239,7 +254,7 @@ public class TDDStatsActivity extends NoSplashActivity { 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 NoSplashActivity { //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 NoSplashActivity { 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 NoSplashActivity { } } - @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(LocalInsightPlugin.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/Profile.java b/app/src/main/java/info/nightscout/androidaps/data/Profile.java index ea63605ceb..2a9a7b2783 100644 --- a/app/src/main/java/info/nightscout/androidaps/data/Profile.java +++ b/app/src/main/java/info/nightscout/androidaps/data/Profile.java @@ -17,6 +17,7 @@ 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.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; @@ -231,7 +232,7 @@ public class Profile { if (notify && secondsFromMidnight % 3600 != 0) { if (Config.APS) { 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)); + RxBus.INSTANCE.send(new EventNewNotification(notification)); } } } @@ -263,11 +264,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) { 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 80a6e1b457..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/data/QuickWizard.java +++ /dev/null @@ -1,86 +0,0 @@ -package info.nightscout.androidaps.data; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import info.nightscout.androidaps.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/db/BgReading.java b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java index 6fafdc4b6d..8b206e2c78 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/BgReading.java +++ b/app/src/main/java/info/nightscout/androidaps/db/BgReading.java @@ -216,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/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 9fa3ab9929..d8926fc4c1 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -243,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 @@ -412,7 +412,6 @@ 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; } @@ -738,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; } } @@ -1035,10 +1034,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { 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; } @@ -1371,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; } @@ -1577,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; } } @@ -1720,8 +1719,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void run() { if (L.isEnabled(L.DATABASE)) log.debug("Firing EventProfileNeedsUpdate"); - MainApp.bus().post(new EventReloadProfileSwitchData()); - MainApp.bus().post(new EventProfileNeedsUpdate()); + RxBus.INSTANCE.send(new EventReloadProfileSwitchData()); + RxBus.INSTANCE.send(new EventProfileNeedsUpdate()); scheduledProfileSwitchEventPost = null; } } 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 5f37c3d96b..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,6 +1,8 @@ package info.nightscout.androidaps.db; import android.graphics.Color; + +import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.j256.ormlite.field.DatabaseField; @@ -18,11 +20,13 @@ 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.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; @@ -78,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; } @@ -107,7 +111,7 @@ public class ProfileSwitch implements Interval, DataPointWithLabelInterface { */ 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) { @@ -156,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; @@ -212,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) { @@ -290,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/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/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.java b/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java deleted file mode 100644 index 81d1f60271..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventCustomActionsChanged.java +++ /dev/null @@ -1,4 +0,0 @@ -package info.nightscout.androidaps.events; - -public class EventCustomActionsChanged extends 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.java b/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java deleted file mode 100644 index 265ce2998c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventLocationChange.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.events; - -import android.location.Location; - -public class EventLocationChange extends Event { - public Location location; - - public EventLocationChange(Location location) { - this.location = location; - } -} 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 546d6f8624..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.androidaps.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 db3498bed7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventNewBG.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.events; - -import androidx.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.java b/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java deleted file mode 100644 index 9e3f3b08c7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventProfileNeedsUpdate.java +++ /dev/null @@ -1,8 +0,0 @@ -package info.nightscout.androidaps.events; - -/** - * Created by mike on 02.06.2017. - */ - -public class EventProfileNeedsUpdate extends Event { -} 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/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 e1d9d527e1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.java +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.events; - -import androidx.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/PluginBase.java b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java index 7b1d0c6175..f7c8e9ada4 100644 --- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java +++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java @@ -5,20 +5,19 @@ import android.os.SystemClock; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentActivity; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventConfigBuilderChange; -import info.nightscout.androidaps.events.EventRefreshGui; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.EventConfigBuilderUpdateGui; -import info.nightscout.androidaps.utils.SP; 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.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. @@ -81,8 +80,8 @@ public abstract class PluginBase { setFragmentVisible(type, enabled); ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(this, getType()); ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxEnabled"); - MainApp.bus().post(new EventRefreshGui()); - MainApp.bus().post(new EventConfigBuilderChange()); + RxBus.INSTANCE.send(new EventRebuildTabs()); + RxBus.INSTANCE.send(new EventConfigBuilderChange()); RxBus.INSTANCE.send(new EventConfigBuilderUpdateGui()); ConfigBuilderPlugin.getPlugin().logPluginStatus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index c9444acb33..f339bd3771 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -14,8 +14,6 @@ import android.os.SystemClock; import androidx.annotation.NonNull; import androidx.core.app.NotificationCompat; -import com.squareup.otto.Subscribe; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -52,6 +50,7 @@ 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; @@ -62,12 +61,15 @@ 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"; @@ -116,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() { @@ -135,8 +167,8 @@ public class LoopPlugin extends PluginBase { @Override protected void onStop() { + disposable.clear(); super.onStop(); - MainApp.bus().unregister(this); } @Override @@ -145,43 +177,10 @@ 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.getCause() 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; } - @Subscribe - public void onStatusEvent(final EventTempTargetChange ev) { - new Thread(() -> invoke("EventTempTargetChange", true)).start(); - } - - public void suspendTo(long endTime) { loopSuspendedTill = endTime; isSuperBolus = false; @@ -439,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"); @@ -472,7 +471,7 @@ public class LoopPlugin extends PluginBase { NSUpload.uploadDeviceStatus(); SP.incInt(R.string.key_ObjectivesmanualEnacts); } - MainApp.bus().post(new EventAcceptOpenLoopChange()); + RxBus.INSTANCE.send(new EventAcceptOpenLoopChange()); } }); FabricPrivacy.getInstance().logCustom("AcceptTemp"); @@ -647,7 +646,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); } } }); @@ -656,7 +660,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); } } }); @@ -667,7 +676,12 @@ public class LoopPlugin extends PluginBase { @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); } } }); @@ -681,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/aps/loop/events/EventNewOpenLoopNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java deleted file mode 100644 index 6a0a4dc0cf..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/events/EventNewOpenLoopNotification.java +++ /dev/null @@ -1,9 +0,0 @@ -package info.nightscout.androidaps.plugins.aps.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/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/common/SubscriberFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java deleted file mode 100644 index 4e6f07671d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/common/SubscriberFragment.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.common; - -import androidx.fragment.app.Fragment; - -import info.nightscout.androidaps.MainApp; - -abstract public class SubscriberFragment extends Fragment { - @Override - public void onPause() { - super.onPause(); - MainApp.bus().unregister(this); - } - - @Override - public void onResume() { - super.onResume(); - MainApp.bus().register(this); - updateGUI(); - } - - protected abstract void updateGUI(); -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index f011ac57cf..059bec1444 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -68,6 +68,7 @@ class ConfigBuilderFragment : Fragment() { @Synchronized private fun updateGUI() { + configbuilder_categories.removeAllViews() createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, MainApp.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE)) createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, MainApp.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN)) createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, MainApp.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java index b73c535147..f43513fbf5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.SensitivityInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.insulin.InsulinOrefRapidActingPlugin; import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; @@ -67,14 +68,12 @@ public class ConfigBuilderPlugin extends PluginBase { @Override protected void onStart() { - MainApp.bus().register(this); super.onStart(); } @Override protected void onStop() { super.onStop(); - MainApp.bus().unregister(this); } @@ -83,7 +82,7 @@ public class ConfigBuilderPlugin extends PluginBase { upgradeSettings(); loadSettings(); setAlwaysEnabledPluginsEnabled(); - MainApp.bus().post(new EventAppInitialized()); + RxBus.INSTANCE.send(new EventAppInitialized()); } private void setAlwaysEnabledPluginsEnabled() { 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 b81ae37983..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 androidx.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/PluginViewHolder.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt index ddb5356f70..86e0f39437 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginViewHolder.kt @@ -3,12 +3,12 @@ package info.nightscout.androidaps.plugins.configBuilder import android.content.Intent import android.view.View import android.widget.* -import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.PreferencesActivity -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.bus.RxBus import info.nightscout.androidaps.utils.PasswordProtection class PluginViewHolder internal constructor(private val fragment: ConfigBuilderFragment, @@ -34,7 +34,7 @@ class PluginViewHolder internal constructor(private val fragment: ConfigBuilderF pluginVisibility.setOnClickListener { plugin.setFragmentVisible(pluginType, pluginVisibility.isChecked) ConfigBuilderPlugin.getPlugin().storeSettings("CheckedCheckboxVisible") - MainApp.bus().post(EventRefreshGui()) + RxBus.send(EventRebuildTabs()) ConfigBuilderPlugin.getPlugin().logPluginStatus() } 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 index b9276a5ac3..025d8dac1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctions.java @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.configBuilder; import android.content.Intent; import android.os.Bundle; + import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import com.squareup.otto.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,14 +23,18 @@ import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.interfaces.ProfileInterface; import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.SP; +import io.reactivex.disposables.CompositeDisposable; +import io.reactivex.schedulers.Schedulers; public class ProfileFunctions { private static Logger log = LoggerFactory.getLogger(L.PROFILE); + private CompositeDisposable disposable = new CompositeDisposable(); private static ProfileFunctions profileFunctions = null; @@ -44,29 +48,30 @@ public class ProfileFunctions { ProfileFunctions.getInstance(); // register to bus at start } - ProfileFunctions() { - MainApp.bus().register(this); - } - - @Subscribe - public void onProfileSwitch(EventProfileNeedsUpdate 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); - } - if (result.enacted) - MainApp.bus().post(new EventNewBasalProfile()); - } - }); + private ProfileFunctions() { + disposable.add(RxBus.INSTANCE + .toObservable(EventProfileNeedsUpdate.class) + .observeOn(Schedulers.io()) + .subscribe(event -> { + 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); + } + if (result.enacted) + RxBus.INSTANCE.send(new EventNewBasalProfile()); + } + }); + }, FabricPrivacy::logException) + ); } public String getProfileName() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java index ec3ef44881..e026d6589d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.java @@ -15,6 +15,7 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; +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; @@ -89,6 +90,6 @@ public class DstHelperPlugin extends PluginBase implements ConstraintsInterface private void warnUser(int id, String warningText) { Notification notification = new Notification(id, warningText, Notification.LOW); - MainApp.bus().post(new EventNewNotification(notification)); + RxBus.INSTANCE.send(new EventNewNotification(notification)); } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index 63f522da8d..aafd877672 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -18,19 +18,20 @@ import androidx.recyclerview.widget.LinearSmoothScroller import androidx.recyclerview.widget.RecyclerView import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.SP +import info.nightscout.androidaps.receivers.NetworkChangeReceiver +import info.nightscout.androidaps.utils.* import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.objectives_fragment.* +import org.slf4j.LoggerFactory class ObjectivesFragment : Fragment() { + private val log = LoggerFactory.getLogger(L.CONSTRAINTS) private val objectivesAdapter = ObjectivesAdapter() private val handler = Handler(Looper.getMainLooper()) @@ -50,7 +51,6 @@ class ObjectivesFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - objectives_recyclerview.layoutManager = LinearLayoutManager(view.context) objectives_recyclerview.adapter = objectivesAdapter objectives_fake.setOnClickListener { updateGUI() } @@ -104,17 +104,14 @@ class ObjectivesFragment : Fragment() { for (i in 0 until ObjectivesPlugin.objectives.size) { val objective = ObjectivesPlugin.objectives[i] if (!objective.isStarted || !objective.isAccomplished) { - val smoothScroller = object : LinearSmoothScroller(context!!) { - override fun getVerticalSnapPreference(): Int { - return SNAP_TO_START - } - - override fun calculateTimeForScrolling(dx: Int): Int { - return super.calculateTimeForScrolling(dx) * 4 + context?.let { + val smoothScroller = object : LinearSmoothScroller(it) { + override fun getVerticalSnapPreference(): Int = SNAP_TO_START + override fun calculateTimeForScrolling(dx: Int): Int = super.calculateTimeForScrolling(dx) * 4 } + smoothScroller.targetPosition = i + objectives_recyclerview.layoutManager?.startSmoothScroll(smoothScroller) } - smoothScroller.targetPosition = i - objectives_recyclerview.layoutManager?.startSmoothScroll(smoothScroller) break } } @@ -168,10 +165,17 @@ class ObjectivesFragment : Fragment() { holder.progress.removeAllViews() for (task in objective.tasks) { if (task.shouldBeIgnored()) continue + // name val name = TextView(holder.progress.context) name.text = MainApp.gs(task.task) + ":" name.setTextColor(-0x1) holder.progress.addView(name, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT) + // hint + task.hints.forEach { h -> + if (!task.isCompleted) + holder.progress.addView(h.generate(context)) + } + // state val state = TextView(holder.progress.context) state.setTextColor(-0x1) val basicHTML = "%2\$s" @@ -183,13 +187,14 @@ class ObjectivesFragment : Fragment() { state.setOnClickListener { val dialog = ObjectivesExamDialog() val bundle = Bundle() - val position = objective.tasks.indexOf(task) - bundle.putInt("currentTask", position) + val taskPosition = objective.tasks.indexOf(task) + bundle.putInt("currentTask", taskPosition) dialog.arguments = bundle ObjectivesExamDialog.objective = objective fragmentManager?.let { dialog.show(it, "ObjectivesFragment") } } } + // horizontal line val separator = View(holder.progress.context) separator.setBackgroundColor(Color.DKGRAY) holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) @@ -198,16 +203,64 @@ class ObjectivesFragment : Fragment() { holder.accomplished.text = MainApp.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn)) holder.accomplished.setTextColor(-0x3e3e3f) holder.verify.setOnClickListener { - objective.accomplishedOn = DateUtil.now() - notifyDataSetChanged() - scrollToCurrentObjective() - startUpdateTimer() + holder.verify.visibility = View.INVISIBLE + NetworkChangeReceiver.fetch() + if (objectives_fake.isChecked) { + objective.accomplishedOn = DateUtil.now() + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else + SntpClient.ntpTime(object : SntpClient.Callback() { + override fun run() { + activity?.runOnUiThread { + holder.verify.visibility = View.VISIBLE + log.debug("NTP time: $time System time: ${DateUtil.now()}") + if (!networkConnected) { + ToastUtils.showToastInUiThread(context, R.string.notconnected) + } else if (success) { + if (objective.isCompleted(time)) { + objective.accomplishedOn = time + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else { + ToastUtils.showToastInUiThread(context, R.string.requirementnotmet) + } + } else { + ToastUtils.showToastInUiThread(context, R.string.failedretrievetime) + } + } + } + }, NetworkChangeReceiver.isConnected()) } holder.start.setOnClickListener { - objective.startedOn = DateUtil.now() - notifyDataSetChanged() - scrollToCurrentObjective() - startUpdateTimer() + holder.start.visibility = View.INVISIBLE + NetworkChangeReceiver.fetch() + if (objectives_fake.isChecked) { + objective.startedOn = DateUtil.now() + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else + SntpClient.ntpTime(object : SntpClient.Callback() { + override fun run() { + activity?.runOnUiThread { + holder.start.visibility = View.VISIBLE + log.debug("NTP time: $time System time: ${DateUtil.now()}") + if (!networkConnected) { + ToastUtils.showToastInUiThread(context, R.string.notconnected) + } else if (success) { + objective.startedOn = time + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else { + ToastUtils.showToastInUiThread(context, R.string.failedretrievetime) + } + } + } + }, NetworkChangeReceiver.isConnected()) } holder.revert.setOnClickListener { objective.accomplishedOn = 0 @@ -216,8 +269,8 @@ class ObjectivesFragment : Fragment() { val prevObj = ObjectivesPlugin.objectives[position - 1] prevObj.accomplishedOn = 0 } - notifyDataSetChanged() scrollToCurrentObjective() + RxBus.send(EventObjectivesUpdateGui()) } if (objective.hasSpecialInput && !objective.isAccomplished && objective.isStarted) { // generate random request code if none exists @@ -231,7 +284,7 @@ class ObjectivesFragment : Fragment() { holder.enterButton.setOnClickListener { val input = holder.input.text.toString() objective.specialAction(activity, input) - notifyDataSetChanged() + RxBus.send(EventObjectivesUpdateGui()) } } else { holder.enterButton.visibility = View.GONE diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index dcd9dd31d1..ca3e1d3126 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -21,8 +21,8 @@ import java.util.* object ObjectivesPlugin : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .fragmentClass(ObjectivesFragment::class.qualifiedName) - .alwaysEnabled(!Config.NSCLIENT) - .showInList(!Config.NSCLIENT) + .alwaysEnabled(Config.APS) + .showInList(Config.APS) .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives)), ConstraintsInterface { @@ -64,7 +64,7 @@ object ObjectivesPlugin : PluginBase(PluginDescription() private fun doConvertSP(number: Int, name: String) { if (!SP.contains("Objectives_" + name + "_started")) { - SP.putLong("Objectives_" + name + "_started", SP.getLong("Objectives" + number + "accomplished", 0L)) + SP.putLong("Objectives_" + name + "_started", SP.getLong("Objectives" + number + "started", 0L)) SP.putLong("Objectives_" + name + "_accomplished", SP.getLong("Objectives" + number + "accomplished", 0L)) } // TODO: we can remove Objectives1accomplished sometimes later diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt index 1c7c6c7ee1..1428652be5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt @@ -57,12 +57,11 @@ class ObjectivesExamDialog : DialogFragment() { objectives_exam_question.setText(task.question) // Options objectives_exam_options.removeAllViews() - for (o in task.options) { - val option: Option = o as Option; - val cb = option.generate(context) + task.options.forEach { + val cb = it.generate(context) if (task.answered) { cb.isEnabled = false - if (option.isCorrect) + if (it.isCorrect) cb.isChecked = true } objectives_exam_options.addView(cb) @@ -70,8 +69,7 @@ class ObjectivesExamDialog : DialogFragment() { // Hints objectives_exam_hints.removeAllViews() for (h in task.hints) { - val hint: Hint = h as Hint; - objectives_exam_hints.addView(hint.generate(context)) + objectives_exam_hints.addView(h.generate(context)) } // Disabled to objectives_exam_disabledto.text = MainApp.gs(R.string.answerdisabledto, DateUtil.timeString(task.disabledTo)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java index f58d469fa2..c882a921f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.java @@ -4,6 +4,7 @@ import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.text.util.Linkify; +import android.view.View; import android.widget.CheckBox; import android.widget.TextView; @@ -36,6 +37,10 @@ public abstract class Objective { this.gate = gate; startedOn = SP.getLong("Objectives_" + spName + "_started", 0L); accomplishedOn = SP.getLong("Objectives_" + spName + "_accomplished", 0L); + if ((accomplishedOn - DateUtil.now()) > T.hours(3).msecs() || (startedOn - DateUtil.now()) > T.hours(3).msecs()) { // more than 3 hours in the future + startedOn = 0; + accomplishedOn = 0; + } setupTasks(tasks); for (Task task : tasks) task.objective = this; } @@ -48,12 +53,20 @@ public abstract class Objective { return true; } + public boolean isCompleted(long trueTime) { + for (Task task : tasks) { + if (!task.shouldBeIgnored() && !task.isCompleted(trueTime)) + return false; + } + return true; + } + public boolean isRevertable() { return false; } public boolean isAccomplished() { - return accomplishedOn != 0; + return accomplishedOn != 0 && accomplishedOn < DateUtil.now(); } public boolean isStarted() { @@ -100,6 +113,7 @@ public abstract class Objective { @StringRes private int task; private Objective objective; + ArrayList hints = new ArrayList<>(); public Task(@StringRes int task) { this.task = task; @@ -114,11 +128,21 @@ public abstract class Objective { } public abstract boolean isCompleted(); + public boolean isCompleted(long trueTime) { return isCompleted(); }; public String getProgress() { return MainApp.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet); } + Task hint(Hint hint) { + hints.add(hint); + return this; + } + + public ArrayList getHints() { + return hints; + } + public boolean shouldBeIgnored() { return false; } @@ -138,6 +162,11 @@ public abstract class Objective { return getObjective().isStarted() && System.currentTimeMillis() - getObjective().getStartedOn() >= minimumDuration; } + @Override + public boolean isCompleted(long trueTime) { + return getObjective().isStarted() && trueTime - getObjective().getStartedOn() >= minimumDuration; + } + @Override public String getProgress() { return getDurationText(System.currentTimeMillis() - getObjective().getStartedOn()) @@ -157,8 +186,7 @@ public abstract class Objective { public class ExamTask extends Task { @StringRes int question; - List hints = new ArrayList<>(); - List options = new ArrayList<>(); + ArrayList

- * You can also change the locale of your application on the fly by using the setLocale method. - *

- * Created by gunhansancar on 07/10/15. - */ -public class LocaleHelper { - - private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language"; - - public static void onCreate(Context context) { - String lang = getPersistedData(Locale.getDefault().getLanguage()); - setLocale(context, lang); - } - - public static void onCreate(Context context, String defaultLanguage) { - String lang = getPersistedData(defaultLanguage); - setLocale(context, lang); - } - - public static String getLanguage() { - return getPersistedData(Locale.getDefault().getLanguage()); - } - - public static void setLocale(Context context, String language) { - persist(context, language); - updateResources(context, language); - } - - private static String getPersistedData(String defaultLanguage) { - return SP.getString(SELECTED_LANGUAGE, defaultLanguage); - } - - private static void persist(Context context, String language) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - SharedPreferences.Editor editor = preferences.edit(); - - editor.putString(SELECTED_LANGUAGE, language); - editor.apply(); - } - - private static void updateResources(Context context, String language) { - Locale locale = new Locale(language); - Locale.setDefault(locale); - - Resources resources = context.getResources(); - - Configuration configuration = resources.getConfiguration(); - configuration.locale = locale; - - resources.updateConfiguration(configuration, resources.getDisplayMetrics()); - } - - public static Locale getLocale() { - return new Locale(getPersistedData("en")); - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.kt new file mode 100644 index 0000000000..6052c5699a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.utils + +import android.content.Context +import info.nightscout.androidaps.R +import java.util.* + +object LocaleHelper { + fun update(context: Context) = + updateResources(context, currentLanguage()) + + fun currentLanguage(): String = + SP.getString(R.string.key_language, Locale.getDefault().language) + + fun currentLocale(): Locale = + Locale(SP.getString(R.string.key_language, Locale.getDefault().language)) + + @Suppress("DEPRECATION") + private fun updateResources(context: Context, language: String) { + var locale = Locale(language) + if (language.contains("_")) { + // language with country like pt_BR defined in arrays.xml + val lang = language.substring(0, 2) + val country = language.substring(3, 5) + locale = Locale(lang, country) + } + + Locale.setDefault(locale) + val resources = context.resources + resources.configuration.setLocale(locale) + resources.updateConfiguration(resources.configuration, resources.displayMetrics) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java new file mode 100644 index 0000000000..fcee3638b9 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java @@ -0,0 +1,227 @@ +package info.nightscout.androidaps.utils; +/* + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import android.os.SystemClock; +import android.util.Log; + +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; + +/** + * {@hide} + *

+ * Simple SNTP client class for retrieving network time. + *

+ * Sample usage: + *

SntpClient client = new SntpClient();
+ * if (client.requestTime("time.foo.com")) {
+ *     long now = client.getNtpTime() + SystemClock.elapsedRealtime() - client.getNtpTimeReference();
+ * }
+ * 
+ */ +public class SntpClient { + private static final String TAG = "SntpClient"; + + //private static final int REFERENCE_TIME_OFFSET = 16; + private static final int ORIGINATE_TIME_OFFSET = 24; + private static final int RECEIVE_TIME_OFFSET = 32; + private static final int TRANSMIT_TIME_OFFSET = 40; + private static final int NTP_PACKET_SIZE = 48; + + private static final int NTP_PORT = 123; + private static final int NTP_MODE_CLIENT = 3; + private static final int NTP_VERSION = 3; + + // Number of seconds between Jan 1, 1900 and Jan 1, 1970 + // 70 years plus 17 leap days + private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; + + // system time computed from NTP server response + private static long mNtpTime; + + // value of SystemClock.elapsedRealtime() corresponding to mNtpTime + private static long mNtpTimeReference; + + // round trip time in milliseconds + private static long mRoundTripTime; + + public static abstract class Callback implements Runnable { + public boolean networkConnected = false; + public boolean success = false; + public long time = 0; + } + + public static synchronized void ntpTime(final Callback callback, boolean isConnected) { + callback.networkConnected = isConnected; + if (callback.networkConnected) { + new Thread(() -> doNtpTime(callback)).start(); + } else { + callback.run(); + } + } + + static void doNtpTime(final Callback callback) { + callback.success = requestTime("time.google.com", 5000); + callback.time = getNtpTime() + SystemClock.elapsedRealtime() - getNtpTimeReference(); + callback.run(); + } + + /** + * Sends an SNTP request to the given host and processes the response. + * + * @param host host name of the server. + * @param timeout network timeout in milliseconds. + * @return true if the transaction was successful. + */ + private static synchronized boolean requestTime(String host, int timeout) { + try { + DatagramSocket socket = new DatagramSocket(); + socket.setSoTimeout(timeout); + InetAddress address = InetAddress.getByName(host); + byte[] buffer = new byte[NTP_PACKET_SIZE]; + DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT); + + // set mode = 3 (client) and version = 3 + // mode is in low 3 bits of first byte + // version is in bits 3-5 of first byte + buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3); + + // get current time and write it to the request packet + long requestTime = System.currentTimeMillis(); + long requestTicks = SystemClock.elapsedRealtime(); + writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime); + + socket.send(request); + + // read the response + DatagramPacket response = new DatagramPacket(buffer, buffer.length); + socket.receive(response); + long responseTicks = SystemClock.elapsedRealtime(); + long responseTime = requestTime + (responseTicks - requestTicks); + socket.close(); + + // extract the results + long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET); + long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET); + long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET); + long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime); + // receiveTime = originateTime + transit + skew + // responseTime = transmitTime + transit - skew + // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2 + // = ((originateTime + transit + skew - originateTime) + + // (transmitTime - (transmitTime + transit - skew)))/2 + // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2 + // = (transit + skew - transit + skew)/2 + // = (2 * skew)/2 = skew + long clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2; + // if (Config.LOGD) Log.d(TAG, "round trip: " + roundTripTime + " ms"); + // if (Config.LOGD) Log.d(TAG, "clock offset: " + clockOffset + " ms"); + + // save our results - use the times on this side of the network latency + // (response rather than request time) + mNtpTime = responseTime + clockOffset; + mNtpTimeReference = responseTicks; + mRoundTripTime = roundTripTime; + } catch (Exception e) { + Log.d(TAG, "request time failed: " + e); + return false; + } + + return true; + } + + /** + * Returns the time computed from the NTP transaction. + * + * @return time value computed from NTP server response. + */ + private static long getNtpTime() { + return mNtpTime; + } + + /** + * Returns the reference clock value (value of SystemClock.elapsedRealtime()) + * corresponding to the NTP time. + * + * @return reference clock corresponding to the NTP time. + */ + private static long getNtpTimeReference() { + return mNtpTimeReference; + } + + /** + * Returns the round trip time of the NTP transaction + * + * @return round trip time in milliseconds. + */ + public long getRoundTripTime() { + return mRoundTripTime; + } + + /** + * Reads an unsigned 32 bit big endian number from the given offset in the buffer. + */ + private static long read32(byte[] buffer, int offset) { + byte b0 = buffer[offset]; + byte b1 = buffer[offset + 1]; + byte b2 = buffer[offset + 2]; + byte b3 = buffer[offset + 3]; + + // convert signed bytes to unsigned values + int i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0); + int i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1); + int i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2); + int i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3); + + return ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3; + } + + /** + * Reads the NTP time stamp at the given offset in the buffer and returns + * it as a system time (milliseconds since January 1, 1970). + */ + private static long readTimeStamp(byte[] buffer, int offset) { + long seconds = read32(buffer, offset); + long fraction = read32(buffer, offset + 4); + return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); + } + + /** + * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp + * at the given offset in the buffer. + */ + private static void writeTimeStamp(byte[] buffer, int offset, long time) { + long seconds = time / 1000L; + long milliseconds = time - seconds * 1000L; + seconds += OFFSET_1900_TO_1970; + + // write seconds in big endian format + buffer[offset++] = (byte) (seconds >> 24); + buffer[offset++] = (byte) (seconds >> 16); + buffer[offset++] = (byte) (seconds >> 8); + buffer[offset++] = (byte) (seconds >> 0); + + long fraction = milliseconds * 0x100000000L / 1000L; + // write fraction in big endian format + buffer[offset++] = (byte) (fraction >> 24); + buffer[offset++] = (byte) (fraction >> 16); + buffer[offset++] = (byte) (fraction >> 8); + // low order bits should be random data + buffer[offset++] = (byte) (Math.random() * 255.0); + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java b/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java index 815a90681b..fe596d8f08 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/ToastUtils.java @@ -6,29 +6,20 @@ import android.os.Handler; import android.os.Looper; import android.widget.Toast; -import androidx.annotation.IdRes; - import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; +import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; +import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; public class ToastUtils { - public static void showToastInUiThread(final Context ctx, - final int stringId) { + public static void showToastInUiThread(final Context ctx, final int stringId) { showToastInUiThread(ctx, MainApp.gs(stringId)); } - public static void showToastInUiThread(final Context ctx, - final String string) { - + public static void showToastInUiThread(final Context ctx, final String string) { Handler mainThread = new Handler(Looper.getMainLooper()); - mainThread.post(new Runnable() { - @Override - public void run() { - Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show(); - } - }); + mainThread.post(() -> Toast.makeText(ctx, string, Toast.LENGTH_SHORT).show()); } public static void showToastInUiThread(final Context ctx, @@ -36,23 +27,13 @@ public class ToastUtils { showToastInUiThread(ctx, string); playSound(ctx, soundID); - new Thread(new Runnable() { - @Override - public void run() { - Notification notification = new Notification(Notification.TOAST_ALARM, string, Notification.URGENT); - MainApp.bus().post(new EventNewNotification(notification)); - } - }).start(); + Notification notification = new Notification(Notification.TOAST_ALARM, string, Notification.URGENT); + RxBus.INSTANCE.send(new EventNewNotification(notification)); } private static void playSound(final Context ctx, final int soundID) { final MediaPlayer soundMP = MediaPlayer.create(ctx, soundID); soundMP.start(); - soundMP.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { - @Override - public void onCompletion(MediaPlayer mp) { - mp.release(); - } - }); + soundMP.setOnCompletionListener(MediaPlayer::release); } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/Translator.java b/app/src/main/java/info/nightscout/androidaps/utils/Translator.java index ee83f856e4..e25c083a7b 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/Translator.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/Translator.java @@ -33,6 +33,8 @@ public class Translator { return MainApp.gs(R.string.careportal_exercise); case "Site Change": return MainApp.gs(R.string.careportal_pumpsitechange); + case "Pump Battery Change": + return MainApp.gs(R.string.careportal_pumpbatterychange); case "Sensor Start": return MainApp.gs(R.string.careportal_cgmsensorstart); case "Sensor Change": diff --git a/app/src/main/res/layout/automation_dialog_action.xml b/app/src/main/res/layout/automation_dialog_action.xml index 9297cba148..5077dcd4bc 100644 --- a/app/src/main/res/layout/automation_dialog_action.xml +++ b/app/src/main/res/layout/automation_dialog_action.xml @@ -2,7 +2,6 @@ + android:text="@string/please_choose_an_action_type" + android:textAppearance="@style/TextAppearance.AppCompat.Large" /> + android:text="@string/please_choose_a_trigger_type" + android:textAppearance="@style/TextAppearance.AppCompat.Large" /> + android:text="@string/triggers" + android:textAppearance="@style/TextAppearance.AppCompat.Large" /> + android:layout_marginBottom="15dp" /> + android:entries="@array/quickWizardYesNo"/> + android:entries="@array/quickWizardYesNo"/> + android:entries="@array/quickWizardYesNoPosNeg"/> + android:entries="@array/quickWizardYesNo"/> + android:entries="@array/quickWizardYesNoPosNeg"/> + android:entries="@array/quickWizardYesNo"/> + android:entries="@array/quickWizardYesNo"/> diff --git a/app/src/main/res/layout/overview_fragment.xml b/app/src/main/res/layout/overview_fragment.xml index e94eb29d0e..8741cf1c2a 100644 --- a/app/src/main/res/layout/overview_fragment.xml +++ b/app/src/main/res/layout/overview_fragment.xml @@ -192,8 +192,7 @@ android:id="@+id/overview_canulaage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -202,8 +201,7 @@ android:id="@+id/overview_insulinage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -212,8 +210,7 @@ android:id="@+id/overview_reservoirlevel" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -222,8 +219,7 @@ android:id="@+id/overview_sensorage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -232,8 +228,7 @@ android:id="@+id/overview_batterylevel" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> diff --git a/app/src/main/res/layout/overview_fragment_smallheight.xml b/app/src/main/res/layout/overview_fragment_smallheight.xml index 0c5789185f..18625a562c 100644 --- a/app/src/main/res/layout/overview_fragment_smallheight.xml +++ b/app/src/main/res/layout/overview_fragment_smallheight.xml @@ -192,8 +192,7 @@ android:id="@+id/overview_canulaage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -202,8 +201,7 @@ android:id="@+id/overview_insulinage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -212,8 +210,7 @@ android:id="@+id/overview_reservoirlevel" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -222,8 +219,7 @@ android:id="@+id/overview_sensorage" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> @@ -232,8 +228,7 @@ android:id="@+id/overview_batterylevel" android:layout_width="wrap_content" android:layout_height="wrap_content" - android:paddingHorizontal="5dp" - android:layout_marginHorizontal="3dp" + android:layout_weight="1" android:gravity="center" android:text="" android:textSize="14sp" /> diff --git a/app/src/main/res/layout/overview_wizard_dialog.xml b/app/src/main/res/layout/overview_wizard_dialog.xml index 4cc27c2092..71ce0e31e9 100644 --- a/app/src/main/res/layout/overview_wizard_dialog.xml +++ b/app/src/main/res/layout/overview_wizard_dialog.xml @@ -1,6 +1,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + android:layout_gravity="center" + android:layout_marginLeft="10dp" + android:layout_marginRight="10dp" + android:text="@string/boluswizard" + android:textAppearance="?android:attr/textAppearanceLarge" + android:textColor="@color/colorCalculatorButton" /> + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -173,9 +192,9 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" - android:layout_marginLeft="10dp" + android:layout_marginStart="10dp" android:checked="false" - android:text="Super\nbolus" /> + android:text="@string/superbolus" /> @@ -211,7 +230,7 @@ @@ -219,7 +238,7 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" - android:width="120dp" + android:labelFor="@+id/treatment_wizard_notes" android:padding="10dp" android:text="@string/careportal_newnstreatment_notes_label" android:textAppearance="@android:style/TextAppearance.Material.Small" @@ -227,317 +246,373 @@ - + + + + + + +