diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000000..d15d2440fd
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,48 @@
+This document speciffy hints and good practices for source code contributions.
+
+AndroidAPS is community effort and all contributions are welcome! If you wish help us improving AndroidAPS - please read and try to adhere to
+this guidelines, to make the development and process of change aproval as smooth as possible :)
+
+General rules
+=============
+
+* There are plenty of ways you can help, some of them are listed on wiki:
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/How-can-I-help.html
+* If you wish to help with documentation or translating:
+ https://androidaps.readthedocs.io/en/latest/EN/translations.html
+
+Development guidelines
+======================
+
+Coding convetions
+-----------------
+1. Use Android Studio with default indents (4 chars, use spaces)
+2. Use autoformat feature CTRL-ALT-L in every changed file before commit
+
+Commiting Changes / Pull Requests
+---------------------------------
+
+1. Make fork of repository on github
+2. Create separate branch for each feature, branch from most recent dev
+3. Commit all changes to your fork
+4. When ready, rebase on top of dev and make pull request to main repo
+
+Naming Conventions for Pull Requests / Branches
+-----------------------------------------------
+
+TODO
+
+Translations
+------------
+
+* If possible, always use Android translation mechanism (with strings.xml and @strings/id) instead of hardcoded texts
+* Provide only English strings - all other languages will be crowd translated via Crowdn https://translations.androidaps.org/
+
+Hints
+-----
+
+* Start small, it is easier to review smaller changes that affect fewer parts of code
+* Take a look into Issues list (https://github.com/MilosKozak/AndroidAPS/issues) - maybe there is somthing you can fix or implement
+* For new features, make sure there is Issue to track progress and have on-topic discussion
+* Reach out to community, discuss idea on Gitter (https://gitter.im/MilosKozak/AndroidAPS)
+* Speak with other developers to minimise merge conflicts. Find out who worked, working or plan to work on speciffic issue or part of app
diff --git a/app/build.gradle b/app/build.gradle
index 8b2c15a042..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-g"
+ 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,9 +284,6 @@ 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"
/*
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/MainActivity.java b/app/src/main/java/info/nightscout/androidaps/MainActivity.java
index 83dab8130d..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(false);
- } 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 4137e2e1b1..785aa84c38 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,9 +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.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;
@@ -92,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;
@@ -129,10 +125,18 @@ 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);
- Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> log.error("Uncaught exception crashing app", ex));
+ Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> {
+ if (ex instanceof InternalError) {
+ // usually the app trying to spawn a thread while being killed
+ return;
+ }
+
+ log.error("Uncaught exception crashing app", ex);
+ });
try {
if (FabricPrivacy.fabricEnabled()) {
@@ -157,8 +161,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,7 +172,7 @@ public class MainApp extends Application {
// Register all tabs in app here
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());
@@ -183,24 +185,23 @@ 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.MDI) pluginsList.add(MDIPlugin.getPlugin());
+ if (Config.PUMPDRIVERS) pluginsList.add(MedtronicPumpPlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(MDIPlugin.getPlugin());
pluginsList.add(VirtualPumpPlugin.getPlugin());
+ pluginsList.add(CareportalPlugin.getPlugin());
if (Config.APS) pluginsList.add(LoopPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSAMAPlugin.getPlugin());
if (Config.APS) pluginsList.add(OpenAPSSMBPlugin.getPlugin());
pluginsList.add(NSProfilePlugin.getPlugin());
- if (Config.OTHERPROFILES) pluginsList.add(SimpleProfilePlugin.getPlugin());
- if (Config.OTHERPROFILES) pluginsList.add(LocalProfilePlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(SimpleProfilePlugin.getPlugin());
+ if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.getPlugin());
pluginsList.add(TreatmentsPlugin.getPlugin());
- if (Config.SAFETY) pluginsList.add(SafetyPlugin.getPlugin());
- if (Config.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());
@@ -210,7 +211,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.INSTANCE);
pluginsList.add(FoodPlugin.getPlugin());
pluginsList.add(WearPlugin.initPlugin(this));
@@ -285,10 +286,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);
}
@@ -390,19 +387,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 cd969a53a1..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);
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 5096a82250..0e93a47151 100644
--- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java
@@ -9,27 +9,28 @@ import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceGroup;
import android.preference.PreferenceManager;
-import android.preference.PreferenceScreen;
-import android.text.TextUtils;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
-import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
-import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin;
-import info.nightscout.androidaps.plugins.general.tidepool.comm.TidepoolUploader;
-import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
-import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
+import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
+import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin;
+import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
+import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
+import info.nightscout.androidaps.plugins.general.tidepool.TidepoolPlugin;
+import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
+import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
+import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin;
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin;
@@ -42,14 +43,9 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref0Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
-import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin;
-import info.nightscout.androidaps.plugins.general.wear.WearPlugin;
-import info.nightscout.androidaps.plugins.general.xdripStatusline.StatuslinePlugin;
import info.nightscout.androidaps.plugins.source.SourceDexcomPlugin;
-import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP;
-import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
MyPreferenceFragment myPreferenceFragment;
@@ -68,22 +64,19 @@ 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);
}
- updatePrefSummary(myPreferenceFragment.getPreference(key));
+ updatePrefSummary(myPreferenceFragment.findPreference(key));
}
private static void updatePrefSummary(Preference pref) {
@@ -95,13 +88,13 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
EditTextPreference editTextPref = (EditTextPreference) pref;
if (pref.getKey().contains("password") || pref.getKey().contains("secret")) {
pref.setSummary("******");
- } else if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name))) {
- pref.setSummary(SP.getString(R.string.key_danars_name, ""));
} else if (editTextPref.getText() != null) {
((EditTextPreference) pref).setDialogMessage(editTextPref.getDialogMessage());
pref.setSummary(editTextPref.getText());
- } else if (pref.getKey().contains("smscommunicator_allowednumbers") && (editTextPref.getText() == null || TextUtils.isEmpty(editTextPref.getText().trim()))) {
- pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary));
+ } else {
+ for (PluginBase plugin : MainApp.getPluginsList()) {
+ plugin.updatePreferenceSummary(pref);
+ }
}
}
}
@@ -191,7 +184,7 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(NSClientPlugin.getPlugin(), PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(TidepoolPlugin.INSTANCE, PluginType.GENERAL);
- addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.getPlugin(), PluginType.GENERAL);
+ addPreferencesFromResourceIfEnabled(SmsCommunicatorPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResourceIfEnabled(AutomationPlugin.INSTANCE, PluginType.GENERAL);
addPreferencesFromResource(R.xml.pref_others);
@@ -201,26 +194,11 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
addPreferencesFromResourceIfEnabled(StatuslinePlugin.getPlugin(), PluginType.GENERAL);
}
- if (Config.NSCLIENT) {
- PreferenceScreen scrnAdvancedSettings = (PreferenceScreen) findPreference(getString(R.string.key_advancedsettings));
- if (scrnAdvancedSettings != null) {
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_warning)));
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_res_critical)));
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_warning)));
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_statuslights_bat_critical)));
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights)));
- scrnAdvancedSettings.removePreference(getPreference(getString(R.string.key_show_statuslights_extended)));
- }
- }
-
initSummary(getPreferenceScreen());
- final Preference tidepoolTestLogin = findPreference(MainApp.gs(R.string.key_tidepool_test_login));
- if (tidepoolTestLogin != null)
- tidepoolTestLogin.setOnPreferenceClickListener(preference -> {
- TidepoolUploader.INSTANCE.testLogin(getActivity());
- return false;
- });
+ for (PluginBase plugin : MainApp.getPluginsList()) {
+ plugin.preprocessPreferences(this);
+ }
}
@Override
@@ -228,9 +206,5 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre
super.onSaveInstanceState(outState);
outState.putInt("id", id);
}
-
- public Preference getPreference(String key) {
- return findPreference(key);
- }
}
}
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/db/CareportalEvent.java b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
index 40fadff684..1c33e8f1be 100644
--- a/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
+++ b/app/src/main/java/info/nightscout/androidaps/db/CareportalEvent.java
@@ -100,8 +100,8 @@ public class CareportalEvent implements DataPointWithLabelInterface, Interval {
String hours = " " + MainApp.gs(R.string.hours) + " ";
if (useShortText) {
- days = "d";
- hours = "h";
+ days = MainApp.gs(R.string.shortday);
+ hours = MainApp.gs(R.string.shorthour);
}
return diff.get(TimeUnit.DAYS) + days + diff.get(TimeUnit.HOURS) + hours;
diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java
index 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/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..8de88e1e0e 100644
--- a/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
+++ b/app/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.java
@@ -1,24 +1,26 @@
package info.nightscout.androidaps.interfaces;
import android.os.SystemClock;
+import android.preference.Preference;
+import android.preference.PreferenceFragment;
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.jetbrains.annotations.NotNull;
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 +83,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();
}
@@ -216,4 +218,10 @@ public abstract class PluginBase {
protected void onStateChange(PluginType type, State oldState, State newState) {
}
+
+ public void preprocessPreferences(@NotNull final PreferenceFragment preferenceFragment) {
+ }
+
+ public void updatePreferenceSummary(@NotNull final Preference pref) {
+ }
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
index b3b0c091d5..7e568af2d9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.java
@@ -247,7 +247,7 @@ public class APSResult {
}
}
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return array;
}
@@ -280,7 +280,7 @@ public class APSResult {
}
}
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return latest;
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/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
index ef31ad599e..65db6e440c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java
@@ -164,7 +164,7 @@ public class OpenAPSAMAPlugin extends PluginBase implements APSInterface {
return;
if (!HardLimits.checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return;
- if (!HardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.05, HardLimits.maxBasal()))
+ if (!HardLimits.checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
return;
if (!HardLimits.checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
index 899c0151d8..8cac8b87cc 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSMA/OpenAPSMAPlugin.java
@@ -162,7 +162,7 @@ public class OpenAPSMAPlugin extends PluginBase implements APSInterface {
return;
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return;
- if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.05, HardLimits.maxBasal()))
+ if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
index d410eba291..c27a3f2059 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java
@@ -170,7 +170,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr
return;
if (!checkOnlyHardLimits(Profile.toMgdl(profile.getIsf(), units), "sens", HardLimits.MINISF, HardLimits.MAXISF))
return;
- if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.05, HardLimits.maxBasal()))
+ if (!checkOnlyHardLimits(profile.getMaxDailyBasal(), "max_daily_basal", 0.02, HardLimits.maxBasal()))
return;
if (!checkOnlyHardLimits(pump.getBaseBasalRate(), "current_basal", 0.01, HardLimits.maxBasal()))
return;
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/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/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..91c20b095a 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,19 @@ 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.DateUtil;
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,61 +49,69 @@ 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() {
- return getProfileName(System.currentTimeMillis());
+ return getProfileName(System.currentTimeMillis(), true, false);
}
public String getProfileName(boolean customized) {
- return getProfileName(System.currentTimeMillis(), customized);
+ return getProfileName(System.currentTimeMillis(), customized, false);
}
- public String getProfileName(long time) {
- return getProfileName(time, true);
+ public String getProfileNameWithDuration() {
+ return getProfileName(System.currentTimeMillis(), true, true);
}
- public String getProfileName(long time, boolean customized) {
+ public String getProfileName(long time, boolean customized, boolean showRemainingTime) {
+ String profileName = MainApp.gs(R.string.noprofileselected);
+
TreatmentsInterface activeTreatments = TreatmentsPlugin.getPlugin();
ProfileInterface activeProfile = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
ProfileSwitch profileSwitch = activeTreatments.getProfileSwitchFromHistory(time);
if (profileSwitch != null) {
if (profileSwitch.profileJson != null) {
- return customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
+ profileName = customized ? profileSwitch.getCustomizedName() : profileSwitch.profileName;
} else {
ProfileStore profileStore = activeProfile.getProfile();
if (profileStore != null) {
Profile profile = profileStore.getSpecificProfile(profileSwitch.profileName);
if (profile != null)
- return profileSwitch.profileName;
+ profileName = profileSwitch.profileName;
}
}
+
+ if (showRemainingTime && profileSwitch.durationInMinutes != 0) {
+ profileName += DateUtil.untilString(profileSwitch.originalEnd());
+ }
+ return profileName;
}
- return MainApp.gs(R.string.noprofileselected);
+ return profileName;
}
public boolean isProfileValid(String from) {
@@ -171,7 +184,7 @@ public class ProfileFunctions {
profileSwitch = new ProfileSwitch();
profileSwitch.date = System.currentTimeMillis();
profileSwitch.source = Source.USER;
- profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false);
+ profileSwitch.profileName = getInstance().getProfileName(System.currentTimeMillis(), false, false);
profileSwitch.profileJson = getInstance().getProfile().getData().toString();
profileSwitch.profilePlugin = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getClass().getName();
profileSwitch.durationInMinutes = duration;
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 e026d6589d..828fa1b86f 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
@@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
public class DstHelperPlugin extends PluginBase implements ConstraintsInterface {
public static final int DISABLE_TIMEFRAME_HOURS = -3;
- public static final int WARN_PRIOR_TIMEFRAME_HOURS = 24;
+ public static final int WARN_PRIOR_TIMEFRAME_HOURS = 12;
private static Logger log = LoggerFactory.getLogger(L.CONSTRAINTS);
static DstHelperPlugin plugin = null;
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 cd6e6dff4c..5edb199c9a 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
@@ -51,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() }
@@ -105,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
}
}
@@ -208,49 +204,63 @@ class ObjectivesFragment : Fragment() {
holder.accomplished.setTextColor(-0x3e3e3f)
holder.verify.setOnClickListener {
holder.verify.visibility = View.INVISIBLE
- 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
- notifyDataSetChanged()
- scrollToCurrentObjective()
- startUpdateTimer()
+ NetworkChangeReceiver.grabNetworkStatus(context)
+ 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.requirementnotmet)
+ ToastUtils.showToastInUiThread(context, R.string.failedretrievetime)
}
- } else {
- ToastUtils.showToastInUiThread(context, R.string.failedretrievetime)
}
}
- }
- }, NetworkChangeReceiver.isConnected())
+ }, NetworkChangeReceiver.isConnected())
}
holder.start.setOnClickListener {
holder.start.visibility = View.INVISIBLE
- 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
- notifyDataSetChanged()
- scrollToCurrentObjective()
- startUpdateTimer()
- } else {
- ToastUtils.showToastInUiThread(context, R.string.failedretrievetime)
+ NetworkChangeReceiver.grabNetworkStatus(context)
+ 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())
+ }, NetworkChangeReceiver.isConnected())
}
holder.revert.setOnClickListener {
objective.accomplishedOn = 0
@@ -259,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
@@ -274,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 7913e73426..5882f84d61 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 {
@@ -105,7 +105,7 @@ object ObjectivesPlugin : PluginBase(PluginDescription()
val requestCode = SP.getString(R.string.key_objectives_request_code, "")
var url = SP.getString(R.string.key_nsclientinternal_url, "").toLowerCase()
if (!url.endsWith("\"")) url = "$url/"
- val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString()
+ @Suppress("DEPRECATION") val hashNS = Hashing.sha1().hashString(url + BuildConfig.APPLICATION_ID + "/" + requestCode, Charsets.UTF_8).toString()
if (request.equals(hashNS.substring(0, 10), ignoreCase = true)) {
SP.putLong("Objectives_" + "openloop" + "_started", DateUtil.now())
SP.putLong("Objectives_" + "openloop" + "_accomplished", DateUtil.now())
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 30ab4b500b..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)
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 b126f93673..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
@@ -230,7 +230,7 @@ public abstract class Objective {
return question;
}
- public List getOptions() {
+ public List getOptions() {
return options;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java
index 0a101dd975..017ad33a8c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java
@@ -37,6 +37,7 @@ public class Objective2 extends Objective {
);
tasks.add(new ExamTask(R.string.pumpdisconnect_label, R.string.pumpdisconnect_label,"pumpdisconnect")
.option(new Option(R.string.pumpdisconnect_letknow, true))
+ .option(new Option(R.string.pumpdisconnect_suspend, false))
.option(new Option(R.string.pumpdisconnect_dontchnage, false))
.hint(new Hint(R.string.pumpdisconnect_hint1))
);
@@ -45,6 +46,7 @@ public class Objective2 extends Objective {
.option(new Option(R.string.objectives_storeelsewhere, true))
.option(new Option(R.string.objectives_doexportonstart, false))
.option(new Option(R.string.objectives_doexportafterchange, true))
+ .option(new Option(R.string.objectives_doexportafterobjective, true))
.option(new Option(R.string.objectives_doexportafterfirtssettings, true))
.hint(new Hint(R.string.objectives_hint1))
.hint(new Hint(R.string.objectives_hint2))
@@ -65,6 +67,7 @@ public class Objective2 extends Objective {
.option(new Option(R.string.exercise_switchprofileabove100, false))
.option(new Option(R.string.exercise_stoploop, false))
.option(new Option(R.string.exercise_doitbeforestart, true))
+ .option(new Option(R.string.exercise_afterstart, true))
.hint(new Hint(R.string.exercise_hint1))
);
tasks.add(new ExamTask(R.string.suspendloop_label, R.string.suspendloop_doigetinsulin,"suspendloop")
@@ -196,6 +199,11 @@ public class Objective2 extends Objective {
.hint(new Hint(R.string.profileswitchtime_hint1))
);
+ tasks.add(new ExamTask(R.string.other_medication_label, R.string.other_medication_text,"otherMedicationWarning")
+ .option(new Option(R.string.yes, true))
+ .option(new Option(R.string.no, false))
+ );
+
for (Task task : tasks)
Collections.shuffle(((ExamTask)task).options);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/signatureVerifier/SignatureVerifier.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.java
similarity index 73%
rename from app/src/main/java/info/nightscout/androidaps/plugins/general/signatureVerifier/SignatureVerifier.java
rename to app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.java
index b0616ec35e..9c9e38bb46 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/signatureVerifier/SignatureVerifier.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.java
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.general.signatureVerifier;
+package info.nightscout.androidaps.plugins.constraints.signatureVerifier;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
@@ -42,23 +42,23 @@ import info.nightscout.androidaps.utils.SP;
* In case someone decides to leak a ready-to-use APK nonetheless, we can still disable it.
* Self-compiled APKs with privately held certificates cannot and will not be disabled.
*/
-public class SignatureVerifier extends PluginBase implements ConstraintsInterface {
+public class SignatureVerifierPlugin extends PluginBase implements ConstraintsInterface {
private static final String REVOKED_CERTS_URL = "https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/src/main/assets/revoked_certs.txt";
private static final long UPDATE_INTERVAL = TimeUnit.DAYS.toMillis(1);
- private static SignatureVerifier plugin = new SignatureVerifier();
+ private static SignatureVerifierPlugin plugin = new SignatureVerifierPlugin();
private Logger log = LoggerFactory.getLogger(L.CORE);
private final Object $lock = new Object[0];
private File revokedCertsFile;
private List revokedCerts;
- public static SignatureVerifier getPlugin() {
+ public static SignatureVerifierPlugin getPlugin() {
return plugin;
}
- private SignatureVerifier() {
+ private SignatureVerifierPlugin() {
super(new PluginDescription()
.mainType(PluginType.CONSTRAINTS)
.neverVisible(true)
@@ -124,14 +124,52 @@ public class SignatureVerifier extends PluginBase implements ConstraintsInterfac
}
}
}
- } catch (PackageManager.NameNotFoundException e) {
- log.error("Error in SignatureVerifier", e);
- } catch (NoSuchAlgorithmException e) {
- log.error("Error in SignatureVerifier", e);
+ } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
+ log.error("Error in SignatureVerifierPlugin", e);
}
return false;
}
+ public List shortHashes() {
+ List hashes = new ArrayList<>();
+ try {
+ Signature[] signatures = MainApp.instance().getPackageManager().getPackageInfo(MainApp.instance().getPackageName(), PackageManager.GET_SIGNATURES).signatures;
+ if (signatures != null) {
+ for (Signature signature : signatures) {
+ MessageDigest digest = MessageDigest.getInstance("SHA256");
+ byte[] fingerprint = digest.digest(signature.toByteArray());
+ String hash = Hex.toHexString(fingerprint);
+ log.debug("Found signature: " + hash);
+ log.debug("Found signature (short): " + singleCharMap(fingerprint));
+ hashes.add(singleCharMap(fingerprint));
+ }
+ }
+ } catch (PackageManager.NameNotFoundException | NoSuchAlgorithmException e) {
+ log.error("Error in SignatureVerifierPlugin", e);
+ }
+ return hashes;
+ }
+
+ String map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!\"§$%&/()=?,.-;:_<>|°^`´\\@€*'#+~{}[]¿¡áéíóúàèìòùöäü`ÁÉÍÓÚÀÈÌÒÙÖÄÜßÆÇÊËÎÏԌ۟æçêëîïôœûÿĆČĐŠŽćđšžñΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ\u03A2ΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρςστυφχψωϨϩϪϫϬϭϮϯϰϱϲϳϴϵ϶ϷϸϹϺϻϼϽϾϿЀЁЂЃЄЅІЇЈЉЊЋЌЍЎЏАБВГДЕЖЗ";
+
+ private String singleCharMap(byte[] array) {
+ StringBuilder sb = new StringBuilder();
+ for (byte b : array) {
+ sb.append(map.charAt(b & 0xFF));
+ }
+ return sb.toString();
+ }
+
+ public String singleCharUnMap(String shortHash) {
+ byte[] array = new byte[shortHash.length()];
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < array.length; i++) {
+ if (i != 0) sb.append(":");
+ sb.append(String.format("%02X", 0xFF & map.charAt(map.indexOf(shortHash.charAt(i)))));
+ }
+ return sb.toString();
+ }
+
private boolean shouldDownloadCerts() {
return System.currentTimeMillis() - SP.getLong(R.string.key_last_revoked_certs_check, 0L) >= UPDATE_INTERVAL;
}
@@ -153,7 +191,7 @@ public class SignatureVerifier extends PluginBase implements ConstraintsInterfac
this.revokedCerts = parseRevokedCertsFile(revokedCerts);
}
} catch (IOException e) {
- log.error("Error in SignatureVerifier", e);
+ log.error("Error in SignatureVerifierPlugin", e);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt
similarity index 97%
rename from app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerPlugin.kt
rename to app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt
index bf67426787..ee267c689e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.general.versionChecker
+package info.nightscout.androidaps.plugins.constraints.versionChecker
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtils.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt
similarity index 69%
rename from app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtils.kt
rename to app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt
index 7961b19e83..ac9724608f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtils.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt
@@ -1,4 +1,4 @@
-package info.nightscout.androidaps.plugins.general.versionChecker
+package info.nightscout.androidaps.plugins.constraints.versionChecker
import android.content.Context
import android.net.ConnectivityManager
@@ -15,21 +15,14 @@ import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
-
// check network connection
fun isConnected(): Boolean {
val connMgr = MainApp.instance().applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
-fun findVersion(file :String?): String? {
- val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
- return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
-}
-
private val log = LoggerFactory.getLogger(L.CORE)
-
fun triggerCheckVersion() {
if (!SP.contains(R.string.key_last_time_this_version_detected)) {
@@ -56,13 +49,34 @@ private fun checkVersion() = if (isConnected()) {
log.debug("Github master version no checked. No connectivity")
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
- val comparison: Int? = newVersion?.versionStrip()?.compareTo(currentVersion.versionStrip())
- when {
- comparison == null -> onVersionNotDetectable()
- comparison == 0 -> onSameVersionDetected()
- comparison > 0 -> onNewVersionDetected(currentVersion = currentVersion, newVersion = newVersion)
- else -> onOlderVersionDetected()
+
+ val newVersionElements = newVersion.toNumberList()
+ val currentVersionElements = currentVersion.toNumberList()
+
+ if (newVersionElements == null || newVersionElements.isEmpty()) {
+ onVersionNotDetectable()
+ return
}
+
+ if (currentVersionElements == null || currentVersionElements.isEmpty()) {
+ // current version scrambled?!
+ onNewVersionDetected(currentVersion, newVersion)
+ return
+ }
+
+ newVersionElements.take(3).forEachIndexed { i, newElem ->
+ val currElem: Int = currentVersionElements.getOrNull(i)
+ ?: return onNewVersionDetected(currentVersion, newVersion)
+
+ (newElem - currElem).let {
+ when {
+ it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
+ it < 0 -> return onOlderVersionDetected()
+ it == 0 -> Unit
+ }
+ }
+ }
+ onSameVersionDetected()
}
private fun onOlderVersionDetected() {
@@ -75,7 +89,7 @@ fun onSameVersionDetected() {
}
fun onVersionNotDetectable() {
- log.debug("fetch failed, ignore and smartcast to non-null")
+ log.debug("fetch failed")
}
fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
@@ -88,14 +102,25 @@ fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
}
}
+@Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.")
fun String.versionStrip() = this.mapNotNull {
when (it) {
in '0'..'9' -> it
- '.' -> it
- else -> null
+ '.' -> it
+ else -> null
}
}.joinToString(separator = "")
+fun String.numericVersionPart(): String =
+ "(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1) ?: ""
+
+fun String?.toNumberList() =
+ this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
+
+fun findVersion(file: String?): String? {
+ val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
+ return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
+}
val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java
deleted file mode 100644
index 579700be4c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.java
+++ /dev/null
@@ -1,329 +0,0 @@
-package info.nightscout.androidaps.plugins.general.actions;
-
-
-import android.app.Activity;
-import android.content.Intent;
-import android.graphics.drawable.Drawable;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.LinearLayout;
-
-import androidx.fragment.app.FragmentManager;
-
-import com.squareup.otto.Subscribe;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import info.nightscout.androidaps.Config;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.activities.HistoryBrowseActivity;
-import info.nightscout.androidaps.activities.TDDStatsActivity;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.events.EventCustomActionsChanged;
-import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.events.EventInitializationChanged;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
-import info.nightscout.androidaps.plugins.general.actions.dialogs.FillDialog;
-import info.nightscout.androidaps.plugins.general.actions.dialogs.NewExtendedBolusDialog;
-import info.nightscout.androidaps.plugins.general.actions.dialogs.NewTempBasalDialog;
-import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
-import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
-import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.SP;
-import info.nightscout.androidaps.utils.SingleClickButton;
-
-public class ActionsFragment extends SubscriberFragment implements View.OnClickListener {
-
- private View actionsFragmentView;
- private SingleClickButton profileSwitch;
- private SingleClickButton tempTarget;
- private SingleClickButton extendedBolus;
- private SingleClickButton extendedBolusCancel;
- private SingleClickButton tempBasal;
- private SingleClickButton tempBasalCancel;
- private SingleClickButton fill;
- private SingleClickButton tddStats;
- private SingleClickButton history;
-
- private Map pumpCustomActions = new HashMap<>();
- private List pumpCustomButtons = new ArrayList<>();
-
- public ActionsFragment() {
- super();
- }
-
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.actions_fragment, container, false);
-
- profileSwitch = view.findViewById(R.id.actions_profileswitch);
- tempTarget = view.findViewById(R.id.actions_temptarget);
- extendedBolus = view.findViewById(R.id.actions_extendedbolus);
- extendedBolusCancel = view.findViewById(R.id.actions_extendedbolus_cancel);
- tempBasal = view.findViewById(R.id.actions_settempbasal);
- tempBasalCancel = view.findViewById(R.id.actions_canceltempbasal);
- fill = view.findViewById(R.id.actions_fill);
- tddStats = view.findViewById(R.id.actions_tddstats);
- history = view.findViewById(R.id.actions_historybrowser);
-
- profileSwitch.setOnClickListener(this);
- tempTarget.setOnClickListener(this);
- extendedBolus.setOnClickListener(this);
- extendedBolusCancel.setOnClickListener(this);
- tempBasal.setOnClickListener(this);
- tempBasalCancel.setOnClickListener(this);
- fill.setOnClickListener(this);
- history.setOnClickListener(this);
- tddStats.setOnClickListener(this);
-
- actionsFragmentView = view;
-
- updateGUI();
- SP.putBoolean(R.string.key_objectiveuseactions, true);
- return view;
- }
-
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventCustomActionsChanged ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- if (ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null && ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() != null) {
- profileSwitch.setVisibility(View.VISIBLE);
- } else {
- profileSwitch.setVisibility(View.GONE);
- }
-
- if (ProfileFunctions.getInstance().getProfile() == null) {
- tempTarget.setVisibility(View.GONE);
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.GONE);
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.GONE);
- fill.setVisibility(View.GONE);
- return;
- }
-
- final PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- final boolean basalprofileEnabled = MainApp.isEngineeringModeOrRelease()
- && pump.getPumpDescription().isSetBasalProfileCapable;
-
- if (!basalprofileEnabled || !pump.isInitialized() || pump.isSuspended())
- profileSwitch.setVisibility(View.GONE);
- else
- profileSwitch.setVisibility(View.VISIBLE);
-
- if (!pump.getPumpDescription().isExtendedBolusCapable || !pump.isInitialized() || pump.isSuspended() || pump.isFakingTempsByExtendedBoluses()) {
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.GONE);
- } else {
- ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
- if (activeExtendedBolus != null) {
- extendedBolus.setVisibility(View.GONE);
- extendedBolusCancel.setVisibility(View.VISIBLE);
- extendedBolusCancel.setText(MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString());
- } else {
- extendedBolus.setVisibility(View.VISIBLE);
- extendedBolusCancel.setVisibility(View.GONE);
- }
- }
-
-
- if (!pump.getPumpDescription().isTempBasalCapable || !pump.isInitialized() || pump.isSuspended()) {
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.GONE);
- } else {
- final TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (activeTemp != null) {
- tempBasal.setVisibility(View.GONE);
- tempBasalCancel.setVisibility(View.VISIBLE);
- tempBasalCancel.setText(MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort());
- } else {
- tempBasal.setVisibility(View.VISIBLE);
- tempBasalCancel.setVisibility(View.GONE);
- }
- }
-
- if (!pump.getPumpDescription().isRefillingCapable || !pump.isInitialized() || pump.isSuspended())
- fill.setVisibility(View.GONE);
- else
- fill.setVisibility(View.VISIBLE);
-
- if (!Config.APS)
- tempTarget.setVisibility(View.GONE);
- else
- tempTarget.setVisibility(View.VISIBLE);
-
- if (!pump.getPumpDescription().supportsTDDs)
- tddStats.setVisibility(View.GONE);
- else
- tddStats.setVisibility(View.VISIBLE);
-
- checkPumpCustomActions();
-
- }
- });
- }
-
-
- View.OnClickListener pumpCustomActionsListener = v -> {
-
- SingleClickButton btn = (SingleClickButton) v;
-
- CustomAction customAction = this.pumpCustomActions.get(btn.getText().toString());
-
- ConfigBuilderPlugin.getPlugin().getActivePump().executeCustomAction(customAction.getCustomActionType());
-
- };
-
-
- private void checkPumpCustomActions() {
-
- PumpInterface activePump = ConfigBuilderPlugin.getPlugin().getActivePump();
-
- removePumpCustomActions();
-
- if (activePump == null) {
- return;
- }
-
- List customActions = activePump.getCustomActions();
-
- if (customActions != null && customActions.size() > 0) {
-
- LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout);
-
- for (CustomAction customAction : customActions) {
-
- if (!customAction.isEnabled())
- continue;
-
- SingleClickButton btn = new SingleClickButton(getContext(), null, android.R.attr.buttonStyle);
- btn.setText(MainApp.gs(customAction.getName()));
-
- LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
- LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f);
- layoutParams.setMargins(20, 8, 20, 8); // 10,3,10,3
-
- btn.setLayoutParams(layoutParams);
- btn.setOnClickListener(pumpCustomActionsListener);
-
- Drawable top = getResources().getDrawable(customAction.getIconResourceId());
- btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
-
- ll.addView(btn);
-
- this.pumpCustomActions.put(MainApp.gs(customAction.getName()), customAction);
- this.pumpCustomButtons.add(btn);
- }
- }
- }
-
-
- private void removePumpCustomActions() {
-
- if (pumpCustomActions.size() == 0)
- return;
-
- LinearLayout ll = actionsFragmentView.findViewById(R.id.action_buttons_layout);
-
- for (SingleClickButton customButton : pumpCustomButtons) {
- ll.removeView(customButton);
- }
-
- pumpCustomButtons.clear();
- }
-
-
- @Override
- public void onClick(View view) {
- FragmentManager manager = getFragmentManager();
- switch (view.getId()) {
- case R.id.actions_profileswitch:
- NewNSTreatmentDialog newDialog = new NewNSTreatmentDialog();
- final OptionsToShow profileswitch = CareportalFragment.PROFILESWITCH;
- profileswitch.executeProfileSwitch = true;
- newDialog.setOptions(profileswitch, R.string.careportal_profileswitch);
- newDialog.show(manager, "NewNSTreatmentDialog");
- break;
- case R.id.actions_temptarget:
- NewNSTreatmentDialog newTTDialog = new NewNSTreatmentDialog();
- final OptionsToShow temptarget = CareportalFragment.TEMPTARGET;
- temptarget.executeTempTarget = true;
- newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget);
- newTTDialog.show(manager, "NewNSTreatmentDialog");
- break;
- case R.id.actions_extendedbolus:
- NewExtendedBolusDialog newExtendedDialog = new NewExtendedBolusDialog();
- newExtendedDialog.show(manager, "NewExtendedDialog");
- break;
- case R.id.actions_extendedbolus_cancel:
- if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(null);
- }
- break;
- case R.id.actions_canceltempbasal:
- if (TreatmentsPlugin.getPlugin().isTempBasalInProgress()) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, null);
- }
- break;
- case R.id.actions_settempbasal:
- NewTempBasalDialog newTempDialog = new NewTempBasalDialog();
- newTempDialog.show(manager, "NewTempDialog");
- break;
- case R.id.actions_fill:
- FillDialog fillDialog = new FillDialog();
- fillDialog.show(manager, "FillDialog");
- break;
- case R.id.actions_historybrowser:
- startActivity(new Intent(getContext(), HistoryBrowseActivity.class));
- break;
- case R.id.actions_tddstats:
- startActivity(new Intent(getContext(), TDDStatsActivity.class));
- break;
- }
- }
-}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt
new file mode 100644
index 0000000000..dfc06e6156
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt
@@ -0,0 +1,242 @@
+package info.nightscout.androidaps.plugins.general.actions
+
+
+import android.content.Intent
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.LinearLayout
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.Config
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.activities.HistoryBrowseActivity
+import info.nightscout.androidaps.activities.TDDStatsActivity
+import info.nightscout.androidaps.events.*
+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.actions.defs.CustomAction
+import info.nightscout.androidaps.plugins.general.actions.dialogs.FillDialog
+import info.nightscout.androidaps.plugins.general.actions.dialogs.NewExtendedBolusDialog
+import info.nightscout.androidaps.plugins.general.actions.dialogs.NewTempBasalDialog
+import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment
+import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
+import info.nightscout.androidaps.queue.Callback
+import info.nightscout.androidaps.utils.*
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.actions_fragment.*
+import java.util.*
+
+class ActionsFragment : Fragment() {
+
+ private var disposable: CompositeDisposable = CompositeDisposable()
+
+ private val pumpCustomActions = HashMap()
+ private val pumpCustomButtons = ArrayList()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.actions_fragment, container, false)
+ }
+
+ override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
+ super.onViewCreated(view, savedInstanceState)
+
+ actions_profileswitch.setOnClickListener {
+ val newDialog = NewNSTreatmentDialog()
+ val profileSwitch = CareportalFragment.PROFILESWITCH
+ profileSwitch.executeProfileSwitch = true
+ newDialog.setOptions(profileSwitch, R.string.careportal_profileswitch)
+ fragmentManager?.let { newDialog.show(it, "NewNSTreatmentDialog") }
+ }
+ actions_temptarget.setOnClickListener {
+ val newTTDialog = NewNSTreatmentDialog()
+ val temptarget = CareportalFragment.TEMPTARGET
+ temptarget.executeTempTarget = true
+ newTTDialog.setOptions(temptarget, R.string.careportal_temporarytarget)
+ fragmentManager?.let { newTTDialog.show(it, "NewNSTreatmentDialog") }
+ }
+ actions_extendedbolus.setOnClickListener {
+ fragmentManager?.let { NewExtendedBolusDialog().show(it, "NewExtendedDialog") }
+ }
+ actions_extendedbolus_cancel.setOnClickListener {
+ if (TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress) {
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelExtended(object : Callback() {
+ override fun run() {
+ if (!result.success)
+ ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.extendedbolusdeliveryerror))
+ }
+ })
+ }
+ }
+ actions_settempbasal.setOnClickListener { fragmentManager?.let { NewTempBasalDialog().show(it, "NewTempDialog") } }
+ actions_canceltempbasal.setOnClickListener {
+ if (TreatmentsPlugin.getPlugin().isTempBasalInProgress) {
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() {
+ override fun run() {
+ if (!result.success)
+ ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.tempbasaldeliveryerror))
+ }
+ })
+ }
+ }
+ actions_fill.setOnClickListener { fragmentManager?.let { FillDialog().show(it, "FillDialog") } }
+ actions_historybrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) }
+ actions_tddstats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) }
+
+ SP.putBoolean(R.string.key_objectiveuseactions, true)
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+ disposable += RxBus
+ .toObservable(EventInitializationChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGui()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventRefreshOverview::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGui()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventExtendedBolusChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGui()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventTempBasalChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGui()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ disposable += RxBus
+ .toObservable(EventCustomActionsChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ updateGui()
+ }, {
+ FabricPrivacy.logException(it)
+ })
+ updateGui()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ @Synchronized
+ fun updateGui() {
+ actions_profileswitch?.visibility =
+ if (ConfigBuilderPlugin.getPlugin().activeProfileInterface?.profile != null) View.VISIBLE
+ else View.GONE
+
+ if (ProfileFunctions.getInstance().profile == null) {
+ actions_temptarget?.visibility = View.GONE
+ actions_extendedbolus?.visibility = View.GONE
+ actions_extendedbolus_cancel?.visibility = View.GONE
+ actions_settempbasal?.visibility = View.GONE
+ actions_canceltempbasal?.visibility = View.GONE
+ actions_fill?.visibility = View.GONE
+ return
+ }
+
+ val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return
+ val basalProfileEnabled = MainApp.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable
+
+ actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE
+
+ if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized || pump.isSuspended || pump.isFakingTempsByExtendedBoluses || Config.APS) {
+ actions_extendedbolus?.visibility = View.GONE
+ actions_extendedbolus_cancel?.visibility = View.GONE
+ } else {
+ val activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis())
+ if (activeExtendedBolus != null) {
+ actions_extendedbolus?.visibility = View.GONE
+ actions_extendedbolus_cancel?.visibility = View.VISIBLE
+ actions_extendedbolus_cancel?.text = MainApp.gs(R.string.cancel) + " " + activeExtendedBolus.toString()
+ } else {
+ actions_extendedbolus?.visibility = View.VISIBLE
+ actions_extendedbolus_cancel?.visibility = View.GONE
+ }
+ }
+
+ if (!pump.pumpDescription.isTempBasalCapable || !pump.isInitialized || pump.isSuspended) {
+ actions_settempbasal?.visibility = View.GONE
+ actions_canceltempbasal?.visibility = View.GONE
+ } else {
+ val activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis())
+ if (activeTemp != null) {
+ actions_settempbasal?.visibility = View.GONE
+ actions_canceltempbasal?.visibility = View.VISIBLE
+ actions_canceltempbasal?.text = MainApp.gs(R.string.cancel) + " " + activeTemp.toStringShort()
+ } else {
+ actions_settempbasal?.visibility = View.VISIBLE
+ actions_canceltempbasal?.visibility = View.GONE
+ }
+ }
+
+ actions_fill?.visibility =
+ if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE
+ else View.VISIBLE
+
+ actions_temptarget?.visibility = if (!Config.APS) View.GONE else View.VISIBLE
+ actions_tddstats?.visibility = if (!pump.pumpDescription.supportsTDDs) View.GONE else View.VISIBLE
+ checkPumpCustomActions()
+ }
+
+ private fun checkPumpCustomActions() {
+ val activePump = ConfigBuilderPlugin.getPlugin().activePump ?: return
+ val customActions = activePump.customActions ?: return
+ removePumpCustomActions()
+
+ for (customAction in customActions) {
+ if (!customAction.isEnabled) continue
+
+ val btn = SingleClickButton(context, null, android.R.attr.buttonStyle)
+ btn.text = MainApp.gs(customAction.name)
+
+ val layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.5f)
+ layoutParams.setMargins(20, 8, 20, 8) // 10,3,10,3
+
+ btn.layoutParams = layoutParams
+ btn.setOnClickListener { v ->
+ val b = v as SingleClickButton
+ val action = this.pumpCustomActions[b.text.toString()]
+ ConfigBuilderPlugin.getPlugin().activePump!!.executeCustomAction(action!!.customActionType)
+ }
+
+ val top = resources.getDrawable(customAction.iconResourceId)
+ btn.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null)
+
+ action_buttons_layout?.addView(btn)
+
+ this.pumpCustomActions[MainApp.gs(customAction.name)] = customAction
+ this.pumpCustomButtons.add(btn)
+ }
+ }
+
+ private fun removePumpCustomActions() {
+ for (customButton in pumpCustomButtons) action_buttons_layout?.removeView(customButton)
+ pumpCustomButtons.clear()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt
index 086c75a157..04afb826a2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt
@@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.PluginType
object ActionsPlugin : PluginBase(PluginDescription()
.mainType(PluginType.GENERAL)
- .fragmentClass(ActionsFragment::class.java.name)
+ .fragmentClass(ActionsFragment::class.qualifiedName)
.pluginName(R.string.actions)
.shortName(R.string.actions_shortname)
.description(R.string.description_actions))
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.java
index 6eb3be382b..4f7bb62c74 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationEvent.java
@@ -10,8 +10,11 @@ import java.util.List;
import info.nightscout.androidaps.plugins.general.automation.actions.Action;
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger;
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class AutomationEvent {
+ private static final Logger log = LoggerFactory.getLogger(AutomationEvent.class);
private Trigger trigger = new TriggerConnector();
private List actions = new ArrayList<>();
@@ -74,7 +77,7 @@ public class AutomationEvent {
}
o.put("actions", array);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -91,7 +94,7 @@ public class AutomationEvent {
actions.add(Action.instantiate(new JSONObject(array.getString(i))));
}
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt
index 8b6ffb1720..d1135c21ed 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt
@@ -29,7 +29,7 @@ class AutomationFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
- eventListAdapter = EventListAdapter(AutomationPlugin.automationEvents, fragmentManager)
+ eventListAdapter = EventListAdapter(AutomationPlugin.automationEvents, fragmentManager, activity)
automation_eventListView.layoutManager = LinearLayoutManager(context)
automation_eventListView.adapter = eventListAdapter
@@ -74,14 +74,11 @@ class AutomationFragment : Fragment() {
@Synchronized
private fun updateGui() {
- if (eventListAdapter == null) return
eventListAdapter?.notifyDataSetChanged()
val sb = StringBuilder()
- for (l in AutomationPlugin.executionLog.reversed()) {
- sb.append(l)
- sb.append("\n")
- }
- automation_logView.text = sb.toString()
+ for (l in AutomationPlugin.executionLog.reversed())
+ sb.append(l).append("\n")
+ automation_logView?.text = sb.toString()
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt
index 02f5bf5e87..8b78ae6458 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt
@@ -13,6 +13,7 @@ import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.automation.actions.*
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged
@@ -160,11 +161,16 @@ object AutomationPlugin : PluginBase(PluginDescription()
private fun processActions() {
if (!isEnabled(PluginType.GENERAL))
return
+ if (LoopPlugin.getPlugin().isSuspended) {
+ if (L.isEnabled(L.AUTOMATION))
+ log.debug("Loop deactivated")
+ return
+ }
if (L.isEnabled(L.AUTOMATION))
log.debug("processActions")
for (event in automationEvents) {
- if (event.isEnabled() && event.trigger.shouldRun() && event.preconditions.shouldRun()) {
+ if (event.isEnabled && event.trigger.shouldRun() && event.preconditions.shouldRun()) {
val actions = event.actions
for (action in actions) {
action.doAction(object : Callback() {
@@ -221,7 +227,8 @@ object AutomationPlugin : PluginBase(PluginDescription()
TriggerWifiSsid(),
TriggerLocation(),
TriggerAutosensValue(),
- TriggerBolusAgo()
+ TriggerBolusAgo(),
+ TriggerPumpLastConnection()
)
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/EventListAdapter.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/EventListAdapter.java
index ec1cac23d6..08079a9110 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/EventListAdapter.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/EventListAdapter.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation;
+import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -26,14 +27,17 @@ import info.nightscout.androidaps.plugins.general.automation.actions.Action;
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog;
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationDataChanged;
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector;
+import info.nightscout.androidaps.utils.OKDialog;
class EventListAdapter extends RecyclerView.Adapter {
- private final List mEventList;
- private final FragmentManager mFragmentManager;
+ private final List eventList;
+ private final FragmentManager fragmentManager;
+ private final Activity activity;
- EventListAdapter(List events, FragmentManager fragmentManager) {
- this.mEventList = events;
- this.mFragmentManager = fragmentManager;
+ EventListAdapter(List events, FragmentManager fragmentManager, Activity activity) {
+ this.eventList = events;
+ this.fragmentManager = fragmentManager;
+ this.activity = activity;
}
@NonNull
@@ -52,7 +56,7 @@ class EventListAdapter extends RecyclerView.Adapter
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
- final AutomationEvent event = mEventList.get(position);
+ final AutomationEvent event = eventList.get(position);
holder.eventTitle.setText(event.getTitle());
holder.enabled.setChecked(event.isEnabled());
holder.iconLayout.removeAllViews();
@@ -82,16 +86,18 @@ class EventListAdapter extends RecyclerView.Adapter
}
// enabled event
- holder.enabled.setOnCheckedChangeListener((buttonView, isChecked) -> {
- event.setEnabled(isChecked);
+ holder.enabled.setOnClickListener(v -> {
+ event.setEnabled((holder.enabled.isChecked()));
RxBus.INSTANCE.send(new EventAutomationDataChanged());
});
// remove event
- holder.iconTrash.setOnClickListener(v -> {
- mEventList.remove(event);
- RxBus.INSTANCE.send(new EventAutomationDataChanged());
- });
+ holder.iconTrash.setOnClickListener(v ->
+ OKDialog.showConfirmation(activity, MainApp.gs(R.string.removerecord) + " " + event.getTitle(), () -> {
+ eventList.remove(event);
+ RxBus.INSTANCE.send(new EventAutomationDataChanged());
+ })
+ );
// edit event
holder.rootLayout.setOnClickListener(v -> {
@@ -101,14 +107,14 @@ class EventListAdapter extends RecyclerView.Adapter
args.putString("event", event.toJSON());
args.putInt("position", position);
dialog.setArguments(args);
- if (mFragmentManager != null)
- dialog.show(mFragmentManager, "EditEventDialog");
+ if (fragmentManager != null)
+ dialog.show(fragmentManager, "EditEventDialog");
});
}
@Override
public int getItemCount() {
- return mEventList.size();
+ return eventList.size();
}
static class ViewHolder extends RecyclerView.ViewHolder {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.java
index 796f023f1d..ee4564fd6f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.java
@@ -11,6 +11,8 @@ import javax.annotation.Nullable;
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger;
import info.nightscout.androidaps.queue.Callback;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/*
Action ideas:
@@ -44,6 +46,7 @@ import info.nightscout.androidaps.queue.Callback;
public abstract class Action {
+ private static final Logger log = LoggerFactory.getLogger(Action.class);
public Trigger precondition = null;
@@ -65,7 +68,7 @@ public abstract class Action {
try {
o.put("type", this.getClass().getName());
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -84,7 +87,7 @@ public abstract class Action {
Class clazz = Class.forName(type);
return ((Action) clazz.newInstance()).fromJSON(data != null ? data.toString() : "");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return null;
}
@@ -98,7 +101,7 @@ public abstract class Action {
fromJSON(data.toString());
}
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.java
index bd221d8f81..39adbcac27 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspend.java
@@ -18,8 +18,12 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ActionLoopSuspend extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionLoopSuspend.class);
+
public InputDuration minutes = new InputDuration(0, InputDuration.TimeUnit.MINUTES);
@Override
@@ -59,7 +63,7 @@ public class ActionLoopSuspend extends Action {
o.put("type", this.getClass().getName());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -70,7 +74,7 @@ public class ActionLoopSuspend extends Action {
JSONObject o = new JSONObject(data);
minutes.setMinutes(JsonHelper.safeGetInt(o, "minutes"));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.java
index 1f7ad543c2..7bd501b460 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.java
@@ -20,8 +20,12 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ActionNotification extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionNotification.class);
+
public InputString text = new InputString();
@Override
@@ -59,7 +63,7 @@ public class ActionNotification extends Action {
o.put("type", this.getClass().getName());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -70,7 +74,7 @@ public class ActionNotification extends Action {
JSONObject o = new JSONObject(data);
text.setValue(JsonHelper.safeGetString(o, "text"));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java
index 50fbb786db..8a4762bd08 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.java
@@ -92,7 +92,7 @@ public class ActionProfileSwitch extends Action {
data.put("profileToSwitchTo", inputProfileName.getValue());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -105,7 +105,7 @@ public class ActionProfileSwitch extends Action {
profileName = JsonHelper.safeGetString(d, "profileToSwitchTo");
inputProfileName.setValue(profileName);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java
index 20b6abb081..23b54640a5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.java
@@ -19,8 +19,12 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuil
import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerProfilePercent;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ActionProfileSwitchPercent extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionProfileSwitchPercent.class);
+
InputPercent pct = new InputPercent();
InputDuration duration = new InputDuration(0, InputDuration.TimeUnit.MINUTES);
@@ -71,7 +75,7 @@ public class ActionProfileSwitchPercent extends Action {
data.put("durationInMinutes", duration.getMinutes());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -83,7 +87,7 @@ public class ActionProfileSwitchPercent extends Action {
pct.setValue(JsonHelper.safeGetInt(d, "percentage"));
duration.setMinutes(JsonHelper.safeGetInt(d, "durationInMinutes"));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java
index f8afafca75..fa9140e5f9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.java
@@ -21,6 +21,7 @@ import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.JsonHelper;
public class ActionSendSMS extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionSendSMS.class);
public InputString text = new InputString();
@@ -36,7 +37,7 @@ public class ActionSendSMS extends Action {
@Override
public void doAction(Callback callback) {
- boolean result = SmsCommunicatorPlugin.getPlugin().sendNotificationToAllNumbers(text.getValue());
+ boolean result = SmsCommunicatorPlugin.INSTANCE.sendNotificationToAllNumbers(text.getValue());
if (callback != null)
callback.result(new PumpEnactResult().success(result).comment(result ? R.string.ok : R.string.danar_error)).run();
@@ -56,7 +57,7 @@ public class ActionSendSMS extends Action {
o.put("type", this.getClass().getName());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -67,7 +68,7 @@ public class ActionSendSMS extends Action {
JSONObject o = new JSONObject(data);
text.setValue(JsonHelper.safeGetString(o, "text"));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.java
index 659bb508eb..b0ef645069 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.java
@@ -24,8 +24,12 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.JsonHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ActionStartTempTarget extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionStartTempTarget.class);
+
String reason = "";
InputTempTarget value = new InputTempTarget();
InputDuration duration = new InputDuration(0, InputDuration.TimeUnit.MINUTES);
@@ -93,7 +97,7 @@ public class ActionStartTempTarget extends Action {
data.put("durationInMinutes", duration.getMinutes());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -107,7 +111,7 @@ public class ActionStartTempTarget extends Action {
value.setValue(JsonHelper.safeGetDouble(d, "value"));
duration.setMinutes(JsonHelper.safeGetInt(d, "durationInMinutes"));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.java
index de251c499e..abf354bc9c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStopTempTarget.java
@@ -14,8 +14,12 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.JsonHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class ActionStopTempTarget extends Action {
+ private static final Logger log = LoggerFactory.getLogger(ActionStopTempTarget.class);
+
String reason = "";
private TempTarget tempTarget;
@@ -54,7 +58,7 @@ public class ActionStopTempTarget extends Action {
data.put("reason", reason);
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -65,7 +69,7 @@ public class ActionStopTempTarget extends Action {
JSONObject d = new JSONObject(data);
reason = JsonHelper.safeGetString(d, "reason");
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.java
index f6ba6b6f67..69ac67bf07 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.java
@@ -13,10 +13,13 @@ import com.google.common.base.Optional;
import org.json.JSONException;
import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
public abstract class Trigger {
+ private static final Logger log = LoggerFactory.getLogger(Trigger.class);
TriggerConnector connector = null;
long lastRun;
@@ -56,7 +59,7 @@ public abstract class Trigger {
try {
return instantiate(new JSONObject(json));
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return null;
}
@@ -69,7 +72,7 @@ public abstract class Trigger {
Class clazz = Class.forName(type);
return ((Trigger) clazz.newInstance()).fromJSON(data.toString());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return null;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.java
index da850b187d..ce0a8f63bb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.java
@@ -89,7 +89,7 @@ public class TriggerAutosensValue extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -102,7 +102,7 @@ public class TriggerAutosensValue extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.java
index 1636377bf2..3733859b96 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.java
@@ -104,7 +104,7 @@ public class TriggerBg extends Trigger {
data.put("units", bg.getUnits());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -118,7 +118,7 @@ public class TriggerBg extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.java
index 0ad9f75ab2..0a038112e2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.java
@@ -86,7 +86,7 @@ public class TriggerBolusAgo extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -99,7 +99,7 @@ public class TriggerBolusAgo extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.java
index 4ddeb4299a..bf17dc72d1 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.java
@@ -87,7 +87,7 @@ public class TriggerCOB extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -100,7 +100,7 @@ public class TriggerCOB extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.java
index ae4bd35ad5..549925528a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.java
@@ -162,7 +162,7 @@ public class TriggerConnector extends Trigger {
data.put("triggerList", array);
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -179,7 +179,7 @@ public class TriggerConnector extends Trigger {
add(newItem);
}
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.java
index a3939a60b7..eee649307b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.java
@@ -129,7 +129,7 @@ public class TriggerDelta extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -144,7 +144,7 @@ public class TriggerDelta extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.java
index c4003af861..a3935d7cec 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIob.java
@@ -82,7 +82,7 @@ public class TriggerIob extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -95,7 +95,7 @@ public class TriggerIob extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.java
index 4772d29112..19965cfc9a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.java
@@ -93,7 +93,7 @@ public class TriggerLocation extends Trigger {
data.put("lastRun", lastRun);
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -108,7 +108,7 @@ public class TriggerLocation extends Trigger {
name.setValue(JsonHelper.safeGetString(d, "name"));
lastRun = JsonHelper.safeGetLong(d, "lastRun");
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.java
index d86bc35cb8..e4c0ae4346 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.java
@@ -88,7 +88,7 @@ public class TriggerProfilePercent extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -101,7 +101,7 @@ public class TriggerProfilePercent extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.java
new file mode 100644
index 0000000000..ff8bb335f9
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.java
@@ -0,0 +1,146 @@
+package info.nightscout.androidaps.plugins.general.automation.triggers;
+
+import android.widget.LinearLayout;
+
+import androidx.fragment.app.FragmentManager;
+
+import com.google.common.base.Optional;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.general.automation.elements.Comparator;
+import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration;
+import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement;
+import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder;
+import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel;
+import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.JsonHelper;
+import info.nightscout.androidaps.utils.T;
+
+public class TriggerPumpLastConnection extends Trigger {
+ private static Logger log = LoggerFactory.getLogger(L.AUTOMATION);
+ private InputDuration minutesAgo = new InputDuration(0, InputDuration.TimeUnit.MINUTES);
+ private Comparator comparator = new Comparator();
+
+ public TriggerPumpLastConnection() {
+ super();
+ }
+
+ private TriggerPumpLastConnection(TriggerPumpLastConnection triggerPumpLastConnection) {
+ super();
+ minutesAgo = new InputDuration(triggerPumpLastConnection.minutesAgo);
+ lastRun = triggerPumpLastConnection.lastRun;
+ comparator = new Comparator(triggerPumpLastConnection.comparator);
+ }
+
+ public double getValue() {
+ return minutesAgo.getValue();
+ }
+
+ public Comparator getComparator() {
+ return comparator;
+ }
+
+ @Override
+ public synchronized boolean shouldRun() {
+
+ if (lastRun > DateUtil.now() - T.mins(5).msecs())
+ return false;
+ long lastConnection = ConfigBuilderPlugin.getPlugin().getActivePump().lastDataTime();
+
+ if (lastConnection == 0 && comparator.getValue() == Comparator.Compare.IS_NOT_AVAILABLE)
+ return true;
+
+ double minutesAgo = (double) (DateUtil.now() - lastConnection) / (60 * 1000);
+ if (L.isEnabled(L.AUTOMATION))
+ log.debug("Last connection min ago: " + minutesAgo);
+
+ boolean doRun = comparator.getValue().check((minutesAgo), getValue());
+ if (doRun) {
+ if (L.isEnabled(L.AUTOMATION))
+ log.debug("Ready for execution: " + friendlyDescription());
+ return true;
+ }
+ return false;
+ }
+
+ @Override
+ public synchronized String toJSON() {
+ JSONObject o = new JSONObject();
+ try {
+ o.put("type", TriggerPumpLastConnection.class.getName());
+ JSONObject data = new JSONObject();
+ data.put("minutesAgo", getValue());
+ data.put("lastRun", lastRun);
+ data.put("comparator", comparator.getValue().toString());
+ o.put("data", data);
+ } catch (JSONException e) {
+ log.error("Unhandled exception", e);
+ }
+ return o.toString();
+ }
+
+ @Override
+ Trigger fromJSON(String data) {
+ try {
+ JSONObject d = new JSONObject(data);
+ minutesAgo.setMinutes(JsonHelper.safeGetInt(d, "minutesAgo"));
+ lastRun = JsonHelper.safeGetLong(d, "lastRun");
+ comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
+ } catch (Exception e) {
+ log.error("Unhandled exception", e);
+ }
+ return this;
+ }
+
+ @Override
+ public int friendlyName() {
+ return R.string.automation_trigger_pump_last_connection_label;
+ }
+
+ @Override
+ public String friendlyDescription() {
+ return MainApp.gs(R.string.automation_trigger_pump_last_connection_compared, MainApp.gs(comparator.getValue().getStringRes()), (int) getValue());
+ }
+
+ @Override
+ public Optional icon() {
+ return Optional.of(R.drawable.remove);
+ }
+
+ @Override
+ public Trigger duplicate() {
+ return new TriggerPumpLastConnection(this);
+ }
+
+ TriggerPumpLastConnection setValue(int requestedValue) {
+ this.minutesAgo.setMinutes(requestedValue);
+ return this;
+ }
+
+ TriggerPumpLastConnection lastRun(long lastRun) {
+ this.lastRun = lastRun;
+ return this;
+ }
+
+ TriggerPumpLastConnection comparator(Comparator.Compare compare) {
+ this.comparator = new Comparator().setValue(compare);
+ return this;
+ }
+
+ @Override
+ public void generateDialog(LinearLayout root, FragmentManager fragmentManager) {
+ new LayoutBuilder()
+ .add(new StaticLabel(R.string.automation_trigger_pump_last_connection_label))
+ .add(comparator)
+ .add(new LabelWithElement(MainApp.gs(R.string.automation_trigger_pump_last_connection_description) + ": ", "", minutesAgo))
+ .build(root);
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.java
index a145253b36..89c8d17085 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.java
@@ -163,7 +163,7 @@ public class TriggerRecurringTime extends Trigger {
object.put("type", TriggerRecurringTime.class.getName());
object.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return object.toString();
}
@@ -181,7 +181,7 @@ public class TriggerRecurringTime extends Trigger {
minute = JsonHelper.safeGetInt(o, "minute");
validTo = JsonHelper.safeGetLong(o, "validTo");
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.java
index 378652ed2a..f45efdf4a4 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.java
@@ -74,7 +74,7 @@ public class TriggerTempTarget extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -86,7 +86,7 @@ public class TriggerTempTarget extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(ComparatorExists.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.java
index 261783b99c..08f9a65aa7 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.java
@@ -65,7 +65,7 @@ public class TriggerTime extends Trigger {
object.put("type", TriggerTime.class.getName());
object.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return object.toString();
}
@@ -78,7 +78,7 @@ public class TriggerTime extends Trigger {
lastRun = JsonHelper.safeGetLong(o, "lastRun");
runAt = JsonHelper.safeGetLong(o, "runAt");
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.java
index 8755c3559c..1d03871620 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.java
@@ -93,7 +93,7 @@ public class TriggerTimeRange extends Trigger {
object.put("type", TriggerTimeRange.class.getName());
object.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
log.debug(object.toString());
return object.toString();
@@ -108,7 +108,7 @@ public class TriggerTimeRange extends Trigger {
start = JsonHelper.safeGetInt(o, "start");
end = JsonHelper.safeGetInt(o, "end");
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java
index 84094095d5..dd2c34bcb8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.java
@@ -59,13 +59,13 @@ public class TriggerWifiSsid extends Trigger {
if (lastRun > DateUtil.now() - T.mins(5).msecs())
return false;
- if (!eventNetworkChange.wifiConnected && comparator.getValue() == Comparator.Compare.IS_NOT_AVAILABLE) {
+ if (!eventNetworkChange.getWifiConnected() && comparator.getValue() == Comparator.Compare.IS_NOT_AVAILABLE) {
if (L.isEnabled(L.AUTOMATION))
log.debug("Ready for execution: " + friendlyDescription());
return true;
}
- boolean doRun = eventNetworkChange.wifiConnected && comparator.getValue().check(eventNetworkChange.getSsid(), getValue());
+ boolean doRun = eventNetworkChange.getWifiConnected() && comparator.getValue().check(eventNetworkChange.connectedSsid(), getValue());
if (doRun) {
if (L.isEnabled(L.AUTOMATION))
log.debug("Ready for execution: " + friendlyDescription());
@@ -85,7 +85,7 @@ public class TriggerWifiSsid extends Trigger {
data.put("comparator", comparator.getValue().toString());
o.put("data", data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return o.toString();
}
@@ -98,7 +98,7 @@ public class TriggerWifiSsid extends Trigger {
lastRun = JsonHelper.safeGetLong(d, "lastRun");
comparator.setValue(Comparator.Compare.valueOf(JsonHelper.safeGetString(d, "comparator")));
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return this;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java
index c7f6e1bf64..42ae7fd6fc 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.java
@@ -4,14 +4,14 @@ package info.nightscout.androidaps.plugins.general.careportal;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
-import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -22,19 +22,18 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventCareportalEventChange;
-import info.nightscout.androidaps.interfaces.PumpInterface;
-import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus;
import info.nightscout.androidaps.plugins.general.overview.OverviewFragment;
-import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.FabricPrivacy;
-import info.nightscout.androidaps.utils.SP;
-import info.nightscout.androidaps.utils.SetWarnColor;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class CareportalFragment extends SubscriberFragment implements View.OnClickListener {
+public class CareportalFragment extends Fragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(CareportalFragment.class);
+ private CompositeDisposable disposable = new CompositeDisposable();
TextView iage;
TextView cage;
@@ -71,59 +70,69 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.careportal_fragment, container, false);
+ View view = inflater.inflate(R.layout.careportal_fragment, container, false);
- view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this);
- view.findViewById(R.id.careportal_announcement).setOnClickListener(this);
- view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this);
- view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this);
- view.findViewById(R.id.careportal_combobolus).setOnClickListener(this);
- view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this);
- view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this);
- view.findViewById(R.id.careportal_exercise).setOnClickListener(this);
- view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this);
- view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this);
- view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this);
- view.findViewById(R.id.careportal_note).setOnClickListener(this);
- view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this);
- view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this);
- view.findViewById(R.id.careportal_question).setOnClickListener(this);
- view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this);
- view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this);
- view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this);
- view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this);
- view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this);
+ view.findViewById(R.id.careportal_bgcheck).setOnClickListener(this);
+ view.findViewById(R.id.careportal_announcement).setOnClickListener(this);
+ view.findViewById(R.id.careportal_cgmsensorinsert).setOnClickListener(this);
+ view.findViewById(R.id.careportal_cgmsensorstart).setOnClickListener(this);
+ view.findViewById(R.id.careportal_combobolus).setOnClickListener(this);
+ view.findViewById(R.id.careportal_correctionbolus).setOnClickListener(this);
+ view.findViewById(R.id.careportal_carbscorrection).setOnClickListener(this);
+ view.findViewById(R.id.careportal_exercise).setOnClickListener(this);
+ view.findViewById(R.id.careportal_insulincartridgechange).setOnClickListener(this);
+ view.findViewById(R.id.careportal_pumpbatterychange).setOnClickListener(this);
+ view.findViewById(R.id.careportal_mealbolus).setOnClickListener(this);
+ view.findViewById(R.id.careportal_note).setOnClickListener(this);
+ view.findViewById(R.id.careportal_profileswitch).setOnClickListener(this);
+ view.findViewById(R.id.careportal_pumpsitechange).setOnClickListener(this);
+ view.findViewById(R.id.careportal_question).setOnClickListener(this);
+ view.findViewById(R.id.careportal_snackbolus).setOnClickListener(this);
+ view.findViewById(R.id.careportal_tempbasalend).setOnClickListener(this);
+ view.findViewById(R.id.careportal_tempbasalstart).setOnClickListener(this);
+ view.findViewById(R.id.careportal_openapsoffline).setOnClickListener(this);
+ view.findViewById(R.id.careportal_temporarytarget).setOnClickListener(this);
- iage = view.findViewById(R.id.careportal_insulinage);
- cage = view.findViewById(R.id.careportal_canulaage);
- sage = view.findViewById(R.id.careportal_sensorage);
- pbage = view.findViewById(R.id.careportal_pbage);
+ iage = view.findViewById(R.id.careportal_insulinage);
+ cage = view.findViewById(R.id.careportal_canulaage);
+ sage = view.findViewById(R.id.careportal_sensorage);
+ pbage = view.findViewById(R.id.careportal_pbage);
- statsLayout = view.findViewById(R.id.careportal_stats);
+ statsLayout = view.findViewById(R.id.careportal_stats);
- noProfileView = view.findViewById(R.id.profileview_noprofile);
- butonsLayout = view.findViewById(R.id.careportal_buttons);
+ noProfileView = view.findViewById(R.id.profileview_noprofile);
+ butonsLayout = view.findViewById(R.id.careportal_buttons);
- ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null ? ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() : null;
- if (profileStore == null) {
- noProfileView.setVisibility(View.VISIBLE);
- butonsLayout.setVisibility(View.GONE);
- } else {
- noProfileView.setVisibility(View.GONE);
- butonsLayout.setVisibility(View.VISIBLE);
- }
-
- if (Config.NSCLIENT)
- statsLayout.setVisibility(View.GONE); // visible on overview
-
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
+ ProfileStore profileStore = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface() != null ? ConfigBuilderPlugin.getPlugin().getActiveProfileInterface().getProfile() : null;
+ if (profileStore == null) {
+ noProfileView.setVisibility(View.VISIBLE);
+ butonsLayout.setVisibility(View.GONE);
+ } else {
+ noProfileView.setVisibility(View.GONE);
+ butonsLayout.setVisibility(View.VISIBLE);
}
- return null;
+ if (Config.NSCLIENT)
+ statsLayout.setVisibility(View.GONE); // visible on overview
+
+ return view;
+ }
+
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventCareportalEventChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
+ updateGUI();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
}
@Override
@@ -203,12 +212,6 @@ public class CareportalFragment extends SubscriberFragment implements View.OnCli
newDialog.show(manager, "NewNSTreatmentDialog");
}
- @Subscribe
- public void onStatusEvent(final EventCareportalEventChange c) {
- updateGUI();
- }
-
- @Override
protected void updateGUI() {
Activity activity = getActivity();
updateAge(activity, sage, iage, cage, pbage);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java
index 66727f0f7f..997c6b0ba9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java
@@ -1,12 +1,8 @@
package info.nightscout.androidaps.plugins.general.food;
-import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
-import androidx.appcompat.app.AlertDialog;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
@@ -18,7 +14,10 @@ import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.appcompat.app.AlertDialog;
+import androidx.fragment.app.Fragment;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,17 +30,20 @@ import java.util.Set;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
-import info.nightscout.androidaps.utils.FabricPrivacy;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SpinnerHelper;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by mike on 16.10.2017.
*/
-public class FoodFragment extends SubscriberFragment {
+public class FoodFragment extends Fragment {
private static Logger log = LoggerFactory.getLogger(FoodFragment.class);
+ private CompositeDisposable disposable = new CompositeDisposable();
EditText filter;
ImageView clearFilter;
@@ -59,93 +61,96 @@ public class FoodFragment extends SubscriberFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.food_fragment, container, false);
- filter = (EditText) view.findViewById(R.id.food_filter);
- clearFilter = (ImageView) view.findViewById(R.id.food_clearfilter);
- category = new SpinnerHelper(view.findViewById(R.id.food_category));
- subcategory = new SpinnerHelper(view.findViewById(R.id.food_subcategory));
- recyclerView = (RecyclerView) view.findViewById(R.id.food_recyclerview);
- recyclerView.setHasFixedSize(true);
- LinearLayoutManager llm = new LinearLayoutManager(view.getContext());
- recyclerView.setLayoutManager(llm);
+ View view = inflater.inflate(R.layout.food_fragment, container, false);
+ filter = (EditText) view.findViewById(R.id.food_filter);
+ clearFilter = (ImageView) view.findViewById(R.id.food_clearfilter);
+ category = new SpinnerHelper(view.findViewById(R.id.food_category));
+ subcategory = new SpinnerHelper(view.findViewById(R.id.food_subcategory));
+ recyclerView = (RecyclerView) view.findViewById(R.id.food_recyclerview);
+ recyclerView.setHasFixedSize(true);
+ LinearLayoutManager llm = new LinearLayoutManager(view.getContext());
+ recyclerView.setLayoutManager(llm);
- clearFilter.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- filter.setText("");
- category.setSelection(0);
- subcategory.setSelection(0);
- filterData();
- }
- });
+ clearFilter.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ filter.setText("");
+ category.setSelection(0);
+ subcategory.setSelection(0);
+ filterData();
+ }
+ });
- category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- fillSubcategories();
- filterData();
- }
+ category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ fillSubcategories();
+ filterData();
+ }
- @Override
- public void onNothingSelected(AdapterView> parent) {
- fillSubcategories();
- filterData();
- }
- });
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+ fillSubcategories();
+ filterData();
+ }
+ });
- subcategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
- @Override
- public void onItemSelected(AdapterView> parent, View view, int position, long id) {
- filterData();
- }
+ subcategory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
+ @Override
+ public void onItemSelected(AdapterView> parent, View view, int position, long id) {
+ filterData();
+ }
- @Override
- public void onNothingSelected(AdapterView> parent) {
- filterData();
- }
- });
+ @Override
+ public void onNothingSelected(AdapterView> parent) {
+ filterData();
+ }
+ });
- filter.addTextChangedListener(new TextWatcher() {
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
+ filter.addTextChangedListener(new TextWatcher() {
+ @Override
+ public void beforeTextChanged(CharSequence s, int start, int count, int after) {
+ }
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- filterData();
- }
+ @Override
+ public void onTextChanged(CharSequence s, int start, int before, int count) {
+ filterData();
+ }
- @Override
- public void afterTextChanged(Editable s) {
- }
- });
+ @Override
+ public void afterTextChanged(Editable s) {
+ }
+ });
- RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp
- .getSpecificPlugin(FoodPlugin.class).getService().getFoodData());
- recyclerView.setAdapter(adapter);
+ RecyclerViewAdapter adapter = new RecyclerViewAdapter(FoodPlugin.getPlugin().getService().getFoodData());
+ recyclerView.setAdapter(adapter);
- loadData();
- fillCategories();
- fillSubcategories();
- filterData();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
+ loadData();
+ fillCategories();
+ fillSubcategories();
+ filterData();
+ return view;
}
- @Subscribe
- @SuppressWarnings("unused")
- public void onStatusEvent(final EventFoodDatabaseChanged ev) {
- loadData();
- filterData();
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventFoodDatabaseChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
}
void loadData() {
- unfiltered = MainApp.getSpecificPlugin(FoodPlugin.class).getService().getFoodData();
+ unfiltered = FoodPlugin.getPlugin().getService().getFoodData();
}
void fillCategories() {
@@ -207,19 +212,11 @@ public class FoodFragment extends SubscriberFragment {
filtered.add(f);
}
- updateGUI();
+ updateGui();
}
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- recyclerView.swapAdapter(new FoodFragment.RecyclerViewAdapter(filtered), true);
- }
- });
+ protected void updateGui() {
+ recyclerView.swapAdapter(new FoodFragment.RecyclerViewAdapter(filtered), true);
}
public class RecyclerViewAdapter extends RecyclerView.Adapter {
@@ -299,7 +296,7 @@ public class FoodFragment extends SubscriberFragment {
if (_id != null && !_id.equals("")) {
NSUpload.removeFoodFromNS(_id);
}
- MainApp.getSpecificPlugin(FoodPlugin.class).getService().delete(food);
+ FoodPlugin.getPlugin().getService().delete(food);
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java
index 3856ecfc22..065c74eabb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java
@@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.general.food;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
+
import androidx.annotation.Nullable;
import com.j256.ormlite.android.apptools.OpenHelperManager;
@@ -11,7 +12,6 @@ import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.DaoManager;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
-import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
@@ -34,6 +34,10 @@ import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.events.EventFoodDatabaseChanged;
import info.nightscout.androidaps.events.EventNsFood;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 24.09.2017.
@@ -41,6 +45,7 @@ import info.nightscout.androidaps.logging.L;
public class FoodService extends OrmLiteBaseService {
private Logger log = LoggerFactory.getLogger(L.DATAFOOD);
+ private CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture> scheduledFoodEventPost = null;
@@ -48,7 +53,34 @@ public class FoodService extends OrmLiteBaseService {
public FoodService() {
onCreate();
dbInitialize();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNsFood.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ int mode = event.getMode();
+ Bundle payload = event.getPayload();
+
+ try {
+ if (payload.containsKey("food")) {
+ JSONObject json = new JSONObject(payload.getString("food"));
+ if (mode == EventNsFood.Companion.getADD() || mode == EventNsFood.Companion.getUPDATE())
+ this.createFoodFromJsonIfNotExists(json);
+ else
+ this.deleteNS(json);
+ }
+
+ if (payload.containsKey("foods")) {
+ JSONArray array = new JSONArray(payload.getString("foods"));
+ if (mode == EventNsFood.Companion.getADD() || mode == EventNsFood.Companion.getUPDATE())
+ this.createFoodFromJsonIfNotExists(array);
+ else
+ this.deleteNS(array);
+ }
+ } catch (JSONException e) {
+ log.error("Unhandled Exception", e);
+ }
+ }, FabricPrivacy::logException)
+ );
}
/**
@@ -79,34 +111,6 @@ public class FoodService extends OrmLiteBaseService {
return null;
}
- @Subscribe
- public void handleNsEvent(EventNsFood event) {
- int mode = event.getMode();
- Bundle payload = event.getPayload();
-
- try {
- if (payload.containsKey("food")) {
- JSONObject json = new JSONObject(payload.getString("food"));
- if (mode == EventNsFood.ADD || mode == EventNsFood.UPDATE) {
- this.createFoodFromJsonIfNotExists(json);
- } else {
- this.deleteNS(json);
- }
- }
-
- if (payload.containsKey("foods")) {
- JSONArray array = new JSONArray(payload.getString("foods"));
- if (mode == EventNsFood.ADD || mode == EventNsFood.UPDATE) {
- this.createFoodFromJsonIfNotExists(array);
- } else {
- this.deleteNS(array);
- }
- }
- } catch (JSONException e) {
- log.error("Unhandled Exception", e);
- }
- }
-
@Override
public void onCreate() {
super.onCreate();
@@ -162,7 +166,7 @@ public class FoodService extends OrmLiteBaseService {
public void run() {
if (L.isEnabled(L.DATAFOOD))
log.debug("Firing EventFoodChange");
- MainApp.bus().post(event);
+ RxBus.INSTANCE.send(event);
callback.setPost(null);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java
index ea56115347..7a801a44c0 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.java
@@ -28,6 +28,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.ToastUtils;
@@ -136,7 +137,7 @@ public class ImportExportPrefs {
OKDialog.show(context, MainApp.gs(R.string.setting_imported), MainApp.gs(R.string.restartingapp), () -> {
log.debug("Exiting");
MainApp.instance().stopKeepAliveService();
- MainApp.bus().post(new EventAppExit());
+ RxBus.INSTANCE.send(new EventAppExit());
MainApp.closeDbHelper();
if (context instanceof Activity) {
((Activity)context).finish();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java
index 50674c5a94..112eb9c951 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.nsclient;
-import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
@@ -17,18 +16,22 @@ import android.widget.CompoundButton;
import android.widget.ScrollView;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.Fragment;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
+
+public class NSClientFragment extends Fragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
-public class NSClientFragment extends SubscriberFragment implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private TextView logTextView;
private TextView queueTextView;
private TextView urlTextView;
@@ -45,51 +48,61 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false);
+ View view = inflater.inflate(R.layout.nsclientinternal_fragment, container, false);
- logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview);
- autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll);
- autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll);
- autoscrollCheckbox.setOnCheckedChangeListener(this);
- pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused);
- pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused);
- pausedCheckbox.setOnCheckedChangeListener(this);
- logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log);
- queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue);
- urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url);
- statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status);
+ logScrollview = (ScrollView) view.findViewById(R.id.nsclientinternal_logscrollview);
+ autoscrollCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_autoscroll);
+ autoscrollCheckbox.setChecked(NSClientPlugin.getPlugin().autoscroll);
+ autoscrollCheckbox.setOnCheckedChangeListener(this);
+ pausedCheckbox = (CheckBox) view.findViewById(R.id.nsclientinternal_paused);
+ pausedCheckbox.setChecked(NSClientPlugin.getPlugin().paused);
+ pausedCheckbox.setOnCheckedChangeListener(this);
+ logTextView = (TextView) view.findViewById(R.id.nsclientinternal_log);
+ queueTextView = (TextView) view.findViewById(R.id.nsclientinternal_queue);
+ urlTextView = (TextView) view.findViewById(R.id.nsclientinternal_url);
+ statusTextView = (TextView) view.findViewById(R.id.nsclientinternal_status);
- clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog);
- clearlog.setOnClickListener(this);
- clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- restart = (TextView) view.findViewById(R.id.nsclientinternal_restart);
- restart.setOnClickListener(this);
- restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow);
- delivernow.setOnClickListener(this);
- delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue);
- clearqueue.setOnClickListener(this);
- clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue);
- showqueue.setOnClickListener(this);
- showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
+ clearlog = (TextView) view.findViewById(R.id.nsclientinternal_clearlog);
+ clearlog.setOnClickListener(this);
+ clearlog.setPaintFlags(clearlog.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
+ restart = (TextView) view.findViewById(R.id.nsclientinternal_restart);
+ restart.setOnClickListener(this);
+ restart.setPaintFlags(restart.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
+ delivernow = (TextView) view.findViewById(R.id.nsclientinternal_delivernow);
+ delivernow.setOnClickListener(this);
+ delivernow.setPaintFlags(delivernow.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
+ clearqueue = (TextView) view.findViewById(R.id.nsclientinternal_clearqueue);
+ clearqueue.setOnClickListener(this);
+ clearqueue.setPaintFlags(clearqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
+ showqueue = (TextView) view.findViewById(R.id.nsclientinternal_showqueue);
+ showqueue.setOnClickListener(this);
+ showqueue.setPaintFlags(showqueue.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
- updateGUI();
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
+ return view;
+ }
- return null;
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNSClientUpdateGUI.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.nsclientinternal_restart:
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
FabricPrivacy.getInstance().logCustom("NSClientRestart");
break;
case R.id.nsclientinternal_delivernow:
@@ -108,7 +121,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
UploadQueue.clearQueue();
- updateGUI();
+ updateGui();
FabricPrivacy.getInstance().logCustom("NSClientClearQueue");
}
});
@@ -116,7 +129,7 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
builder.show();
break;
case R.id.nsclientinternal_showqueue:
- MainApp.bus().post(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList()));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", NSClientPlugin.getPlugin().queue().textList()));
break;
}
}
@@ -126,38 +139,28 @@ public class NSClientFragment extends SubscriberFragment implements View.OnClick
switch (buttonView.getId()) {
case R.id.nsclientinternal_paused:
NSClientPlugin.getPlugin().pause(isChecked);
- updateGUI();
+ updateGui();
FabricPrivacy.getInstance().logCustom("NSClientPause");
break;
case R.id.nsclientinternal_autoscroll:
SP.putBoolean(R.string.key_nsclientinternal_autoscroll, isChecked);
NSClientPlugin.getPlugin().autoscroll = isChecked;
- updateGUI();
+ updateGui();
break;
}
}
- @Subscribe
- public void onStatusEvent(final EventNSClientUpdateGUI ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- NSClientPlugin.getPlugin().updateLog();
- pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false));
- logTextView.setText(NSClientPlugin.getPlugin().textLog);
- if (NSClientPlugin.getPlugin().autoscroll) {
- logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
- }
- urlTextView.setText(NSClientPlugin.getPlugin().url());
- Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + "");
- queueTextView.setText(queuetext);
- statusTextView.setText(NSClientPlugin.getPlugin().status);
- });
+ protected void updateGui() {
+ NSClientPlugin.getPlugin().updateLog();
+ pausedCheckbox.setChecked(SP.getBoolean(R.string.key_nsclientinternal_paused, false));
+ logTextView.setText(NSClientPlugin.getPlugin().textLog);
+ if (NSClientPlugin.getPlugin().autoscroll) {
+ logScrollview.fullScroll(ScrollView.FOCUS_DOWN);
+ }
+ urlTextView.setText(NSClientPlugin.getPlugin().url());
+ Spanned queuetext = Html.fromHtml(MainApp.gs(R.string.queue) + " " + UploadQueue.size() + "");
+ queueTextView.setText(queuetext);
+ statusTextView.setText(NSClientPlugin.getPlugin().status);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java
index 4b6072ee1e..037f91b3f0 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java
@@ -7,11 +7,12 @@ import android.content.ServiceConnection;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
+import android.preference.PreferenceFragment;
+import android.preference.PreferenceScreen;
import android.text.Html;
import android.text.Spanned;
-import com.squareup.otto.Subscribe;
-
+import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -22,7 +23,6 @@ import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange;
@@ -31,15 +31,20 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientNewLog;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.ToastUtils;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class NSClientPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger(L.NSCLIENT);
+ private CompositeDisposable disposable = new CompositeDisposable();
static NSClientPlugin nsClientPlugin;
@@ -87,7 +92,7 @@ public class NSClientPlugin extends PluginBase {
}
nsClientReceiverDelegate =
- new NsClientReceiverDelegate(MainApp.instance().getApplicationContext(), MainApp.bus());
+ new NsClientReceiverDelegate();
}
public boolean isAllowed() {
@@ -97,41 +102,79 @@ public class NSClientPlugin extends PluginBase {
@Override
protected void onStart() {
- MainApp.bus().register(this);
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, NSClientService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
super.onStart();
- nsClientReceiverDelegate.registerReceivers();
+ nsClientReceiverDelegate.grabReceiversState();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNSClientStatus.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ status = event.getStatus();
+ RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNetworkChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (nsClientService != null) {
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNSClientNewLog.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ addToLog(event);
+ if (L.isEnabled(L.NSCLIENT))
+ log.debug(event.getAction() + " " + event.getLogText());
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventChargingState.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), FabricPrivacy::logException)
+ );
}
@Override
protected void onStop() {
- MainApp.bus().unregister(this);
- Context context = MainApp.instance().getApplicationContext();
- context.unbindService(mConnection);
-
- nsClientReceiverDelegate.unregisterReceivers();
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ disposable.clear();
super.onStop();
}
- @Subscribe
- public void onStatusEvent(EventPreferenceChange ev) {
- nsClientReceiverDelegate.onStatusEvent(ev);
- }
+ @Override
+ public void preprocessPreferences(@NotNull PreferenceFragment preferenceFragment) {
+ super.preprocessPreferences(preferenceFragment);
- @Subscribe
- public void onStatusEvent(final EventChargingState ev) {
- nsClientReceiverDelegate.onStatusEvent(ev);
+ if (Config.NSCLIENT) {
+ PreferenceScreen scrnAdvancedSettings = (PreferenceScreen) preferenceFragment.findPreference(MainApp.gs(R.string.key_advancedsettings));
+ if (scrnAdvancedSettings != null) {
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_res_warning)));
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_res_critical)));
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_bat_warning)));
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_statuslights_bat_critical)));
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_show_statuslights)));
+ scrnAdvancedSettings.removePreference(preferenceFragment.findPreference(MainApp.gs(R.string.key_show_statuslights_extended)));
+ }
+ }
}
- @Subscribe
- public void onStatusEvent(final EventNetworkChange ev) {
- nsClientReceiverDelegate.onStatusEvent(ev);
- }
-
-
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
@@ -149,33 +192,12 @@ public class NSClientPlugin extends PluginBase {
}
};
- @Subscribe
- public void onStatusEvent(final EventAppExit ignored) {
- if (nsClientService != null) {
- MainApp.instance().getApplicationContext().unbindService(mConnection);
- nsClientReceiverDelegate.unregisterReceivers();
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventNSClientNewLog ev) {
- addToLog(ev);
- if (L.isEnabled(L.NSCLIENT))
- log.debug(ev.action + " " + ev.logText);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNSClientStatus ev) {
- status = ev.status;
- MainApp.bus().post(new EventNSClientUpdateGUI());
- }
-
synchronized void clearLog() {
handler.post(() -> {
synchronized (listLog) {
listLog.clear();
}
- MainApp.bus().post(new EventNSClientUpdateGUI());
+ RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
});
}
@@ -188,7 +210,7 @@ public class NSClientPlugin extends PluginBase {
listLog.remove(0);
}
}
- MainApp.bus().post(new EventNSClientUpdateGUI());
+ RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
});
}
@@ -214,7 +236,6 @@ public class NSClientPlugin extends PluginBase {
public void pause(boolean newState) {
SP.putBoolean(R.string.key_nsclientinternal_paused, newState);
paused = newState;
- MainApp.bus().post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java
index 881593b32a..f5582b71a2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java
@@ -594,7 +594,7 @@ public class NSUpload {
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java
index 072ad6cd56..fd05b133f5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java
@@ -6,74 +6,45 @@ import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
-import com.squareup.otto.Bus;
-
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.events.EventChargingState;
import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.events.EventPreferenceChange;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.receivers.ChargingStateReceiver;
import info.nightscout.androidaps.receivers.NetworkChangeReceiver;
import info.nightscout.androidaps.utils.SP;
class NsClientReceiverDelegate {
- private final Context context;
- private final Bus bus;
-
- private NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
- private ChargingStateReceiver chargingStateReceiver = new ChargingStateReceiver();
-
private boolean allowedChargingState = true;
private boolean allowedNetworkState = true;
boolean allowed = true;
- NsClientReceiverDelegate(Context context, Bus bus) {
- this.context = context;
- this.bus = bus;
- }
-
- void registerReceivers() {
+ void grabReceiversState() {
Context context = MainApp.instance().getApplicationContext();
- // register NetworkChangeReceiver --> https://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html
- // Nougat is not providing Connectivity-Action anymore ;-(
- context.registerReceiver(networkChangeReceiver,
- new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
- context.registerReceiver(networkChangeReceiver,
- new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION));
- EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(context);
- if (event != null)
- bus.post(event);
+ EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(context);
+ if (event != null) RxBus.INSTANCE.send(event);
- context.registerReceiver(chargingStateReceiver,
- new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
+ EventChargingState eventChargingState = ChargingStateReceiver.grabChargingState(context);
+ if (eventChargingState != null) RxBus.INSTANCE.send(eventChargingState);
- EventChargingState eventChargingState = chargingStateReceiver.grabChargingState(context);
- if (eventChargingState != null)
- bus.post(eventChargingState);
-
- }
-
- void unregisterReceivers() {
- context.unregisterReceiver(networkChangeReceiver);
- context.unregisterReceiver(chargingStateReceiver);
}
void onStatusEvent(EventPreferenceChange ev) {
if (ev.isChanged(R.string.key_ns_wifionly) ||
ev.isChanged(R.string.key_ns_wifi_ssids) ||
ev.isChanged(R.string.key_ns_allowroaming)
- ) {
- EventNetworkChange event = networkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext());
+ ) {
+ EventNetworkChange event = NetworkChangeReceiver.grabNetworkStatus(MainApp.instance().getApplicationContext());
if (event != null)
- bus.post(event);
+ RxBus.INSTANCE.send(event);
} else if (ev.isChanged(R.string.key_ns_chargingonly)) {
- EventChargingState event = chargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
+ EventChargingState event = ChargingStateReceiver.grabChargingState(MainApp.instance().getApplicationContext());
if (event != null)
- bus.post(event);
+ RxBus.INSTANCE.send(event);
}
}
@@ -95,18 +66,16 @@ class NsClientReceiverDelegate {
}
}
- void processStateChange() {
+ private void processStateChange() {
boolean newAllowedState = allowedChargingState && allowedNetworkState;
if (newAllowedState != allowed) {
allowed = newAllowedState;
- bus.post(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
RxBus.INSTANCE.send(new EventPreferenceChange(R.string.key_nsclientinternal_paused));
}
}
boolean calculateStatus(final EventChargingState ev) {
boolean chargingOnly = SP.getBoolean(R.string.key_ns_chargingonly, false);
-
boolean newAllowedState = true;
if (!ev.isCharging() && chargingOnly) {
@@ -123,19 +92,17 @@ class NsClientReceiverDelegate {
boolean newAllowedState = true;
- if (ev.wifiConnected) {
+ if (ev.getWifiConnected()) {
if (!allowedSSIDs.trim().isEmpty() &&
- (!allowedSSIDs.contains(ev.getSsid()) && !allowedSSIDs.contains(ev.ssid))) {
+ (!allowedSSIDs.contains(ev.connectedSsid()) && !allowedSSIDs.contains(ev.getSsid()))) {
newAllowedState = false;
}
} else {
- if ((!allowRoaming && ev.roaming) || wifiOnly) {
+ if ((!allowRoaming && ev.getRoaming()) || wifiOnly) {
newAllowedState = false;
}
}
-
return newAllowedState;
}
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java
index ead373d61d..01d1f26c33 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java
@@ -5,9 +5,9 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import io.socket.client.Ack;
@@ -33,7 +33,7 @@ public class NSAddAck extends Event implements Ack {
nsClientID = response.getString("NSCLIENT_ID");
}
}
- MainApp.bus().post(this);
+ RxBus.INSTANCE.send(this);
return;
} catch (Exception e) {
log.error("Unhandled exception", e);
@@ -44,7 +44,7 @@ public class NSAddAck extends Event implements Ack {
if (response.has("result")) {
_id = null;
if (response.getString("result").contains("Not")) {
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
return;
}
if (L.isEnabled(L.NSCLIENT))
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java
index 62c1cf7f5d..754ff6684b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java
@@ -2,13 +2,10 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks;
import org.json.JSONObject;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import io.socket.client.Ack;
-/**
- * Created by mike on 02.01.2016.
- */
public class NSAuthAck extends Event implements Ack{
public boolean read = false;
public boolean write = false;
@@ -19,6 +16,6 @@ public class NSAuthAck extends Event implements Ack{
read = response.optBoolean("read");
write = response.optBoolean("write");
write_treatment = response.optBoolean("write_treatment");
- MainApp.bus().post(this);
+ RxBus.INSTANCE.send(this);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java
index 68ce3d9a37..2a4022980d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java
@@ -5,9 +5,9 @@ import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.Event;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import io.socket.client.Ack;
/**
@@ -28,7 +28,7 @@ public class NSUpdateAck extends Event implements Ack {
result = true;
log.debug("Internal error: Missing _id returned on dbUpdate ack");
}
- MainApp.bus().post(this);
+ RxBus.INSTANCE.send(this);
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java
deleted file mode 100644
index 121085cb94..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.general.nsclient.events;
-
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 15.02.2017.
- */
-
-public class EventNSClientNewLog extends Event {
- public Date date = new Date();
- public String action;
- public String logText;
- public EventNSClientNewLog(String action, String logText) {
- this.action = action;
- this.logText = logText;
- }
-
- SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
-
- public StringBuilder toPreparedHtml() {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append(timeFormat.format(date));
- stringBuilder.append(" ");
- stringBuilder.append(action);
- stringBuilder.append(" ");
- stringBuilder.append(logText);
- stringBuilder.append(" ");
- return stringBuilder;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt
new file mode 100644
index 0000000000..38d6bcfd0f
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientNewLog.kt
@@ -0,0 +1,22 @@
+package info.nightscout.androidaps.plugins.general.nsclient.events
+
+import info.nightscout.androidaps.events.Event
+import java.text.SimpleDateFormat
+import java.util.*
+
+class EventNSClientNewLog(var action: String, var logText: String) : Event() {
+ var date = Date()
+
+ private var timeFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
+
+ fun toPreparedHtml(): StringBuilder {
+ val stringBuilder = StringBuilder()
+ stringBuilder.append(timeFormat.format(date))
+ stringBuilder.append(" ")
+ stringBuilder.append(action)
+ stringBuilder.append(" ")
+ stringBuilder.append(logText)
+ stringBuilder.append(" ")
+ return stringBuilder
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java
deleted file mode 100644
index b5481ce741..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.general.nsclient.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 15.02.2017.
- */
-
-public class EventNSClientRestart extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt
new file mode 100644
index 0000000000..49333b6840
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientRestart.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.general.nsclient.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventNSClientRestart : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java
deleted file mode 100644
index c3bf74321c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.java
+++ /dev/null
@@ -1,18 +0,0 @@
-package info.nightscout.androidaps.plugins.general.nsclient.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 02.01.2016.
- */
-public class EventNSClientStatus extends Event {
- public String status = "";
-
- public EventNSClientStatus(String status) {
- this.status = status;
- }
-
- public EventNSClientStatus() {
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt
new file mode 100644
index 0000000000..4d0c9dcd6e
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt
@@ -0,0 +1,7 @@
+package info.nightscout.androidaps.plugins.general.nsclient.events
+
+import info.nightscout.androidaps.events.EventStatus
+
+class EventNSClientStatus(var text: String) : EventStatus() {
+ override fun getStatus(): String = text
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java
deleted file mode 100644
index 60d74a249d..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.general.nsclient.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 17.02.2017.
- */
-
-public class EventNSClientUpdateGUI extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt
new file mode 100644
index 0000000000..891e61895c
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientUpdateGUI.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.general.nsclient.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventNSClientUpdateGUI : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/AckAlarmReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/AckAlarmReceiver.java
index 7185072692..1c46716d69 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/AckAlarmReceiver.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/AckAlarmReceiver.java
@@ -27,7 +27,7 @@ public class AckAlarmReceiver extends BroadcastReceiver {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
AckAlarmReceiver.class.getSimpleName());
- NSClientPlugin nsClientPlugin = MainApp.getSpecificPlugin(NSClientPlugin.class);
+ NSClientPlugin nsClientPlugin = NSClientPlugin.getPlugin();
if (!nsClientPlugin.isEnabled(PluginType.GENERAL)) {
return;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/DBAccessReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/DBAccessReceiver.java
index 4d8b7eba2a..4838c178ef 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/DBAccessReceiver.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/receivers/DBAccessReceiver.java
@@ -118,7 +118,7 @@ public class DBAccessReceiver extends BroadcastReceiver {
}
public boolean shouldUpload() {
- NSClientPlugin nsClientPlugin = MainApp.getSpecificPlugin(NSClientPlugin.class);
+ NSClientPlugin nsClientPlugin = NSClientPlugin.getPlugin();
return nsClientPlugin.isEnabled(PluginType.GENERAL) && !SP.getBoolean(R.string.key_ns_noupload, false);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java
index 98ac099851..e1c57cc7c2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java
@@ -13,7 +13,6 @@ import android.os.SystemClock;
import com.google.common.base.Charsets;
import com.google.common.hash.Hashing;
import com.j256.ormlite.dao.CloseableIterator;
-import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.json.JSONException;
@@ -69,12 +68,15 @@ import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.JsonHelper;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class NSClientService extends Service {
private static Logger log = LoggerFactory.getLogger(L.NSCLIENT);
+ private CompositeDisposable disposable = new CompositeDisposable();
static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder();
@@ -113,7 +115,6 @@ public class NSClientService extends Service {
private int WATCHDOG_MAXCONNECTIONS = 5;
public NSClientService() {
- registerBus();
if (handler == null) {
HandlerThread handlerThread = new HandlerThread(NSClientService.class.getSimpleName() + "Handler");
handlerThread.start();
@@ -129,14 +130,115 @@ public class NSClientService extends Service {
public void onCreate() {
super.onCreate();
mWakeLock.acquire();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventConfigBuilderChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (nsEnabled != NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)) {
+ latestDateInReceivedData = 0;
+ destroy();
+ initialize();
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (event.isChanged(R.string.key_nsclientinternal_url) ||
+ event.isChanged(R.string.key_nsclientinternal_api_secret) ||
+ event.isChanged(R.string.key_nsclientinternal_paused)
+ ) {
+ latestDateInReceivedData = 0;
+ destroy();
+ initialize();
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.NSCLIENT))
+ log.debug("EventAppExit received");
+ destroy();
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNSClientRestart.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ latestDateInReceivedData = 0;
+ restart();
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(NSAuthAck.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> processAuthAck(event), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(NSUpdateAck.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> processUpdateAck(event), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(NSAddAck.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> processAddAck(event), FabricPrivacy::logException)
+ );
}
@Override
public void onDestroy() {
super.onDestroy();
+ disposable.clear();
if (mWakeLock.isHeld()) mWakeLock.release();
}
+ public void processAddAck(NSAddAck ack) {
+ if (ack.nsClientID != null) {
+ uploadQueue.removeID(ack.json);
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
+ } else {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
+ }
+ }
+
+ public void processUpdateAck(NSUpdateAck ack) {
+ if (ack.result) {
+ uploadQueue.removeID(ack.action, ack._id);
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
+ } else {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
+ }
+ }
+
+ public void processAuthAck(NSAuthAck ack) {
+ String connectionStatus = "Authenticated (";
+ if (ack.read) connectionStatus += "R";
+ if (ack.write) connectionStatus += "W";
+ if (ack.write_treatment) connectionStatus += "T";
+ connectionStatus += ')';
+ isConnected = true;
+ hasWriteAuth = ack.write && ack.write_treatment;
+ RxBus.INSTANCE.send(new EventNSClientStatus(connectionStatus));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", connectionStatus));
+ if (!ack.write) {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!"));
+ }
+ if (!ack.write_treatment) {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
+ }
+ if (!hasWriteAuth) {
+ Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT);
+ RxBus.INSTANCE.send(new EventNewNotification(noperm));
+ } else {
+ RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
+ }
+ }
+
public class LocalBinder extends Binder {
public NSClientService getServiceInstance() {
return NSClientService.this;
@@ -154,52 +256,6 @@ public class NSClientService extends Service {
return START_STICKY;
}
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
- }
-
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.NSCLIENT))
- log.debug("EventAppExit received");
-
- destroy();
-
- stopSelf();
- }
-
- @Subscribe
- public void onStatusEvent(EventPreferenceChange ev) {
- if (ev.isChanged(R.string.key_nsclientinternal_url) ||
- ev.isChanged(R.string.key_nsclientinternal_api_secret) ||
- ev.isChanged(R.string.key_nsclientinternal_paused)
- ) {
- latestDateInReceivedData = 0;
- destroy();
- initialize();
- }
- }
-
- @Subscribe
- public void onStatusEvent(EventConfigBuilderChange ev) {
- if (nsEnabled != MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL)) {
- latestDateInReceivedData = 0;
- destroy();
- initialize();
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventNSClientRestart ev) {
- latestDateInReceivedData = 0;
- restart();
- }
-
public void initialize() {
dataCounter = 0;
@@ -208,19 +264,19 @@ public class NSClientService extends Service {
if (!nsAPISecret.equals(""))
nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString();
- MainApp.bus().post(new EventNSClientStatus("Initializing"));
- if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) {
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "not allowed"));
- MainApp.bus().post(new EventNSClientStatus("Not allowed"));
- } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) {
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "paused"));
- MainApp.bus().post(new EventNSClientStatus("Paused"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Initializing"));
+ if (!NSClientPlugin.getPlugin().isAllowed()) {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "not allowed"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Not allowed"));
+ } else if (NSClientPlugin.getPlugin().paused) {
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "paused"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Paused"));
} else if (!nsEnabled) {
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disabled"));
- MainApp.bus().post(new EventNSClientStatus("Disabled"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disabled"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Disabled"));
} else if (!nsURL.equals("")) {
try {
- MainApp.bus().post(new EventNSClientStatus("Connecting ..."));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Connecting ..."));
IO.Options opt = new IO.Options();
opt.forceNew = true;
opt.reconnection = true;
@@ -228,7 +284,7 @@ public class NSClientService extends Service {
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_PING, onPing);
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "do connect"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "do connect"));
mSocket.connect();
mSocket.on("dataUpdate", onDataUpdate);
mSocket.on("announcement", onAnnouncement);
@@ -236,12 +292,12 @@ public class NSClientService extends Service {
mSocket.on("urgent_alarm", onUrgentAlarm);
mSocket.on("clear_alarm", onClearAlarm);
} catch (URISyntaxException | RuntimeException e) {
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
- MainApp.bus().post(new EventNSClientStatus("Wrong URL syntax"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "Wrong URL syntax"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Wrong URL syntax"));
}
} else {
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "No NS URL specified"));
- MainApp.bus().post(new EventNSClientStatus("Not configured"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "No NS URL specified"));
+ RxBus.INSTANCE.send(new EventNSClientStatus("Not configured"));
}
}
@@ -250,7 +306,7 @@ public class NSClientService extends Service {
public void call(Object... args) {
connectCounter++;
String socketId = mSocket != null ? mSocket.id() : "NULL";
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId));
if (mSocket != null)
sendAuthMessage(new NSAuthAck());
watchdog();
@@ -267,16 +323,16 @@ public class NSClientService extends Service {
reconnections.remove(r);
}
}
- MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "connections in last " + WATCHDOG_INTERVAL_MINUTES + " mins: " + reconnections.size() + "/" + WATCHDOG_MAXCONNECTIONS));
if (reconnections.size() >= WATCHDOG_MAXCONNECTIONS) {
Notification n = new Notification(Notification.NSMALFUNCTION, MainApp.gs(R.string.nsmalfunction), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(n));
- MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "pausing for " + WATCHDOG_RECONNECT_IN + " mins"));
NSClientPlugin.getPlugin().pause(true);
- MainApp.bus().post(new EventNSClientUpdateGUI());
+ RxBus.INSTANCE.send(new EventNSClientUpdateGUI());
new Thread(() -> {
SystemClock.sleep(T.mins(WATCHDOG_RECONNECT_IN).msecs());
- MainApp.bus().post(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("WATCHDOG", "reenabling NSClient"));
NSClientPlugin.getPlugin().pause(false);
}).start();
}
@@ -288,7 +344,7 @@ public class NSClientService extends Service {
public void call(Object... args) {
if (L.isEnabled(L.NSCLIENT))
log.debug("disconnect reason: {}", args);
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "disconnect event"));
}
};
@@ -303,7 +359,7 @@ public class NSClientService extends Service {
mSocket.off("urgent_alarm");
mSocket.off("clear_alarm");
- MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "destroy"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "destroy"));
isConnected = false;
hasWriteAuth = false;
mSocket.disconnect();
@@ -324,38 +380,13 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
- MainApp.bus().post(new EventNSClientNewLog("AUTH", "requesting auth"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("AUTH", "requesting auth"));
if (mSocket != null)
mSocket.emit("authorize", authMessage, ack);
}
- @Subscribe
- public void onStatusEvent(NSAuthAck ack) {
- String connectionStatus = "Authenticated (";
- if (ack.read) connectionStatus += "R";
- if (ack.write) connectionStatus += "W";
- if (ack.write_treatment) connectionStatus += "T";
- connectionStatus += ')';
- isConnected = true;
- hasWriteAuth = ack.write && ack.write_treatment;
- MainApp.bus().post(new EventNSClientStatus(connectionStatus));
- MainApp.bus().post(new EventNSClientNewLog("AUTH", connectionStatus));
- if (!ack.write) {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write permission not granted !!!!"));
- }
- if (!ack.write_treatment) {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "Write treatment permission not granted !!!!"));
- }
- if (!hasWriteAuth) {
- Notification noperm = new Notification(Notification.NSCLIENT_NO_WRITE_PERMISSION, MainApp.gs(R.string.nowritepermission), Notification.URGENT);
- RxBus.INSTANCE.send(new EventNewNotification(noperm));
- } else {
- RxBus.INSTANCE.send(new EventDismissNotification(Notification.NSCLIENT_NO_WRITE_PERMISSION));
- }
- }
-
public void readPreferences() {
- nsEnabled = MainApp.getSpecificPlugin(NSClientPlugin.class).isEnabled(PluginType.GENERAL);
+ nsEnabled = NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL);
nsURL = SP.getString(R.string.key_nsclientinternal_url, "");
nsAPISecret = SP.getString(R.string.key_nsclientinternal_api_secret, "");
nsDevice = SP.getString("careportal_enteredby", "");
@@ -364,7 +395,7 @@ public class NSClientService extends Service {
private Emitter.Listener onPing = new Emitter.Listener() {
@Override
public void call(final Object... args) {
- MainApp.bus().post(new EventNSClientNewLog("PING", "received"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("PING", "received"));
// send data if there is something waiting
resend("Ping received");
}
@@ -393,7 +424,7 @@ public class NSClientService extends Service {
return;
}
try {
- MainApp.bus().post(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received")));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(data, "message", "received")));
} catch (Exception e) {
FabricPrivacy.logException(e);
log.error("Unhandled exception", e);
@@ -420,7 +451,7 @@ public class NSClientService extends Service {
*/
@Override
public void call(final Object... args) {
- MainApp.bus().post(new EventNSClientNewLog("ALARM", "received"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ALARM", "received"));
JSONObject data;
try {
data = (JSONObject) args[0];
@@ -459,7 +490,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
- MainApp.bus().post(new EventNSClientNewLog("URGENTALARM", "received"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("URGENTALARM", "received"));
BroadcastUrgentAlarm.handleUrgentAlarm(data, getApplicationContext());
if (L.isEnabled(L.NSCLIENT))
log.debug(data.toString());
@@ -485,7 +516,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
return;
}
- MainApp.bus().post(new EventNSClientNewLog("CLEARALARM", "received"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("CLEARALARM", "received"));
BroadcastClearAlarm.handleClearAlarm(data, getApplicationContext());
if (L.isEnabled(L.NSCLIENT))
log.debug(data.toString());
@@ -510,7 +541,7 @@ public class NSClientService extends Service {
// delta means only increment/changes are comming
boolean isDelta = data.has("delta");
boolean isFull = !isDelta;
- MainApp.bus().post(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full")));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "Data packet #" + dataCounter++ + (isDelta ? " delta" : " full")));
if (data.has("profiles")) {
JSONArray profiles = data.getJSONArray("profiles");
@@ -518,7 +549,7 @@ public class NSClientService extends Service {
JSONObject profile = (JSONObject) profiles.get(profiles.length() - 1);
profileStore = new ProfileStore(profile);
broadcastProfile = true;
- MainApp.bus().post(new EventNSClientNewLog("PROFILE", "profile received"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "profile received"));
}
}
@@ -528,7 +559,7 @@ public class NSClientService extends Service {
if (!status.has("versionNum")) {
if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
} else {
nightscoutVersionName = nsSettingsStatus.getVersion();
@@ -553,13 +584,13 @@ public class NSClientService extends Service {
}
*/
} else if (!isDelta) {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!"));
}
// If new profile received or change detected broadcast it
if (broadcastProfile && profileStore != null) {
BroadcastProfile.handleNewTreatment(profileStore, MainApp.instance().getApplicationContext(), isDelta);
- MainApp.bus().post(new EventNSClientNewLog("PROFILE", "broadcasting"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("PROFILE", "broadcasting"));
}
if (data.has("treatments")) {
@@ -568,7 +599,7 @@ public class NSClientService extends Service {
JSONArray updatedTreatments = new JSONArray();
JSONArray addedTreatments = new JSONArray();
if (treatments.length() > 0)
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + treatments.length() + " treatments"));
for (Integer index = 0; index < treatments.length(); index++) {
JSONObject jsonTreatment = treatments.getJSONObject(index);
NSTreatment treatment = new NSTreatment(jsonTreatment);
@@ -602,7 +633,7 @@ public class NSClientService extends Service {
if (data.has("devicestatus")) {
JSONArray devicestatuses = data.getJSONArray("devicestatus");
if (devicestatuses.length() > 0) {
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + devicestatuses.length() + " devicestatuses"));
for (Integer index = 0; index < devicestatuses.length(); index++) {
JSONObject jsonStatus = devicestatuses.getJSONObject(index);
// remove from upload queue if Ack is failing
@@ -617,7 +648,7 @@ public class NSClientService extends Service {
JSONArray updatedFoods = new JSONArray();
JSONArray addedFoods = new JSONArray();
if (foods.length() > 0)
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + foods.length() + " foods"));
for (Integer index = 0; index < foods.length(); index++) {
JSONObject jsonFood = foods.getJSONObject(index);
@@ -647,7 +678,7 @@ public class NSClientService extends Service {
if (data.has("mbgs")) {
JSONArray mbgs = data.getJSONArray("mbgs");
if (mbgs.length() > 0)
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + mbgs.length() + " mbgs"));
for (Integer index = 0; index < mbgs.length(); index++) {
JSONObject jsonMbg = mbgs.getJSONObject(index);
// remove from upload queue if Ack is failing
@@ -658,7 +689,7 @@ public class NSClientService extends Service {
if (data.has("cals")) {
JSONArray cals = data.getJSONArray("cals");
if (cals.length() > 0)
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + cals.length() + " cals"));
// Retreive actual calibration
for (Integer index = 0; index < cals.length(); index++) {
// remove from upload queue if Ack is failing
@@ -669,10 +700,10 @@ public class NSClientService extends Service {
if (data.has("sgvs")) {
JSONArray sgvs = data.getJSONArray("sgvs");
if (sgvs.length() > 0)
- MainApp.bus().post(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "received " + sgvs.length() + " sgvs"));
for (Integer index = 0; index < sgvs.length(); index++) {
JSONObject jsonSgv = sgvs.getJSONObject(index);
- // MainApp.bus().post(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString());
+ // RxBus.INSTANCE.send(new EventNSClientNewLog("DATA", "svg " + sgvs.getJSONObject(index).toString());
NSSgv sgv = new NSSgv(jsonSgv);
// Handle new sgv here
// remove from upload queue if Ack is failing
@@ -691,11 +722,11 @@ public class NSClientService extends Service {
}
BroadcastSgvs.handleNewSgv(sgvs, MainApp.instance().getApplicationContext(), isDelta);
}
- MainApp.bus().post(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData)));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
- //MainApp.bus().post(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
+ //RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end");
} finally {
if (wakeLock.isHeld()) wakeLock.release();
}
@@ -713,7 +744,7 @@ public class NSClientService extends Service {
message.put("_id", dbr._id);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbUpdate", message, ack);
- MainApp.bus().post(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@@ -727,7 +758,7 @@ public class NSClientService extends Service {
message.put("_id", dbr._id);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbUpdateUnset", message, ack);
- MainApp.bus().post(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@@ -740,22 +771,12 @@ public class NSClientService extends Service {
message.put("collection", dbr.collection);
message.put("_id", dbr._id);
mSocket.emit("dbRemove", message, ack);
- MainApp.bus().post(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
}
- @Subscribe
- public void onStatusEvent(NSUpdateAck ack) {
- if (ack.result) {
- uploadQueue.removeID(ack.action, ack._id);
- MainApp.bus().post(new EventNSClientNewLog("DBUPDATE/DBREMOVE", "Acked " + ack._id));
- } else {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBUPDATE/DBREMOVE Unknown response"));
- }
- }
-
public void dbAdd(DbRequest dbr, NSAddAck ack) {
try {
if (!isConnected || !hasWriteAuth) return;
@@ -763,7 +784,7 @@ public class NSClientService extends Service {
message.put("collection", dbr.collection);
message.put("data", new JSONObject(dbr.data));
mSocket.emit("dbAdd", message, ack);
- MainApp.bus().post(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID));
} catch (JSONException e) {
log.error("Unhandled exception", e);
}
@@ -772,17 +793,7 @@ public class NSClientService extends Service {
public void sendAlarmAck(AlarmAck alarmAck) {
if (!isConnected || !hasWriteAuth) return;
mSocket.emit("ack", alarmAck.level, alarmAck.group, alarmAck.silenceTime);
- MainApp.bus().post(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime));
- }
-
- @Subscribe
- public void onStatusEvent(NSAddAck ack) {
- if (ack.nsClientID != null) {
- uploadQueue.removeID(ack.json);
- MainApp.bus().post(new EventNSClientNewLog("DBADD", "Acked " + ack.nsClientID));
- } else {
- MainApp.bus().post(new EventNSClientNewLog("ERROR", "DBADD Unknown response"));
- }
+ RxBus.INSTANCE.send(new EventNSClientNewLog("ALARMACK ", alarmAck.level + " " + alarmAck.group + " " + alarmAck.silenceTime));
}
public void resend(final String reason) {
@@ -803,7 +814,7 @@ public class NSClientService extends Service {
}
lastResendTime = System.currentTimeMillis();
- MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend started: " + reason));
CloseableIterator iterator = null;
int maxcount = 30;
@@ -834,7 +845,7 @@ public class NSClientService extends Service {
log.error("Unhandled exception", e);
}
- MainApp.bus().post(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
+ RxBus.INSTANCE.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason));
}
});
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java
index b7d7cae4a0..046290500d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.java
@@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.overview;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
-
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
@@ -12,16 +11,6 @@ import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
-
-import androidx.fragment.app.Fragment;
-import androidx.fragment.app.FragmentActivity;
-import androidx.fragment.app.FragmentManager;
-import androidx.core.content.res.ResourcesCompat;
-import androidx.appcompat.app.AlertDialog;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.appcompat.widget.PopupMenu;
-import androidx.recyclerview.widget.RecyclerView;
-
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
@@ -36,8 +25,16 @@ import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
+import androidx.appcompat.app.AlertDialog;
+import androidx.appcompat.widget.PopupMenu;
+import androidx.core.content.res.ResourcesCompat;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentActivity;
+import androidx.fragment.app.FragmentManager;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
+
import com.jjoe64.graphview.GraphView;
-import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -83,6 +80,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
@@ -113,18 +111,23 @@ import info.nightscout.androidaps.utils.BolusWizard;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.DefaultValueHelper;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.Profiler;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.SingleClickButton;
import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.ToastUtils;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.utils.DateUtil.now;
public class OverviewFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private static Logger log = LoggerFactory.getLogger(L.OVERVIEW);
+ private CompositeDisposable disposable = new CompositeDisposable();
+
TextView timeView;
TextView bgView;
TextView arrowView;
@@ -340,6 +343,117 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
return view;
}
+ @Override
+ public void onPause() {
+ super.onPause();
+ disposable.clear();
+ sLoopHandler.removeCallbacksAndMessages(null);
+ unregisterForContextMenu(apsModeView);
+ unregisterForContextMenu(activeProfileView);
+ unregisterForContextMenu(tempTargetView);
+ }
+
+ @Override
+ public void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventRefreshOverview.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(eventOpenAPSUpdateGui -> scheduleUpdateGUI(eventOpenAPSUpdateGui.getFrom()),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventExtendedBolusChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempBasalChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventTempBasalChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTreatmentChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventTreatmentChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempTargetChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventTempTargetChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAcceptOpenLoopChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventAcceptOpenLoopChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventCareportalEventChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventCareportalEventChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventInitializationChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventInitializationChanged"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventAutosensCalculationFinished"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventProfileNeedsUpdate.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventProfileNeedsUpdate"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventPreferenceChange"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewOpenLoopNotification.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> scheduleUpdateGUI("EventNewOpenLoopNotification"),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPumpStatusChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updatePumpStatus(event.getStatus()),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventIobCalculationProgress.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (iobCalculationProgressView != null)
+ iobCalculationProgressView.setText(event.getProgress());
+ },
+ FabricPrivacy::logException
+ ));
+ sRefreshLoop = () -> {
+ scheduleUpdateGUI("refreshLoop");
+ sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
+ };
+ sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
+ registerForContextMenu(apsModeView);
+ registerForContextMenu(activeProfileView);
+ registerForContextMenu(tempTargetView);
+ updateGUI("onResume");
+ }
+
private void setupChartMenu(View view) {
chartButton = (ImageButton) view.findViewById(R.id.overview_chartMenuButton);
chartButton.setOnClickListener(v -> {
@@ -539,8 +653,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
- private void showSuspendtPump(ContextMenu menu,
- PumpDescription pumpDescription) {
+ private void showSuspendtPump(ContextMenu menu, PumpDescription pumpDescription) {
if (pumpDescription.tempDurationStep15mAllowed)
menu.add(MainApp.gs(R.string.disconnectpumpfor15m));
if (pumpDescription.tempDurationStep30mAllowed)
@@ -846,108 +959,6 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
}
- @Override
- public void onPause() {
- super.onPause();
- MainApp.bus().unregister(this);
- sLoopHandler.removeCallbacksAndMessages(null);
- unregisterForContextMenu(apsModeView);
- unregisterForContextMenu(activeProfileView);
- unregisterForContextMenu(tempTargetView);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- MainApp.bus().register(this);
- sRefreshLoop = () -> {
- scheduleUpdateGUI("refreshLoop");
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- };
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- registerForContextMenu(apsModeView);
- registerForContextMenu(activeProfileView);
- registerForContextMenu(tempTargetView);
- updateGUI("onResume");
- }
-
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged ev) {
- scheduleUpdateGUI("EventInitializationChanged");
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- scheduleUpdateGUI("EventPreferenceChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- scheduleUpdateGUI(ev.from);
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- scheduleUpdateGUI("EventAutosensCalculationFinished");
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- scheduleUpdateGUI("EventTreatmentChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventCareportalEventChange ev) {
- scheduleUpdateGUI("EventCareportalEventChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- scheduleUpdateGUI("EventTempBasalChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- scheduleUpdateGUI("EventExtendedBolusChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewOpenLoopNotification ev) {
- scheduleUpdateGUI("EventNewOpenLoopNotification");
- }
-
- @Subscribe
- public void onStatusEvent(final EventAcceptOpenLoopChange ev) {
- scheduleUpdateGUI("EventAcceptOpenLoopChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempTargetChange ev) {
- scheduleUpdateGUI("EventTempTargetChange");
- }
-
- @Subscribe
- public void onStatusEvent(final EventProfileNeedsUpdate ev) {
- scheduleUpdateGUI("EventProfileNeedsUpdate");
- }
-
- @Subscribe
- public void onStatusEvent(final EventPumpStatusChanged s) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> updatePumpStatus(s.textStatus()));
- }
-
- @Subscribe
- public void onStatusEvent(final EventIobCalculationProgress e) {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- if (iobCalculationProgressView != null)
- iobCalculationProgressView.setText(e.progress);
- });
- }
-
private void hideTempRecommendation() {
Activity activity = getActivity();
if (activity != null)
@@ -1135,7 +1146,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
}
// **** Calibration & CGM buttons ****
- boolean xDripIsBgSource = MainApp.getSpecificPlugin(SourceXdripPlugin.class) != null && MainApp.getSpecificPlugin(SourceXdripPlugin.class).isEnabled(PluginType.BGSOURCE);
+ boolean xDripIsBgSource = SourceXdripPlugin.getPlugin().isEnabled(PluginType.BGSOURCE);
boolean dexcomIsSource = SourceDexcomPlugin.INSTANCE.isEnabled(PluginType.BGSOURCE);
boolean bgAvailable = DatabaseHelper.actualBg() != null;
if (calibrationButton != null) {
@@ -1212,7 +1223,7 @@ public class OverviewFragment extends Fragment implements View.OnClickListener,
extendedBolusView.setVisibility(View.VISIBLE);
}
- activeProfileView.setText(ProfileFunctions.getInstance().getProfileName());
+ activeProfileView.setText(ProfileFunctions.getInstance().getProfileNameWithDuration());
if (profile.getPercentage() != 100 || profile.getTimeshift() != 0) {
activeProfileView.setBackgroundColor(MainApp.gc(R.color.ribbonWarning));
activeProfileView.setTextColor(MainApp.gc(R.color.ribbonTextWarning));
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt
index 0c5b3b4370..cece359f22 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt
@@ -45,7 +45,7 @@ object OverviewPlugin : PluginBase(PluginDescription()
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.add(n.notification))
- MainApp.bus().post(EventRefreshOverview("EventNewNotification"))
+ RxBus.send(EventRefreshOverview("EventNewNotification"))
}, {
FabricPrivacy.logException(it)
})
@@ -54,7 +54,7 @@ object OverviewPlugin : PluginBase(PluginDescription()
.observeOn(Schedulers.io())
.subscribe({ n ->
if (notificationStore.remove(n.id))
- MainApp.bus().post(EventRefreshOverview("EventDismissNotification"))
+ RxBus.send(EventRefreshOverview("EventDismissNotification"))
}, {
FabricPrivacy.logException(it)
})
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java
index 04da9761a3..645f6d2b19 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/BolusProgressDialog.java
@@ -14,8 +14,6 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -23,12 +21,18 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
+import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
public class BolusProgressDialog extends DialogFragment implements View.OnClickListener {
private static Logger log = LoggerFactory.getLogger(L.UI);
+ private CompositeDisposable disposable = new CompositeDisposable();
+
Button stopButton;
TextView statusView;
TextView stopPressedView;
@@ -91,11 +95,34 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
if (L.isEnabled(L.UI))
log.debug("onResume running");
}
- try {
- MainApp.bus().register(this);
- } catch (IllegalArgumentException e) {
- log.error("Already registered");
- }
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPumpStatusChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventDismissBolusProgressIfRunning.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (L.isEnabled(L.UI)) log.debug("EventDismissBolusProgressIfRunning");
+ if (BolusProgressDialog.running) dismiss();
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventOverviewBolusProgress.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (L.isEnabled(L.UI))
+ log.debug("Status: " + event.getStatus() + " Percent: " + event.getPercent());
+ statusView.setText(event.getStatus());
+ progressBar.setProgress(event.getPercent());
+ if (event.getPercent() == 100) {
+ stopButton.setVisibility(View.INVISIBLE);
+ scheduleDismiss();
+ }
+ state = event.getStatus();
+ }, FabricPrivacy::logException)
+ );
}
@Override
@@ -121,11 +148,7 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
log.debug("onPause");
running = false;
super.onPause();
- try {
- MainApp.bus().unregister(this);
- } catch (IllegalArgumentException e) {
- log.error("Already unregistered");
- }
+ disposable.clear();
}
@Override
@@ -149,43 +172,6 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL
}
}
- @Subscribe
- public void onStatusEvent(final EventOverviewBolusProgress ev) {
- Activity activity = getActivity();
- if (activity != null) {
- activity.runOnUiThread(() -> {
- if (L.isEnabled(L.UI))
- log.debug("Status: " + ev.status + " Percent: " + ev.percent);
- statusView.setText(ev.status);
- progressBar.setProgress(ev.percent);
- if (ev.percent == 100) {
- stopButton.setVisibility(View.INVISIBLE);
- scheduleDismiss();
- }
- });
- }
- state = ev.status;
- }
-
- @Subscribe
- public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) {
- if (L.isEnabled(L.UI))
- log.debug("EventDismissBolusprogressIfRunning");
- if (BolusProgressDialog.running) {
- dismiss();
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventPumpStatusChanged c) {
- if (L.isEnabled(L.UI))
- log.debug("EventPumpStatusChanged");
- Activity activity = getActivity();
- if (activity != null) {
- activity.runOnUiThread(() -> statusView.setText(c.textStatus()));
- }
- }
-
private void scheduleDismiss() {
if (L.isEnabled(L.UI))
log.debug("scheduleDismiss");
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt
index 1b52e5f3ff..efe800bef0 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/WizardDialog.kt
@@ -6,7 +6,7 @@ import android.text.Editable
import android.text.TextWatcher
import android.view.*
import android.widget.AdapterView
-import android.widget.AdapterView.*
+import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.CompoundButton
import androidx.fragment.app.DialogFragment
@@ -14,8 +14,8 @@ import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.db.BgReading
import info.nightscout.androidaps.db.DatabaseHelper
-import info.nightscout.androidaps.events.EventFeatureRunning
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
@@ -26,11 +26,11 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.*
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
-import kotlinx.android.synthetic.main.okcancel.*
import kotlinx.android.synthetic.main.overview_wizard_dialog.*
import org.slf4j.LoggerFactory
import java.text.DecimalFormat
import java.util.*
+import kotlin.math.abs
class WizardDialog : DialogFragment() {
private val log = LoggerFactory.getLogger(WizardDialog::class.java)
@@ -58,22 +58,22 @@ class WizardDialog : DialogFragment() {
this.parentContext = context
}
+ override fun onStart() {
+ super.onStart()
+ dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
+ }
+
override fun onDetach() {
super.onDetach()
this.parentContext = null
}
- override fun onResume() {
- super.onResume()
- MainApp.bus().post(EventFeatureRunning(EventFeatureRunning.Feature.WIZARD))
- }
-
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
- savedInstanceState.putDouble("treatments_wizard_bginput", treatments_wizard_bginput.value)
- savedInstanceState.putDouble("treatments_wizard_carbsinput", treatments_wizard_carbsinput.value)
- savedInstanceState.putDouble("treatments_wizard_correctioninput", treatments_wizard_correctioninput.value)
- savedInstanceState.putDouble("treatments_wizard_carbtimeinput", treatments_wizard_carbtimeinput.value)
+ savedInstanceState.putDouble("treatments_wizard_bg_input", treatments_wizard_bg_input.value)
+ savedInstanceState.putDouble("treatments_wizard_carbs_input", treatments_wizard_carbs_input.value)
+ savedInstanceState.putDouble("treatments_wizard_correction_input", treatments_wizard_correction_input.value)
+ savedInstanceState.putDouble("treatments_wizard_carb_time_input", treatments_wizard_carb_time_input.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
@@ -95,25 +95,26 @@ class WizardDialog : DialogFragment() {
val maxCarbs = MainApp.getConstraintChecker().maxCarbsAllowed.value()
val maxCorrection = MainApp.getConstraintChecker().maxBolusAllowed.value()
- treatments_wizard_bginput.setParams(savedInstanceState?.getDouble("treatments_wizard_bginput")
+ treatments_wizard_bg_input.setParams(savedInstanceState?.getDouble("treatments_wizard_bg_input")
?: 0.0, 0.0, 500.0, 0.1, DecimalFormat("0.0"), false, ok, textWatcher)
- treatments_wizard_carbsinput.setParams(savedInstanceState?.getDouble("treatments_wizard_carbsinput")
+ treatments_wizard_carbs_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carbs_input")
?: 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false, ok, textWatcher)
- val bolusstep = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription?.bolusStep
+ val bolusStep = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription?.bolusStep
?: 0.1
- treatments_wizard_correctioninput.setParams(savedInstanceState?.getDouble("treatments_wizard_correctioninput")
- ?: 0.0, -maxCorrection, maxCorrection, bolusstep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
- treatments_wizard_carbtimeinput.setParams(savedInstanceState?.getDouble("treatments_wizard_carbtimeinput")
+ treatments_wizard_correction_input.setParams(savedInstanceState?.getDouble("treatments_wizard_correction_input")
+ ?: 0.0, -maxCorrection, maxCorrection, bolusStep, DecimalFormatter.pumpSupportedBolusFormat(), false, ok, textWatcher)
+ treatments_wizard_carb_time_input.setParams(savedInstanceState?.getDouble("treatments_wizard_carb_time_input")
?: 0.0, -60.0, 60.0, 5.0, DecimalFormat("0"), false, ok, textWatcher)
initDialog()
- treatments_wizard_percent_used.text = SP.getInt(R.string.key_boluswizard_percentage, 100).toString() + "%"
+ treatments_wizard_percent_used.text = MainApp.gs(R.string.format_percent, SP.getInt(R.string.key_boluswizard_percentage, 100))
// ok button
ok.setOnClickListener {
if (okClicked) {
log.debug("guarding: ok already clicked")
} else {
okClicked = true
+ calculateInsulin()
parentContext?.let { context ->
wizard?.confirmAndExecute(context)
}
@@ -130,6 +131,18 @@ class WizardDialog : DialogFragment() {
treatments_wizard_bolusiobcheckbox.setOnCheckedChangeListener { buttonView, _ -> onCheckedChanged(buttonView) }
treatments_wizard_bgtrendcheckbox.setOnCheckedChangeListener { buttonView, _ -> onCheckedChanged(buttonView) }
treatments_wizard_sbcheckbox.setOnCheckedChangeListener { buttonView, _ -> onCheckedChanged(buttonView) }
+
+ val showCalc = SP.getBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), false)
+ treatments_wizard_delimiter.visibility = if (showCalc) View.VISIBLE else View.GONE
+ treatments_wizard_resulttable.visibility = if (showCalc) View.VISIBLE else View.GONE
+ treatments_wizard_calculationcheckbox.isChecked = showCalc
+ treatments_wizard_calculationcheckbox.setOnCheckedChangeListener { _, isChecked ->
+ run {
+ SP.putBoolean(MainApp.gs(R.string.key_wizard_calculation_visible), isChecked)
+ treatments_wizard_delimiter.visibility = if (isChecked) View.VISIBLE else View.GONE
+ treatments_wizard_resulttable.visibility = if (isChecked) View.VISIBLE else View.GONE
+ }
+ }
// profile spinner
treatments_wizard_profile.onItemSelectedListener = object : OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
@@ -160,7 +173,7 @@ class WizardDialog : DialogFragment() {
disposable.clear()
}
- fun onCheckedChanged(buttonView: CompoundButton) {
+ private fun onCheckedChanged(buttonView: CompoundButton) {
saveCheckedStates()
treatments_wizard_ttcheckbox.isEnabled = treatments_wizard_bgcheckbox.isChecked && TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
if (buttonView.id == treatments_wizard_cobcheckbox.id)
@@ -212,17 +225,17 @@ class WizardDialog : DialogFragment() {
val units = profile.units
treatments_wizard_bgunits.text = units
if (units == Constants.MGDL)
- treatments_wizard_bginput.setStep(1.0)
+ treatments_wizard_bg_input.setStep(1.0)
else
- treatments_wizard_bginput.setStep(0.1)
+ treatments_wizard_bg_input.setStep(0.1)
// Set BG if not old
val lastBg = DatabaseHelper.actualBg()
if (lastBg != null) {
- treatments_wizard_bginput.value = lastBg.valueToUnits(units)
+ treatments_wizard_bg_input.value = lastBg.valueToUnits(units)
} else {
- treatments_wizard_bginput.value = 0.0
+ treatments_wizard_bg_input.value = 0.0
}
treatments_wizard_ttcheckbox.isEnabled = TreatmentsPlugin.getPlugin().tempTargetFromHistory != null
@@ -255,37 +268,29 @@ class WizardDialog : DialogFragment() {
if (specificProfile == null) return
// Entered values
- var c_bg = SafeParse.stringToDouble(treatments_wizard_bginput.text)
- val c_carbs = SafeParse.stringToInt(treatments_wizard_carbsinput.text)
- var c_correction = SafeParse.stringToDouble(treatments_wizard_correctioninput.text)
- val corrAfterConstraint = c_correction
- if (c_correction > 0)
- c_correction = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(c_correction)).value()
- if (Math.abs(c_correction - corrAfterConstraint) > 0.01) { // c_correction != corrAfterConstraint doesn't work
- treatments_wizard_correctioninput.value = 0.0
- ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.bolusconstraintapplied))
- return
- }
- val carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(c_carbs)).value()
- if (Math.abs(c_carbs - carbsAfterConstraint) > 0.01) {
- treatments_wizard_carbsinput.value = 0.0
+ var bg = SafeParse.stringToDouble(treatments_wizard_bg_input.text)
+ val carbs = SafeParse.stringToInt(treatments_wizard_carbs_input.text)
+ val correction = SafeParse.stringToDouble(treatments_wizard_correction_input.text)
+ val carbsAfterConstraint = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(carbs)).value()
+ if (abs(carbs - carbsAfterConstraint) > 0.01) {
+ treatments_wizard_carbs_input.value = 0.0
ToastUtils.showToastInUiThread(MainApp.instance().applicationContext, MainApp.gs(R.string.carbsconstraintapplied))
return
}
- c_bg = if (treatments_wizard_bgcheckbox.isChecked) c_bg else 0.0
+ bg = if (treatments_wizard_bgcheckbox.isChecked) bg else 0.0
val tempTarget = if (treatments_wizard_ttcheckbox.isChecked) TreatmentsPlugin.getPlugin().tempTargetFromHistory else null
// COB
- var c_cob = 0.0
+ var cob = 0.0
if (treatments_wizard_cobcheckbox.isChecked) {
val cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "Wizard COB")
- cobInfo.displayCob?.let { c_cob = it }
+ cobInfo.displayCob?.let { cob = it }
}
- val carbTime = SafeParse.stringToInt(treatments_wizard_carbtimeinput.text)
+ val carbTime = SafeParse.stringToInt(treatments_wizard_carb_time_input.text)
- wizard = BolusWizard(specificProfile, profileName, tempTarget, carbsAfterConstraint, c_cob, c_bg, corrAfterConstraint,
+ wizard = BolusWizard(specificProfile, profileName, tempTarget, carbsAfterConstraint, cob, bg, correction,
SP.getInt(R.string.key_boluswizard_percentage, 100).toDouble(),
treatments_wizard_bgcheckbox.isChecked,
treatments_wizard_cobcheckbox.isChecked,
@@ -297,10 +302,10 @@ class WizardDialog : DialogFragment() {
treatment_wizard_notes.text.toString(), carbTime)
wizard?.let { wizard ->
- treatments_wizard_bg.text = c_bg.toString() + " ISF: " + DecimalFormatter.to1Decimal(wizard.sens)
+ treatments_wizard_bg.text = String.format(MainApp.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(bg, specificProfile.units)).valueToUnitsToString(specificProfile.units), wizard.sens)
treatments_wizard_bginsulin.text = StringUtils.formatInsulin(wizard.insulinFromBG)
- treatments_wizard_carbs.text = DecimalFormatter.to0Decimal(c_carbs.toDouble()) + "g IC: " + DecimalFormatter.to1Decimal(wizard.ic)
+ treatments_wizard_carbs.text = String.format(MainApp.gs(R.string.format_carbs_ic), carbs.toDouble(), wizard.ic)
treatments_wizard_carbsinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCarbs)
treatments_wizard_bolusiobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromBolusIOB)
@@ -324,7 +329,7 @@ class WizardDialog : DialogFragment() {
// COB
if (treatments_wizard_cobcheckbox.isChecked) {
- treatments_wizard_cob.text = DecimalFormatter.to2Decimal(c_cob) + "g IC: " + DecimalFormatter.to1Decimal(wizard.ic)
+ treatments_wizard_cob.text = String.format(MainApp.gs(R.string.format_cob_ic), cob, wizard.ic)
treatments_wizard_cobinsulin.text = StringUtils.formatInsulin(wizard.insulinFromCOB)
} else {
treatments_wizard_cob.text = ""
@@ -332,12 +337,12 @@ class WizardDialog : DialogFragment() {
}
if (wizard.calculatedTotalInsulin > 0.0 || carbsAfterConstraint > 0.0) {
- val insulinText = if (wizard.calculatedTotalInsulin > 0.0) DecimalFormatter.toPumpSupportedBolus(wizard.calculatedTotalInsulin) + "U" else ""
- val carbsText = if (carbsAfterConstraint > 0.0) DecimalFormatter.to0Decimal(carbsAfterConstraint.toDouble()) + "g" else ""
- treatments_wizard_total.text = MainApp.gs(R.string.result) + ": " + insulinText + " " + carbsText
+ val insulinText = if (wizard.calculatedTotalInsulin > 0.0) MainApp.gs(R.string.formatinsulinunits, wizard.calculatedTotalInsulin) else ""
+ val carbsText = if (carbsAfterConstraint > 0.0) MainApp.gs(R.string.format_carbs, carbsAfterConstraint) else ""
+ treatments_wizard_total.text = MainApp.gs(R.string.result_insulin_carbs, insulinText, carbsText)
ok.visibility = View.VISIBLE
} else {
- treatments_wizard_total.text = MainApp.gs(R.string.missing) + " " + DecimalFormatter.to0Decimal(wizard.carbsEquivalent) + "g"
+ treatments_wizard_total.text = MainApp.gs(R.string.missing_carbs, wizard.carbsEquivalent.toInt())
ok.visibility = View.INVISIBLE
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt
new file mode 100644
index 0000000000..53ab699d9c
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt
@@ -0,0 +1,6 @@
+package info.nightscout.androidaps.plugins.general.overview.events
+
+import info.nightscout.androidaps.data.PumpEnactResult
+import info.nightscout.androidaps.events.Event
+
+class EventDismissBolusProgressIfRunning(val result: PumpEnactResult?) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java
deleted file mode 100644
index 2022a4d74b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.general.overview.events;
-
-import info.nightscout.androidaps.data.PumpEnactResult;
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by adrian on 20/02/17.
- */
-
-public class EventDismissBolusprogressIfRunning extends Event {
- public final PumpEnactResult result;
-
- public EventDismissBolusprogressIfRunning(PumpEnactResult result) {
- this.result = result;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java
deleted file mode 100644
index 3a7c50faac..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.java
+++ /dev/null
@@ -1,27 +0,0 @@
-package info.nightscout.androidaps.plugins.general.overview.events;
-
-import info.nightscout.androidaps.plugins.treatments.Treatment;
-import info.nightscout.androidaps.events.Event;
-
-public class EventOverviewBolusProgress extends Event {
- public String status = "";
- public Treatment t = null;
- public int percent = 0;
- public int bolusId;
- private static EventOverviewBolusProgress eventOverviewBolusProgress = null;
-
- public EventOverviewBolusProgress() {
- }
-
- public boolean isSMB(){
- return (t != null) && t.isSMB;
- }
-
- public static EventOverviewBolusProgress getInstance() {
- if(eventOverviewBolusProgress == null) {
- eventOverviewBolusProgress = new EventOverviewBolusProgress();
- }
- return eventOverviewBolusProgress;
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt
new file mode 100644
index 0000000000..52b62790da
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt
@@ -0,0 +1,12 @@
+package info.nightscout.androidaps.plugins.general.overview.events
+
+import info.nightscout.androidaps.plugins.treatments.Treatment
+import info.nightscout.androidaps.events.Event
+
+object EventOverviewBolusProgress : Event() {
+ var status = ""
+ var t: Treatment? = null
+ var percent = 0
+
+ fun isSMB(): Boolean = t?.isSMB ?: false
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java
index f46e5184cd..9685445ce0 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.java
@@ -172,7 +172,7 @@ public class NotificationStore {
removeExpired();
unSnooze();
if (store.size() > 0) {
- NotificationRecyclerViewAdapter adapter = new NotificationRecyclerViewAdapter(store);
+ NotificationRecyclerViewAdapter adapter = new NotificationRecyclerViewAdapter(cloneStore());
notificationsView.setAdapter(adapter);
notificationsView.setVisibility(View.VISIBLE);
} else {
@@ -180,4 +180,9 @@ public class NotificationStore {
}
}
+ private synchronized List cloneStore() {
+ List clone = new ArrayList<>(store.size());
+ clone.addAll(store);
+ return clone;
+ }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java
index 13310d70a8..007298ac76 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.java
@@ -1,26 +1,27 @@
package info.nightscout.androidaps.plugins.general.persistentNotification;
-import android.app.Notification;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.annotation.Nullable;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Keeps AndroidAPS in foreground state, so it won't be terminated by Android nor get restricted by the background execution limits
*/
public class DummyService extends Service {
private static Logger log = LoggerFactory.getLogger(L.CORE);
+ private CompositeDisposable disposable = new CompositeDisposable();
@Nullable
@Override
@@ -28,6 +29,30 @@ public class DummyService extends Service {
return null;
}
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ // TODO: I guess this was moved here in order to adhere to the 5 seconds rule to call "startForeground" after a Service was called as Foreground service?
+ // As onCreate() is not called every time a service is started, copied to onStartCommand().
+ startForeground(PersistentNotificationPlugin.ONGOING_NOTIFICATION_ID, PersistentNotificationPlugin.getPlugin().getLastNotification());
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received");
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
+ }
+
+ @Override
+ public void onDestroy() {
+ if (L.isEnabled(L.CORE)) log.debug("onDestroy");
+ disposable.clear();
+ super.onDestroy();
+ stopForeground(true);
+ }
+
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
@@ -35,28 +60,4 @@ public class DummyService extends Service {
return START_STICKY;
}
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.CORE))
- log.debug("EventAppExit received");
-
- stopSelf();
- }
-
- @Override
- public void onCreate() {
- super.onCreate();
- // TODO: I guess this was moved here in order to adhere to the 5 seconds rule to call "startForeground" after a Service was called as Foreground service?
- // As onCreate() is not called every time a service is started, copied to onStartCommand().
- startForeground(PersistentNotificationPlugin.ONGOING_NOTIFICATION_ID, PersistentNotificationPlugin.getPlugin().getLastNotification());
- MainApp.bus().register(this);
- }
-
- @Override
- public void onDestroy() {
- if (L.isEnabled(L.CORE))
- log.debug("onDestroy");
- MainApp.bus().unregister(this);
- stopForeground(true);
- }
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java
index 655435f400..fdee040682 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.java
@@ -15,10 +15,6 @@ import androidx.core.app.NotificationCompat;
import androidx.core.app.RemoteInput;
import androidx.core.app.TaskStackBuilder;
-import com.squareup.otto.Subscribe;
-
-import javax.annotation.Nonnull;
-
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp;
@@ -37,6 +33,7 @@ import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
@@ -44,6 +41,9 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by adrian on 23/12/16.
@@ -51,6 +51,8 @@ import info.nightscout.androidaps.utils.DecimalFormatter;
public class PersistentNotificationPlugin extends PluginBase {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
private static PersistentNotificationPlugin plugin;
private Notification notification;
@@ -91,7 +93,54 @@ public class PersistentNotificationPlugin extends PluginBase {
protected void onStart() {
super.onStart();
createNotificationChannel(); // make sure channels exist before triggering updates through the bus
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventRefreshOverview.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempBasalChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTreatmentChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventInitializationChanged.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewBasalProfile.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> triggerNotificationUpdate(false),
+ FabricPrivacy::logException
+ ));
triggerNotificationUpdate(true);
}
@@ -109,7 +158,7 @@ public class PersistentNotificationPlugin extends PluginBase {
@Override
protected void onStop() {
- MainApp.bus().unregister(this);
+ disposable.clear();
MainApp.instance().stopService(new Intent(MainApp.instance(), DummyService.class));
super.onStop();
}
@@ -285,46 +334,4 @@ public class PersistentNotificationPlugin extends PluginBase {
throw new IllegalStateException("Notification is null");
}
}
-
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBasalProfile ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged ev) {
- triggerNotificationUpdate(false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- triggerNotificationUpdate(false);
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java
deleted file mode 100644
index 4b05072eb1..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.utils.DateUtil;
-
-class AuthRequest {
- private static Logger log = LoggerFactory.getLogger(L.SMS);
-
- Sms requester;
- String confirmCode;
- private Runnable action;
-
- private long date;
-
- private boolean processed;
- private SmsCommunicatorPlugin plugin;
-
- AuthRequest(SmsCommunicatorPlugin plugin, Sms requester, String requestText, String confirmCode, SmsAction action) {
- this.requester = requester;
- this.confirmCode = confirmCode;
- this.action = action;
- this.plugin = plugin;
-
- this.date = DateUtil.now();
-
- plugin.sendSMS(new Sms(requester.phoneNumber, requestText));
- }
-
- void action(String codeReceived) {
- if (processed) {
- if (L.isEnabled(L.SMS))
- log.debug("Already processed");
- return;
- }
- if (!confirmCode.equals(codeReceived)) {
- processed = true;
- if (L.isEnabled(L.SMS))
- log.debug("Wrong code");
- plugin.sendSMS(new Sms(requester.phoneNumber, R.string.sms_wrongcode));
- return;
- }
- if (DateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
- processed = true;
- if (L.isEnabled(L.SMS))
- log.debug("Processing confirmed SMS: " + requester.text);
- if (action != null)
- action.run();
- return;
- }
- if (L.isEnabled(L.SMS))
- log.debug("Timed out SMS: " + requester.text);
- }
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt
new file mode 100644
index 0000000000..48e816928f
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt
@@ -0,0 +1,38 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator
+
+import info.nightscout.androidaps.Constants
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.utils.DateUtil
+import org.slf4j.LoggerFactory
+
+class AuthRequest internal constructor(val plugin: SmsCommunicatorPlugin, var requester: Sms, requestText: String, var confirmCode: String, val action: SmsAction) {
+ private val log = LoggerFactory.getLogger(L.SMS)
+
+ private val date = DateUtil.now()
+ private var processed = false
+
+ init {
+ plugin.sendSMS(Sms(requester.phoneNumber, requestText))
+ }
+
+ fun action(codeReceived: String) {
+ if (processed) {
+ if (L.isEnabled(L.SMS)) log.debug("Already processed")
+ return
+ }
+ if (confirmCode != codeReceived) {
+ processed = true
+ if (L.isEnabled(L.SMS)) log.debug("Wrong code")
+ plugin.sendSMS(Sms(requester.phoneNumber, R.string.sms_wrongcode))
+ return
+ }
+ if (DateUtil.now() - date < Constants.SMS_CONFIRM_TIMEOUT) {
+ processed = true
+ if (L.isEnabled(L.SMS)) log.debug("Processing confirmed SMS: " + requester.text)
+ action.run()
+ return
+ }
+ if (L.isEnabled(L.SMS)) log.debug("Timed out SMS: " + requester.text)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java
deleted file mode 100644
index 2eedfa0a51..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.java
+++ /dev/null
@@ -1,42 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator;
-
-import android.telephony.SmsMessage;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.utils.DateUtil;
-
-class Sms {
- String phoneNumber;
- String text;
- long date;
- boolean received = false;
- boolean sent = false;
- boolean processed = false;
- boolean ignored = false;
-
- Sms(SmsMessage message) {
- phoneNumber = message.getOriginatingAddress();
- text = message.getMessageBody();
- date = message.getTimestampMillis();
- received = true;
- }
-
- Sms(String phoneNumber, String text) {
- this.phoneNumber = phoneNumber;
- this.text = text;
- this.date = DateUtil.now();
- sent = true;
- }
-
- Sms(String phoneNumber, int textId) {
- this.phoneNumber = phoneNumber;
- this.text = MainApp.gs(textId);
- this.date = DateUtil.now();
- sent = true;
- }
-
- public String toString() {
- return "SMS from " + phoneNumber + ": " + text;
- }
-}
-
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt
new file mode 100644
index 0000000000..868620be2e
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/Sms.kt
@@ -0,0 +1,40 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator
+
+import android.telephony.SmsMessage
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.utils.DateUtil
+
+class Sms {
+ var phoneNumber: String
+ var text: String
+ var date: Long
+ var received = false
+ var sent = false
+ var processed = false
+ var ignored = false
+
+ internal constructor(message: SmsMessage) {
+ phoneNumber = message.originatingAddress ?: ""
+ text = message.messageBody
+ date = message.timestampMillis
+ received = true
+ }
+
+ internal constructor(phoneNumber: String, text: String) {
+ this.phoneNumber = phoneNumber
+ this.text = text
+ date = DateUtil.now()
+ sent = true
+ }
+
+ internal constructor(phoneNumber: String, textId: Int) {
+ this.phoneNumber = phoneNumber
+ text = MainApp.gs(textId)
+ date = DateUtil.now()
+ sent = true
+ }
+
+ override fun toString(): String {
+ return "SMS from $phoneNumber: $text"
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java
deleted file mode 100644
index 6b5d5b8747..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.java
+++ /dev/null
@@ -1,33 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator;
-
-abstract class SmsAction implements Runnable {
- Double aDouble;
- Integer anInteger;
- Integer secondInteger;
- String aString;
-
- SmsAction() {}
-
- SmsAction(Double aDouble) {
- this.aDouble = aDouble;
- }
-
- SmsAction(Double aDouble, Integer secondInteger) {
- this.aDouble = aDouble;
- this.secondInteger = secondInteger;
- }
-
- SmsAction(String aString, Integer secondInteger) {
- this.aString = aString;
- this.secondInteger = secondInteger;
- }
-
- SmsAction(Integer anInteger) {
- this.anInteger = anInteger;
- }
-
- SmsAction(Integer anInteger, Integer secondInteger) {
- this.anInteger = anInteger;
- this.secondInteger = secondInteger;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt
new file mode 100644
index 0000000000..98c892d918
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsAction.kt
@@ -0,0 +1,68 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator
+
+abstract class SmsAction : Runnable {
+ var aDouble: Double? = null
+ var anInteger: Int? = null
+ var secondInteger: Int? = null
+ var secondLong: Long? = null
+ var aString: String? = null
+
+ internal constructor()
+ internal constructor(aDouble: Double) {
+ this.aDouble = aDouble
+ }
+
+ internal constructor(aDouble: Double, secondInteger: Int) {
+ this.aDouble = aDouble
+ this.secondInteger = secondInteger
+ }
+
+ internal constructor(aString: String, secondInteger: Int) {
+ this.aString = aString
+ this.secondInteger = secondInteger
+ }
+
+ internal constructor(anInteger: Int) {
+ this.anInteger = anInteger
+ }
+
+ internal constructor(anInteger: Int, secondInteger: Int) {
+ this.anInteger = anInteger
+ this.secondInteger = secondInteger
+ }
+
+ internal constructor(anInteger: Int, secondLong: Long) {
+ this.anInteger = anInteger
+ this.secondLong = secondLong
+ }
+
+ fun aDouble(): Double {
+ return aDouble?.let {
+ aDouble
+ } ?: throw IllegalStateException()
+ }
+
+ fun anInteger(): Int {
+ return anInteger?.let {
+ anInteger
+ } ?: throw IllegalStateException()
+ }
+
+ fun secondInteger(): Int {
+ return secondInteger?.let {
+ secondInteger
+ } ?: throw IllegalStateException()
+ }
+
+ fun secondLong(): Long {
+ return secondLong?.let {
+ secondLong
+ } ?: throw IllegalStateException()
+ }
+
+ fun aString(): String {
+ return aString?.let {
+ aString
+ } ?: throw IllegalStateException()
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java
deleted file mode 100644
index d1c4adf5fe..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.java
+++ /dev/null
@@ -1,73 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.text.Html;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import java.util.Collections;
-import java.util.Comparator;
-
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui;
-import info.nightscout.androidaps.utils.DateUtil;
-
-public class SmsCommunicatorFragment extends SubscriberFragment {
- TextView logView;
-
- public SmsCommunicatorFragment() {
- super();
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View view = inflater.inflate(R.layout.smscommunicator_fragment, container, false);
-
- logView = (TextView) view.findViewById(R.id.smscommunicator_log);
-
- return view;
- }
-
- @Subscribe
- public void onStatusEvent(final EventSmsCommunicatorUpdateGui ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- class CustomComparator implements Comparator {
- public int compare(Sms object1, Sms object2) {
- return (int) (object1.date - object2.date);
- }
- }
- Collections.sort(SmsCommunicatorPlugin.getPlugin().messages, new CustomComparator());
- int messagesToShow = 40;
-
- int start = Math.max(0, SmsCommunicatorPlugin.getPlugin().messages.size() - messagesToShow);
-
- String logText = "";
- for (int x = start; x < SmsCommunicatorPlugin.getPlugin().messages.size(); x++) {
- Sms sms = SmsCommunicatorPlugin.getPlugin().messages.get(x);
- if (sms.ignored) {
- logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + " ";
- } else if (sms.received) {
- logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + " ";
- } else if (sms.sent) {
- logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? "● " : "○ ") + sms.phoneNumber + " " + sms.text + " ";
- }
- }
- logView.setText(Html.fromHtml(logText));
- });
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt
new file mode 100644
index 0000000000..90ec078931
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt
@@ -0,0 +1,70 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator
+
+import android.os.Bundle
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.plugins.bus.RxBus.toObservable
+import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui
+import info.nightscout.androidaps.utils.DateUtil
+import info.nightscout.androidaps.utils.FabricPrivacy
+import info.nightscout.androidaps.utils.HtmlHelper
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.smscommunicator_fragment.*
+import java.util.*
+import kotlin.math.max
+
+class SmsCommunicatorFragment : Fragment() {
+ private val disposable = CompositeDisposable()
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
+ savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.smscommunicator_fragment, container, false)
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+ disposable.add(toObservable(EventSmsCommunicatorUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGui() }) { FabricPrivacy.logException(it) }
+ )
+ updateGui()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ }
+
+ fun updateGui() {
+ class CustomComparator : Comparator {
+ override fun compare(object1: Sms, object2: Sms): Int {
+ return (object1.date - object2.date).toInt()
+ }
+ }
+ Collections.sort(SmsCommunicatorPlugin.messages, CustomComparator())
+ val messagesToShow = 40
+ val start = max(0, SmsCommunicatorPlugin.messages.size - messagesToShow)
+ var logText = ""
+ for (x in start until SmsCommunicatorPlugin.messages.size) {
+ val sms = SmsCommunicatorPlugin.messages[x]
+ when {
+ sms.ignored -> {
+ logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + " "
+ }
+ sms.received -> {
+ logText += DateUtil.timeString(sms.date) + " <<< " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + " "
+ }
+ sms.sent -> {
+ logText += DateUtil.timeString(sms.date) + " >>> " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + " "
+ }
+ }
+ }
+ smscommunicator_log?.text = HtmlHelper.fromHtml(logText)
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java
deleted file mode 100644
index d1494e6033..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.java
+++ /dev/null
@@ -1,807 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator;
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.telephony.SmsManager;
-import android.telephony.SmsMessage;
-
-import com.squareup.otto.Subscribe;
-
-import org.apache.commons.lang3.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.text.Normalizer;
-import java.util.ArrayList;
-import java.util.List;
-
-import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.DetailedBolusInfo;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.Profile;
-import info.nightscout.androidaps.data.ProfileStore;
-import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.db.DatabaseHelper;
-import info.nightscout.androidaps.db.Source;
-import info.nightscout.androidaps.events.EventPreferenceChange;
-import info.nightscout.androidaps.events.EventRefreshOverview;
-import info.nightscout.androidaps.interfaces.Constraint;
-import info.nightscout.androidaps.interfaces.PluginBase;
-import info.nightscout.androidaps.interfaces.PluginDescription;
-import info.nightscout.androidaps.interfaces.PluginType;
-import info.nightscout.androidaps.interfaces.ProfileInterface;
-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.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
-import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
-import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
-import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
-import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus;
-import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.queue.Callback;
-import info.nightscout.androidaps.utils.DateUtil;
-import info.nightscout.androidaps.utils.DecimalFormatter;
-import info.nightscout.androidaps.utils.SP;
-import info.nightscout.androidaps.utils.SafeParse;
-import info.nightscout.androidaps.utils.XdripCalibrations;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class SmsCommunicatorPlugin extends PluginBase {
- private static Logger log = LoggerFactory.getLogger(L.SMS);
-
- private static SmsCommunicatorPlugin smsCommunicatorPlugin;
-
- public static SmsCommunicatorPlugin getPlugin() {
-
- if (smsCommunicatorPlugin == null) {
- smsCommunicatorPlugin = new SmsCommunicatorPlugin();
- }
- return smsCommunicatorPlugin;
- }
-
- List allowedNumbers = new ArrayList<>();
-
- AuthRequest messageToConfirm = null;
-
- long lastRemoteBolusTime = 0;
-
- ArrayList messages = new ArrayList<>();
-
- SmsCommunicatorPlugin() {
- super(new PluginDescription()
- .mainType(PluginType.GENERAL)
- .fragmentClass(SmsCommunicatorFragment.class.getName())
- .pluginName(R.string.smscommunicator)
- .shortName(R.string.smscommunicator_shortname)
- .preferencesId(R.xml.pref_smscommunicator)
- .description(R.string.description_sms_communicator)
- );
- processSettings(null);
- }
-
- @Override
- protected void onStart() {
- MainApp.bus().register(this);
- super.onStart();
- }
-
- @Override
- protected void onStop() {
- MainApp.bus().unregister(this);
- super.onStop();
- }
-
- @Subscribe
- public void processSettings(final EventPreferenceChange ev) {
- if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) {
- String settings = SP.getString(R.string.key_smscommunicator_allowednumbers, "");
-
- allowedNumbers.clear();
- String[] substrings = settings.split(";");
- for (String number : substrings) {
- String cleaned = number.replaceAll("\\s+", "");
- allowedNumbers.add(cleaned);
- log.debug("Found allowed number: " + cleaned);
- }
- }
- }
-
- boolean isCommand(String command, String number) {
- switch (command.toUpperCase()) {
- case "BG":
- case "LOOP":
- case "TREATMENTS":
- case "NSCLIENT":
- case "PUMP":
- case "BASAL":
- case "BOLUS":
- case "EXTENDED":
- case "CAL":
- case "PROFILE":
- return true;
- }
- if (messageToConfirm != null && messageToConfirm.requester.phoneNumber.equals(number))
- return true;
- return false;
- }
-
- boolean isAllowedNumber(String number) {
- for (String num : allowedNumbers) {
- if (num.equals(number)) return true;
- }
- return false;
- }
-
- public void handleNewData(Intent intent) {
- Bundle bundle = intent.getExtras();
- if (bundle == null) return;
-
- Object[] pdus = (Object[]) bundle.get("pdus");
- if (pdus != null) {
- // For every SMS message received
- for (Object pdu : pdus) {
- SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);
- processSms(new Sms(message));
- }
- }
- }
-
- void processSms(final Sms receivedSms) {
- if (!isEnabled(PluginType.GENERAL)) {
- log.debug("Ignoring SMS. Plugin disabled.");
- return;
- }
- if (!isAllowedNumber(receivedSms.phoneNumber)) {
- log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed");
- receivedSms.ignored = true;
- messages.add(receivedSms);
- MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
- return;
- }
-
- messages.add(receivedSms);
- log.debug(receivedSms.toString());
-
- String[] splitted = receivedSms.text.split("\\s+");
- boolean remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false);
-
- if (splitted.length > 0 && isCommand(splitted[0].toUpperCase(), receivedSms.phoneNumber)) {
- switch (splitted[0].toUpperCase()) {
- case "BG":
- processBG(splitted, receivedSms);
- break;
- case "LOOP":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2 || splitted.length == 3)
- processLOOP(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "TREATMENTS":
- if (splitted.length == 2)
- processTREATMENTS(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "NSCLIENT":
- if (splitted.length == 2)
- processNSCLIENT(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "PUMP":
- processPUMP(splitted, receivedSms);
- break;
- case "PROFILE":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2 || splitted.length == 3)
- processPROFILE(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "BASAL":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2 || splitted.length == 3)
- processBASAL(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "EXTENDED":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2 || splitted.length == 3)
- processEXTENDED(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "BOLUS":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2 && DateUtil.now() - lastRemoteBolusTime < Constants.remoteBolusMinDistance)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotebolusnotallowed));
- else if (splitted.length == 2 && ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended())
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.pumpsuspended));
- else if (splitted.length == 2)
- processBOLUS(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- case "CAL":
- if (!remoteCommandsAllowed)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed));
- else if (splitted.length == 2)
- processCAL(splitted, receivedSms);
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- default: // expect passCode here
- if (messageToConfirm != null && messageToConfirm.requester.phoneNumber.equals(receivedSms.phoneNumber)) {
- messageToConfirm.action(splitted[0]);
- messageToConfirm = null;
- } else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_unknowncommand));
- break;
- }
- }
-
- MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
- }
-
- @SuppressWarnings("unused")
- private void processBG(String[] splitted, Sms receivedSms) {
- BgReading actualBG = DatabaseHelper.actualBg();
- BgReading lastBG = DatabaseHelper.lastBg();
-
- String reply = "";
-
- String units = ProfileFunctions.getInstance().getProfileUnits();
-
- if (actualBG != null) {
- reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", ";
- } else if (lastBG != null) {
- Long agoMsec = System.currentTimeMillis() - lastBG.date;
- int agoMin = (int) (agoMsec / 60d / 1000d);
- reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", ";
- }
- GlucoseStatus glucoseStatus = GlucoseStatus.getGlucoseStatusData();
- if (glucoseStatus != null)
- reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", ";
-
- TreatmentsPlugin.getPlugin().updateTotalIOBTreatments();
- IobTotal bolusIob = TreatmentsPlugin.getPlugin().getLastCalculationTreatments().round();
- TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals();
- IobTotal basalIob = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals().round();
-
- String cobText = MainApp.gs(R.string.value_unavailable_short);
- CobInfo cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB");
-
- reply += MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
- + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
- + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), "
- + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString();
-
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- receivedSms.processed = true;
- }
-
- private void processLOOP(String[] splitted, Sms receivedSms) {
- String reply;
- switch (splitted[1].toUpperCase()) {
- case "DISABLE":
- case "STOP":
- LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) {
- loopPlugin.setPluginEnabled(PluginType.LOOP, false);
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_STOP"));
- String reply = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
- MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- });
- } else {
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisdisabled));
- }
- receivedSms.processed = true;
- break;
- case "ENABLE":
- case "START":
- loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) {
- loopPlugin.setPluginEnabled(PluginType.LOOP, true);
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loophasbeenenabled));
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_START"));
- } else {
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisenabled));
- }
- receivedSms.processed = true;
- break;
- case "STATUS":
- loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class);
- if (loopPlugin != null) {
- if (loopPlugin.isEnabled(PluginType.LOOP)) {
- if (loopPlugin.isSuspended())
- reply = String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend());
- else
- reply = MainApp.gs(R.string.smscommunicator_loopisenabled);
- } else {
- reply = MainApp.gs(R.string.smscommunicator_loopisdisabled);
- }
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- receivedSms.processed = true;
- break;
- case "RESUME":
- LoopPlugin.getPlugin().suspendTo(0);
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_RESUME"));
- NSUpload.uploadOpenAPSOffline(0);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopresumed));
- break;
- case "SUSPEND":
- int duration = 0;
- if (splitted.length == 3)
- duration = SafeParse.stringToInt(splitted[2]);
- duration = Math.max(0, duration);
- duration = Math.min(180, duration);
- if (duration == 0) {
- receivedSms.processed = true;
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_wrongduration));
- return;
- } else {
- String passCode = generatePasscode();
- reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(duration) {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger * 60L * 1000);
- NSUpload.uploadOpenAPSOffline(anInteger * 60);
- MainApp.bus().post(new EventRefreshOverview("SMS_LOOP_SUSPENDED"));
- String reply = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " +
- MainApp.gs(result.success ? R.string.smscommunicator_tempbasalcanceled : R.string.smscommunicator_tempbasalcancelfailed);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
-
- }
- });
- }
- break;
- default:
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- break;
- }
- }
-
- private void processTREATMENTS(String[] splitted, Sms receivedSms) {
- if (splitted[1].toUpperCase().equals("REFRESH")) {
- TreatmentsPlugin.getPlugin().getService().resetTreatments();
- MainApp.bus().post(new EventNSClientRestart());
- sendSMS(new Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT"));
- receivedSms.processed = true;
- } else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- }
-
- private void processNSCLIENT(String[] splitted, Sms receivedSms) {
- if (splitted[1].toUpperCase().equals("RESTART")) {
- MainApp.bus().post(new EventNSClientRestart());
- sendSMS(new Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT"));
- receivedSms.processed = true;
- } else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- }
-
- @SuppressWarnings("unused")
- private void processPUMP(String[] splitted, Sms receivedSms) {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() {
- @Override
- public void run() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- if (result.success) {
- if (pump != null) {
- String reply = pump.shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- } else {
- String reply = MainApp.gs(R.string.readstatusfailed);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- receivedSms.processed = true;
- }
-
- private void processPROFILE(String[] splitted, Sms receivedSms) {
- // load profiles
- ProfileInterface anInterface = ConfigBuilderPlugin.getPlugin().getActiveProfileInterface();
- if (anInterface == null) {
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.notconfigured));
- receivedSms.processed = true;
- return;
- }
- ProfileStore store = anInterface.getProfile();
- if (store == null) {
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.notconfigured));
- receivedSms.processed = true;
- return;
- }
- final ArrayList list = store.getProfileList();
-
- if (splitted[1].toUpperCase().equals("STATUS")) {
- sendSMS(new Sms(receivedSms.phoneNumber, ProfileFunctions.getInstance().getProfileName()));
- } else if (splitted[1].toUpperCase().equals("LIST")) {
- if (list.isEmpty())
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.invalidprofile));
- else {
- String reply = "";
- for (int i = 0; i < list.size(); i++) {
- if (i > 0)
- reply += "\n";
- reply += (i + 1) + ". ";
- reply += list.get(i);
- }
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- } else {
-
- int pindex = SafeParse.stringToInt(splitted[1]);
- int percentage = 100;
- if (splitted.length > 2)
- percentage = SafeParse.stringToInt(splitted[2]);
-
- if (pindex > list.size())
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else if (percentage == 0)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else if (pindex == 0)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else {
- final Profile profile = store.getSpecificProfile((String) list.get(pindex - 1));
- if (profile == null)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile));
- else {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_profilereplywithcode), list.get(pindex - 1), percentage, passCode);
- receivedSms.processed = true;
- int finalPercentage = percentage;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction((String) list.get(pindex - 1), finalPercentage) {
- @Override
- public void run() {
- ProfileFunctions.doProfileSwitch(store, (String) list.get(pindex - 1), 0, finalPercentage, 0);
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.profileswitchcreated));
- }
- });
- }
- }
- }
- receivedSms.processed = true;
- }
-
- private void processBASAL(String[] splitted, Sms receivedSms) {
- if (splitted[1].toUpperCase().equals("CANCEL") || splitted[1].toUpperCase().equals("STOP")) {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction() {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcanceled);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- } else if (splitted[1].endsWith("%")) {
- int tempBasalPct = SafeParse.stringToInt(StringUtils.removeEnd(splitted[1], "%"));
- int duration = 30;
- if (splitted.length > 2)
- duration = SafeParse.stringToInt(splitted[2]);
- final Profile profile = ProfileFunctions.getInstance().getProfile();
-
- if (profile == null)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile));
- else if (tempBasalPct == 0 && !splitted[1].equals("0%"))
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else if (duration == 0)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else {
- tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(new Constraint<>(tempBasalPct), profile).value();
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(tempBasalPct, duration) {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalPercent(anInteger, secondInteger, true, profile, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply;
- if (result.isPercent)
- reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration);
- else
- reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- }
- } else {
- Double tempBasal = SafeParse.stringToDouble(splitted[1]);
- int duration = 30;
- if (splitted.length > 2)
- duration = SafeParse.stringToInt(splitted[2]);
- final Profile profile = ProfileFunctions.getInstance().getProfile();
- if (profile == null)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.noprofile));
- else if (tempBasal == 0 && !splitted[1].equals("0"))
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else if (duration == 0)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else {
- tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(new Constraint<>(tempBasal), profile).value();
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(tempBasal, duration) {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().tempBasalAbsolute(aDouble, secondInteger, true, profile, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply;
- if (result.isPercent)
- reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration);
- else
- reply = String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_tempbasalfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- }
- }
- }
-
- private void processEXTENDED(String[] splitted, Sms receivedSms) {
- if (splitted[1].toUpperCase().equals("CANCEL") || splitted[1].toUpperCase().equals("STOP")) {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction() {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelExtended(new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply = MainApp.gs(R.string.smscommunicator_extendedcanceled);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_extendedcancelfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- } else if (splitted.length != 3) {
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- } else {
- Double extended = SafeParse.stringToDouble(splitted[1]);
- int duration = SafeParse.stringToInt(splitted[2]);
- extended = MainApp.getConstraintChecker().applyExtendedBolusConstraints(new Constraint<>(extended)).value();
- if (extended == 0 || duration == 0)
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- else {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(extended, duration) {
- @Override
- public void run() {
- ConfigBuilderPlugin.getPlugin().getCommandQueue().extendedBolus(aDouble, secondInteger, new Callback() {
- @Override
- public void run() {
- if (result.success) {
- String reply = String.format(MainApp.gs(R.string.smscommunicator_extendedset), aDouble, duration);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_extendedfailed);
- reply += "\n" + ConfigBuilderPlugin.getPlugin().getActivePump().shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- }
- }
- }
-
-
- private void processBOLUS(String[] splitted, Sms receivedSms) {
- Double bolus = SafeParse.stringToDouble(splitted[1]);
- bolus = MainApp.getConstraintChecker().applyBolusConstraints(new Constraint<>(bolus)).value();
- if (bolus > 0d) {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(bolus) {
- @Override
- public void run() {
- DetailedBolusInfo detailedBolusInfo = new DetailedBolusInfo();
- detailedBolusInfo.insulin = aDouble;
- detailedBolusInfo.source = Source.USER;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().bolus(detailedBolusInfo, new Callback() {
- @Override
- public void run() {
- final boolean resultSuccess = result.success;
- final double resultBolusDelivered = result.bolusDelivered;
- ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("SMS", new Callback() {
- @Override
- public void run() {
- PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
- if (resultSuccess) {
- String reply = String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered);
- if (pump != null)
- reply += "\n" + pump.shortStatus(true);
- lastRemoteBolusTime = DateUtil.now();
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, reply));
- } else {
- String reply = MainApp.gs(R.string.smscommunicator_bolusfailed);
- if (pump != null)
- reply += "\n" + pump.shortStatus(true);
- sendSMS(new Sms(receivedSms.phoneNumber, reply));
- }
- }
- });
- }
- });
- }
- });
- } else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- }
-
- private void processCAL(String[] splitted, Sms receivedSms) {
- Double cal = SafeParse.stringToDouble(splitted[1]);
- if (cal > 0d) {
- String passCode = generatePasscode();
- String reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode);
- receivedSms.processed = true;
- messageToConfirm = new AuthRequest(this, receivedSms, reply, passCode, new SmsAction(cal) {
- @Override
- public void run() {
- boolean result = XdripCalibrations.sendIntent(aDouble);
- if (result)
- sendSMSToAllNumbers(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationsent));
- else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationfailed));
- }
- });
- } else
- sendSMS(new Sms(receivedSms.phoneNumber, R.string.wrongformat));
- }
-
- public boolean sendNotificationToAllNumbers(String text) {
- boolean result = true;
- for (int i = 0; i < allowedNumbers.size(); i++) {
- Sms sms = new Sms(allowedNumbers.get(i), text);
- result = result && sendSMS(sms);
- }
- return result;
- }
-
- private void sendSMSToAllNumbers(Sms sms) {
- for (String number : allowedNumbers) {
- sms.phoneNumber = number;
- sendSMS(sms);
- }
- }
-
- boolean sendSMS(Sms sms) {
- SmsManager smsManager = SmsManager.getDefault();
- sms.text = stripAccents(sms.text);
-
- try {
- if (L.isEnabled(L.SMS))
- log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text);
- if (sms.text.getBytes().length <= 140)
- smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null);
- else {
- ArrayList parts = smsManager.divideMessage(sms.text);
- smsManager.sendMultipartTextMessage(sms.phoneNumber, null, parts,
- null, null);
- }
-
- messages.add(sms);
- } catch (IllegalArgumentException e) {
- if (e.getMessage().equals("Invalid message body")) {
- Notification notification = new Notification(Notification.INVALID_MESSAGE_BODY, MainApp.gs(R.string.smscommunicator_messagebody), Notification.NORMAL);
- RxBus.INSTANCE.send(new EventNewNotification(notification));
- return false;
- } else {
- Notification notification = new Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL);
- RxBus.INSTANCE.send(new EventNewNotification(notification));
- return false;
- }
- } catch (java.lang.SecurityException e) {
- Notification notification = new Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL);
- RxBus.INSTANCE.send(new EventNewNotification(notification));
- return false;
- }
- MainApp.bus().post(new EventSmsCommunicatorUpdateGui());
- return true;
- }
-
- private String generatePasscode() {
- int startChar1 = 'A'; // on iphone 1st char is uppercase :)
- String passCode = Character.toString((char) (startChar1 + Math.random() * ('z' - 'a' + 1)));
- int startChar2 = Math.random() > 0.5 ? 'a' : 'A';
- passCode += Character.toString((char) (startChar2 + Math.random() * ('z' - 'a' + 1)));
- int startChar3 = Math.random() > 0.5 ? 'a' : 'A';
- passCode += Character.toString((char) (startChar3 + Math.random() * ('z' - 'a' + 1)));
- passCode = passCode.replace('l', 'k').replace('I', 'J');
- return passCode;
- }
-
- private static String stripAccents(String s) {
- s = Normalizer.normalize(s, Normalizer.Form.NFD);
- s = s.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
- return s;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt
new file mode 100644
index 0000000000..e40ed8b1df
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt
@@ -0,0 +1,922 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator
+
+import android.content.Intent
+import android.preference.EditTextPreference
+import android.preference.Preference
+import android.preference.Preference.OnPreferenceChangeListener
+import android.preference.PreferenceFragment
+import android.telephony.SmsManager
+import android.telephony.SmsMessage
+import android.text.TextUtils
+import com.andreabaccega.widget.ValidatingEditTextPreference
+import info.nightscout.androidaps.Constants
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.data.DetailedBolusInfo
+import info.nightscout.androidaps.data.Profile
+import info.nightscout.androidaps.db.DatabaseHelper
+import info.nightscout.androidaps.db.Source
+import info.nightscout.androidaps.db.TempTarget
+import info.nightscout.androidaps.events.EventPreferenceChange
+import info.nightscout.androidaps.events.EventRefreshOverview
+import info.nightscout.androidaps.interfaces.Constraint
+import info.nightscout.androidaps.interfaces.PluginBase
+import info.nightscout.androidaps.interfaces.PluginDescription
+import info.nightscout.androidaps.interfaces.PluginType
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
+import info.nightscout.androidaps.plugins.bus.RxBus.send
+import info.nightscout.androidaps.plugins.bus.RxBus.toObservable
+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.nsclient.events.EventNSClientRestart
+import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
+import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
+import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus
+import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
+import info.nightscout.androidaps.queue.Callback
+import info.nightscout.androidaps.utils.*
+import io.reactivex.disposables.CompositeDisposable
+import io.reactivex.schedulers.Schedulers
+import org.apache.commons.lang3.StringUtils
+import org.slf4j.LoggerFactory
+import java.text.Normalizer
+import java.util.*
+
+object SmsCommunicatorPlugin : PluginBase(PluginDescription()
+ .mainType(PluginType.GENERAL)
+ .fragmentClass(SmsCommunicatorFragment::class.java.name)
+ .pluginName(R.string.smscommunicator)
+ .shortName(R.string.smscommunicator_shortname)
+ .preferencesId(R.xml.pref_smscommunicator)
+ .description(R.string.description_sms_communicator)
+) {
+ private val log = LoggerFactory.getLogger(L.SMS)
+ private val disposable = CompositeDisposable()
+ var allowedNumbers: MutableList = ArrayList()
+ var messageToConfirm: AuthRequest? = null
+ var lastRemoteBolusTime: Long = 0
+ var messages = ArrayList()
+
+ val commands = mapOf(
+ "BG" to "BG",
+ "LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20",
+ "TREATMENTS" to "TREATMENTS REFRESH",
+ "NSCLIENT" to "NSCLIENT RESTART",
+ "PUMP" to "PUMP",
+ "BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n",
+ "BOLUS" to "BOLUS 1.2\nBOLUS 1.2 MEAL",
+ "EXTENDED" to "EXTENDED STOP/CANCEL\nEXTENDED 2 120",
+ "CAL" to "CAL 5.6",
+ "PROFILE" to "PROFILE STATUS/LIST\nPROFILE 1\nPROFILE 2 30",
+ "TARGET" to "TARGET MEAL/ACTIVITY/HYPO/STOP",
+ "SMS" to "SMS DISABLE/STOP",
+ "CARBS" to "CARBS 12\nCARBS 12 23:05\nCARBS 12 11:05PM",
+ "HELP" to "HELP\nHELP command"
+ )
+
+ init {
+ processSettings(null)
+ }
+
+ override fun onStart() {
+ super.onStart()
+ disposable.add(toObservable(EventPreferenceChange::class.java)
+ .observeOn(Schedulers.io())
+ .subscribe({ event: EventPreferenceChange? -> processSettings(event) }) { throwable: Throwable? -> FabricPrivacy.logException(throwable) }
+ )
+ }
+
+ override fun onStop() {
+ disposable.clear()
+ super.onStop()
+ }
+
+ override fun preprocessPreferences(preferenceFragment: PreferenceFragment) {
+ super.preprocessPreferences(preferenceFragment)
+ val distance = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_remotebolusmindistance)) as ValidatingEditTextPreference?
+ ?: return
+ val allowedNumbers = preferenceFragment.findPreference(MainApp.gs(R.string.key_smscommunicator_allowednumbers)) as EditTextPreference?
+ ?: return
+ if (!areMoreNumbers(allowedNumbers.text)) {
+ distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance)
+ + ".\n"
+ + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
+ distance.isEnabled = false
+ } else {
+ distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance)
+ distance.isEnabled = true
+ }
+ allowedNumbers.onPreferenceChangeListener = OnPreferenceChangeListener { _: Preference?, newValue: Any ->
+ if (!areMoreNumbers(newValue as String)) {
+ distance.text = (Constants.remoteBolusMinDistance / (60 * 1000L)).toString()
+ distance.title = (MainApp.gs(R.string.smscommunicator_remotebolusmindistance)
+ + ".\n"
+ + MainApp.gs(R.string.smscommunicator_remotebolusmindistance_caveat))
+ distance.isEnabled = false
+ } else {
+ distance.title = MainApp.gs(R.string.smscommunicator_remotebolusmindistance)
+ distance.isEnabled = true
+ }
+ true
+ }
+ }
+
+ override fun updatePreferenceSummary(pref: Preference) {
+ super.updatePreferenceSummary(pref)
+ if (pref is EditTextPreference) {
+ val editTextPref = pref
+ if (pref.getKey().contains("smscommunicator_allowednumbers") && (editTextPref.text == null || TextUtils.isEmpty(editTextPref.text.trim { it <= ' ' }))) {
+ pref.setSummary(MainApp.gs(R.string.smscommunicator_allowednumbers_summary))
+ }
+ }
+ }
+
+ private fun processSettings(ev: EventPreferenceChange?) {
+ if (ev == null || ev.isChanged(R.string.key_smscommunicator_allowednumbers)) {
+ val settings = SP.getString(R.string.key_smscommunicator_allowednumbers, "")
+ allowedNumbers.clear()
+ val substrings = settings.split(";").toTypedArray()
+ for (number in substrings) {
+ val cleaned = number.replace("\\s+".toRegex(), "")
+ allowedNumbers.add(cleaned)
+ log.debug("Found allowed number: $cleaned")
+ }
+ }
+ }
+
+ fun isCommand(command: String, number: String): Boolean {
+ var found = false
+ commands.forEach { (k, _) ->
+ if (k == command) found = true
+ }
+ return found || messageToConfirm?.requester?.phoneNumber == number
+ }
+
+ fun isAllowedNumber(number: String): Boolean {
+ for (num in allowedNumbers) {
+ if (num == number) return true
+ }
+ return false
+ }
+
+ fun handleNewData(intent: Intent) {
+ val bundle = intent.extras ?: return
+ val format = bundle.getString("format") ?: return
+ val pdus = bundle["pdus"] as Array<*>
+ for (pdu in pdus) {
+ val message = SmsMessage.createFromPdu(pdu as ByteArray, format)
+ processSms(Sms(message))
+ }
+ }
+
+ fun processSms(receivedSms: Sms) {
+ if (!isEnabled(PluginType.GENERAL)) {
+ log.debug("Ignoring SMS. Plugin disabled.")
+ return
+ }
+ if (!isAllowedNumber(receivedSms.phoneNumber)) {
+ log.debug("Ignoring SMS from: " + receivedSms.phoneNumber + ". Sender not allowed")
+ receivedSms.ignored = true
+ messages.add(receivedSms)
+ send(EventSmsCommunicatorUpdateGui())
+ return
+ }
+ val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return
+ messages.add(receivedSms)
+ log.debug(receivedSms.toString())
+ val splitted = receivedSms.text.split(Regex("\\s+")).toTypedArray()
+ val remoteCommandsAllowed = SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
+ if (splitted.isNotEmpty() && isCommand(splitted[0].toUpperCase(Locale.getDefault()), receivedSms.phoneNumber)) {
+ when (splitted[0].toUpperCase(Locale.getDefault())) {
+ "BG" ->
+ if (splitted.size == 1) processBG(receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "LOOP" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 || splitted.size == 3) processLOOP(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "TREATMENTS" ->
+ if (splitted.size == 2) processTREATMENTS(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "NSCLIENT" ->
+ if (splitted.size == 2) processNSCLIENT(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "PUMP" ->
+ if (splitted.size == 1) processPUMP(receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "PROFILE" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 || splitted.size == 3) processPROFILE(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "BASAL" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 || splitted.size == 3) processBASAL(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "EXTENDED" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 || splitted.size == 3) processEXTENDED(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "BOLUS" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 && DateUtil.now() - lastRemoteBolusTime < Constants.remoteBolusMinDistance) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotebolusnotallowed))
+ else if (splitted.size == 2 && pump.isSuspended) sendSMS(Sms(receivedSms.phoneNumber, R.string.pumpsuspended))
+ else if (splitted.size == 2 || splitted.size == 3) processBOLUS(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "CARBS" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2 || splitted.size == 3) processCARBS(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "CAL" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2) processCAL(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "TARGET" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2) processTARGET(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "SMS" ->
+ if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_remotecommandnotallowed))
+ else if (splitted.size == 2) processSMS(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ "HELP" ->
+ if (splitted.size == 1 || splitted.size == 2) processHELP(splitted, receivedSms)
+ else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else ->
+ if (messageToConfirm?.requester?.phoneNumber == receivedSms.phoneNumber) {
+ messageToConfirm?.action(splitted[0])
+ messageToConfirm = null
+ } else sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_unknowncommand))
+ }
+ }
+ send(EventSmsCommunicatorUpdateGui())
+ }
+
+ private fun processBG(receivedSms: Sms) {
+ val actualBG = DatabaseHelper.actualBg()
+ val lastBG = DatabaseHelper.lastBg()
+ var reply = ""
+ val units = ProfileFunctions.getInstance().profileUnits
+ if (actualBG != null) {
+ reply = MainApp.gs(R.string.sms_actualbg) + " " + actualBG.valueToUnitsToString(units) + ", "
+ } else if (lastBG != null) {
+ val agoMsec = System.currentTimeMillis() - lastBG.date
+ val agoMin = (agoMsec / 60.0 / 1000.0).toInt()
+ reply = MainApp.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(MainApp.gs(R.string.sms_minago), agoMin) + ", "
+ }
+ val glucoseStatus = GlucoseStatus.getGlucoseStatusData()
+ if (glucoseStatus != null) reply += MainApp.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "
+ TreatmentsPlugin.getPlugin().updateTotalIOBTreatments()
+ val bolusIob = TreatmentsPlugin.getPlugin().lastCalculationTreatments.round()
+ TreatmentsPlugin.getPlugin().updateTotalIOBTempBasals()
+ val basalIob = TreatmentsPlugin.getPlugin().lastCalculationTempBasals.round()
+ val cobInfo = IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB")
+ reply += (MainApp.gs(R.string.sms_iob) + " " + DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + "U ("
+ + MainApp.gs(R.string.sms_bolus) + " " + DecimalFormatter.to2Decimal(bolusIob.iob) + "U "
+ + MainApp.gs(R.string.sms_basal) + " " + DecimalFormatter.to2Decimal(basalIob.basaliob) + "U), "
+ + MainApp.gs(R.string.cob) + ": " + cobInfo.generateCOBString())
+ sendSMS(Sms(receivedSms.phoneNumber, reply))
+ receivedSms.processed = true
+ }
+
+ private fun processLOOP(splitted: Array, receivedSms: Sms) {
+ when (splitted[1].toUpperCase(Locale.getDefault())) {
+ "DISABLE", "STOP" -> {
+ val loopPlugin = LoopPlugin.getPlugin()
+ if (loopPlugin.isEnabled(PluginType.LOOP)) {
+ loopPlugin.setPluginEnabled(PluginType.LOOP, false)
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() {
+ override fun run() {
+ send(EventRefreshOverview("SMS_LOOP_STOP"))
+ val replyText = MainApp.gs(R.string.smscommunicator_loophasbeendisabled) + " " +
+ MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ })
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisdisabled))
+ receivedSms.processed = true
+ }
+ "ENABLE", "START" -> {
+ val loopPlugin = LoopPlugin.getPlugin()
+ if (!loopPlugin.isEnabled(PluginType.LOOP)) {
+ loopPlugin.setPluginEnabled(PluginType.LOOP, true)
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loophasbeenenabled))
+ send(EventRefreshOverview("SMS_LOOP_START"))
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopisenabled))
+ receivedSms.processed = true
+ }
+ "STATUS" -> {
+ val loopPlugin = LoopPlugin.getPlugin()
+ val reply = if (loopPlugin.isEnabled(PluginType.LOOP)) {
+ if (loopPlugin.isSuspended()) String.format(MainApp.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend())
+ else MainApp.gs(R.string.smscommunicator_loopisenabled)
+ } else
+ MainApp.gs(R.string.smscommunicator_loopisdisabled)
+ sendSMS(Sms(receivedSms.phoneNumber, reply))
+ receivedSms.processed = true
+ }
+ "RESUME" -> {
+ LoopPlugin.getPlugin().suspendTo(0)
+ send(EventRefreshOverview("SMS_LOOP_RESUME"))
+ NSUpload.uploadOpenAPSOffline(0.0)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, R.string.smscommunicator_loopresumed))
+ }
+ "SUSPEND" -> {
+ var duration = 0
+ if (splitted.size == 3) duration = SafeParse.stringToInt(splitted[2])
+ duration = Math.max(0, duration)
+ duration = Math.min(180, duration)
+ if (duration == 0) {
+ receivedSms.processed = true
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_wrongduration))
+ return
+ } else {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_suspendreplywithcode), duration, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(duration) {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() {
+ override fun run() {
+ if (result.success) {
+ LoopPlugin.getPlugin().suspendTo(System.currentTimeMillis() + anInteger() * 60L * 1000)
+ NSUpload.uploadOpenAPSOffline(anInteger() * 60.toDouble())
+ send(EventRefreshOverview("SMS_LOOP_SUSPENDED"))
+ val replyText = MainApp.gs(R.string.smscommunicator_loopsuspended) + " " +
+ MainApp.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ }
+ else -> sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+ }
+
+ private fun processTREATMENTS(splitted: Array, receivedSms: Sms) {
+ if (splitted[1].toUpperCase(Locale.getDefault()) == "REFRESH") {
+ TreatmentsPlugin.getPlugin().service.resetTreatments()
+ send(EventNSClientRestart())
+ sendSMS(Sms(receivedSms.phoneNumber, "TREATMENTS REFRESH SENT"))
+ receivedSms.processed = true
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processNSCLIENT(splitted: Array, receivedSms: Sms) {
+ if (splitted[1].toUpperCase(Locale.getDefault()) == "RESTART") {
+ send(EventNSClientRestart())
+ sendSMS(Sms(receivedSms.phoneNumber, "NSCLIENT RESTART SENT"))
+ receivedSms.processed = true
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processHELP(splitted: Array, receivedSms: Sms) {
+ if (splitted.size == 1) {
+ sendSMS(Sms(receivedSms.phoneNumber, commands.keys.toString().replace("[", "").replace("]", "")))
+ receivedSms.processed = true
+ } else if (isCommand(splitted[1].toUpperCase(Locale.getDefault()), receivedSms.phoneNumber)) {
+ commands[splitted[1].toUpperCase(Locale.getDefault())]?.let {
+ sendSMS(Sms(receivedSms.phoneNumber, it))
+ receivedSms.processed = true
+ }
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processPUMP(receivedSms: Sms) {
+ ConfigBuilderPlugin.getPlugin().commandQueue.readStatus("SMS", object : Callback() {
+ override fun run() {
+ val pump = ConfigBuilderPlugin.getPlugin().activePump
+ if (result.success) {
+ if (pump != null) {
+ val reply = pump.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, reply))
+ }
+ } else {
+ val reply = MainApp.gs(R.string.readstatusfailed)
+ sendSMS(Sms(receivedSms.phoneNumber, reply))
+ }
+ }
+ })
+ receivedSms.processed = true
+ }
+
+ private fun processPROFILE(splitted: Array, receivedSms: Sms) { // load profiles
+ val anInterface = ConfigBuilderPlugin.getPlugin().activeProfileInterface
+ if (anInterface == null) {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured))
+ receivedSms.processed = true
+ return
+ }
+ val store = anInterface.profile
+ if (store == null) {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.notconfigured))
+ receivedSms.processed = true
+ return
+ }
+ val list = store.profileList
+ if (splitted[1].toUpperCase(Locale.getDefault()) == "STATUS") {
+ sendSMS(Sms(receivedSms.phoneNumber, ProfileFunctions.getInstance().profileName))
+ } else if (splitted[1].toUpperCase(Locale.getDefault()) == "LIST") {
+ if (list.isEmpty()) sendSMS(Sms(receivedSms.phoneNumber, R.string.invalidprofile))
+ else {
+ var reply = ""
+ for (i in list.indices) {
+ if (i > 0) reply += "\n"
+ reply += (i + 1).toString() + ". "
+ reply += list[i]
+ }
+ sendSMS(Sms(receivedSms.phoneNumber, reply))
+ }
+ } else {
+ val pindex = SafeParse.stringToInt(splitted[1])
+ var percentage = 100
+ if (splitted.size > 2) percentage = SafeParse.stringToInt(splitted[2])
+ if (pindex > list.size) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else if (percentage == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else if (pindex == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else {
+ val profile = store.getSpecificProfile(list[pindex - 1] as String)
+ if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile))
+ else {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_profilereplywithcode), list[pindex - 1], percentage, passCode)
+ receivedSms.processed = true
+ val finalPercentage = percentage
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(list[pindex - 1] as String, finalPercentage) {
+ override fun run() {
+ ProfileFunctions.doProfileSwitch(store, list[pindex - 1] as String, 0, finalPercentage, 0)
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.profileswitchcreated))
+ }
+ })
+ }
+ }
+ }
+ receivedSms.processed = true
+ }
+
+ private fun processBASAL(splitted: Array, receivedSms: Sms) {
+ if (splitted[1].toUpperCase(Locale.getDefault()) == "CANCEL" || splitted[1].toUpperCase(Locale.getDefault()) == "STOP") {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_basalstopreplywithcode), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelTempBasal(true, object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcanceled)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_tempbasalcancelfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ } else if (splitted[1].endsWith("%")) {
+ var tempBasalPct = SafeParse.stringToInt(StringUtils.removeEnd(splitted[1], "%"))
+ var duration = 30
+ if (splitted.size > 2) duration = SafeParse.stringToInt(splitted[2])
+ val profile = ProfileFunctions.getInstance().profile
+ if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile))
+ else if (tempBasalPct == 0 && splitted[1] != "0%") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else {
+ tempBasalPct = MainApp.getConstraintChecker().applyBasalPercentConstraints(Constraint(tempBasalPct), profile).value()
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_basalpctreplywithcode), tempBasalPct, duration, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasalPct, duration) {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalPercent(anInteger(), secondInteger(), true, profile, object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText: String
+ replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration) else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ } else {
+ var tempBasal = SafeParse.stringToDouble(splitted[1])
+ var duration = 30
+ if (splitted.size > 2) duration = SafeParse.stringToInt(splitted[2])
+ val profile = ProfileFunctions.getInstance().profile
+ if (profile == null) sendSMS(Sms(receivedSms.phoneNumber, R.string.noprofile))
+ else if (tempBasal == 0.0 && splitted[1] != "0") sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else if (duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else {
+ tempBasal = MainApp.getConstraintChecker().applyBasalConstraints(Constraint(tempBasal), profile).value()
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_basalreplywithcode), tempBasal, duration, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(tempBasal, duration) {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.tempBasalAbsolute(aDouble(), secondInteger(), true, profile, object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText = if (result.isPercent) String.format(MainApp.gs(R.string.smscommunicator_tempbasalset_percent), result.percent, result.duration)
+ else String.format(MainApp.gs(R.string.smscommunicator_tempbasalset), result.absolute, result.duration)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_tempbasalfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ }
+ }
+
+ private fun processEXTENDED(splitted: Array, receivedSms: Sms) {
+ if (splitted[1].toUpperCase(Locale.getDefault()) == "CANCEL" || splitted[1].toUpperCase(Locale.getDefault()) == "STOP") {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_extendedstopreplywithcode), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.cancelExtended(object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText = MainApp.gs(R.string.smscommunicator_extendedcanceled)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_extendedcancelfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ } else if (splitted.size != 3) {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ } else {
+ var extended = SafeParse.stringToDouble(splitted[1])
+ val duration = SafeParse.stringToInt(splitted[2])
+ extended = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(extended)).value()
+ if (extended == 0.0 || duration == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_extendedreplywithcode), extended, duration, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(extended, duration) {
+ override fun run() {
+ ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(aDouble(), secondInteger(), object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText = String.format(MainApp.gs(R.string.smscommunicator_extendedset), aDouble, duration)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_extendedfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ }
+ }
+
+ private fun processBOLUS(splitted: Array, receivedSms: Sms) {
+ var bolus = SafeParse.stringToDouble(splitted[1])
+ val isMeal = splitted.size > 2 && splitted[2].equals("MEAL", ignoreCase = true)
+ bolus = MainApp.getConstraintChecker().applyBolusConstraints(Constraint(bolus)).value()
+ if (splitted.size == 3 && !isMeal) {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ } else if (bolus > 0.0) {
+ val passCode = generatePasscode()
+ val reply = if (isMeal)
+ String.format(MainApp.gs(R.string.smscommunicator_mealbolusreplywithcode), bolus, passCode)
+ else
+ String.format(MainApp.gs(R.string.smscommunicator_bolusreplywithcode), bolus, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(bolus) {
+ override fun run() {
+ val detailedBolusInfo = DetailedBolusInfo()
+ detailedBolusInfo.insulin = aDouble()
+ detailedBolusInfo.source = Source.USER
+ ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() {
+ override fun run() {
+ val resultSuccess = result.success
+ val resultBolusDelivered = result.bolusDelivered
+ ConfigBuilderPlugin.getPlugin().commandQueue.readStatus("SMS", object : Callback() {
+ override fun run() {
+ if (resultSuccess) {
+ var replyText = if (isMeal)
+ String.format(MainApp.gs(R.string.smscommunicator_mealbolusdelivered), resultBolusDelivered)
+ else
+ String.format(MainApp.gs(R.string.smscommunicator_bolusdelivered), resultBolusDelivered)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ lastRemoteBolusTime = DateUtil.now()
+ if (isMeal) {
+ ProfileFunctions.getInstance().profile?.let { currentProfile ->
+ var eatingSoonTTDuration = SP.getInt(R.string.key_eatingsoon_duration, Constants.defaultEatingSoonTTDuration)
+ eatingSoonTTDuration =
+ if (eatingSoonTTDuration > 0) eatingSoonTTDuration
+ else Constants.defaultEatingSoonTTDuration
+ var eatingSoonTT = SP.getDouble(R.string.key_eatingsoon_target, if (currentProfile.units == Constants.MMOL) Constants.defaultEatingSoonTTmmol else Constants.defaultEatingSoonTTmgdl)
+ eatingSoonTT =
+ if (eatingSoonTT > 0) eatingSoonTT
+ else if (currentProfile.units == Constants.MMOL) Constants.defaultEatingSoonTTmmol
+ else Constants.defaultEatingSoonTTmgdl
+ val tempTarget = TempTarget()
+ .date(System.currentTimeMillis())
+ .duration(eatingSoonTTDuration)
+ .reason(MainApp.gs(R.string.eatingsoon))
+ .source(Source.USER)
+ .low(Profile.toMgdl(eatingSoonTT, currentProfile.units))
+ .high(Profile.toMgdl(eatingSoonTT, currentProfile.units))
+ TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
+ val tt = if (currentProfile.units == Constants.MMOL) {
+ DecimalFormatter.to1Decimal(eatingSoonTT)
+ } else DecimalFormatter.to0Decimal(eatingSoonTT)
+ replyText += "\n" + String.format(MainApp.gs(R.string.smscommunicator_mealbolusdelivered_tt), tt, eatingSoonTTDuration)
+ }
+ }
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_bolusfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ })
+ } else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processCARBS(splitted: Array, receivedSms: Sms) {
+ var grams = SafeParse.stringToInt(splitted[1])
+ var time = DateUtil.now()
+ if (splitted.size > 2) {
+ val seconds = DateUtil.toSeconds(splitted[2].toUpperCase(Locale.getDefault()))
+ val midnight = MidnightTime.calc()
+ if (seconds == 0 && (!splitted[2].startsWith("00:00") || !splitted[2].startsWith("12:00"))) {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ return
+ }
+ time = midnight + T.secs(seconds.toLong()).msecs()
+ }
+ grams = MainApp.getConstraintChecker().applyCarbsConstraints(Constraint(grams)).value()
+ if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ else {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_carbsreplywithcode), grams, DateUtil.timeString(time), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(grams, time) {
+ override fun run() {
+ val detailedBolusInfo = DetailedBolusInfo()
+ detailedBolusInfo.carbs = anInteger().toDouble()
+ detailedBolusInfo.date = secondLong()
+ ConfigBuilderPlugin.getPlugin().commandQueue.bolus(detailedBolusInfo, object : Callback() {
+ override fun run() {
+ if (result.success) {
+ var replyText = String.format(MainApp.gs(R.string.smscommunicator_carbsset), anInteger)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ var replyText = MainApp.gs(R.string.smscommunicator_carbsfailed)
+ replyText += "\n" + ConfigBuilderPlugin.getPlugin().activePump?.shortStatus(true)
+ sendSMS(Sms(receivedSms.phoneNumber, replyText))
+ }
+ }
+ })
+ }
+ })
+ }
+ }
+
+ private fun processTARGET(splitted: Array, receivedSms: Sms) {
+ val isMeal = splitted[1].equals("MEAL", ignoreCase = true)
+ val isActivity = splitted[1].equals("ACTIVITY", ignoreCase = true)
+ val isHypo = splitted[1].equals("HYPO", ignoreCase = true)
+ val isStop = splitted[1].equals("STOP", ignoreCase = true) || splitted[1].equals("CANCEL", ignoreCase = true)
+ if (isMeal || isActivity || isHypo) {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_temptargetwithcode), splitted[1].toUpperCase(Locale.getDefault()), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() {
+ override fun run() {
+ val currentProfile = ProfileFunctions.getInstance().profile
+ if (currentProfile != null) {
+ var keyDuration = 0
+ var defaultTargetDuration = 0
+ var keyTarget = 0
+ var defaultTargetMMOL = 0.0
+ var defaultTargetMGDL = 0.0
+ if (isMeal) {
+ keyDuration = R.string.key_eatingsoon_duration
+ defaultTargetDuration = Constants.defaultEatingSoonTTDuration
+ keyTarget = R.string.key_eatingsoon_target
+ defaultTargetMMOL = Constants.defaultEatingSoonTTmmol
+ defaultTargetMGDL = Constants.defaultEatingSoonTTmgdl
+ } else if (isActivity) {
+ keyDuration = R.string.key_activity_duration
+ defaultTargetDuration = Constants.defaultActivityTTDuration
+ keyTarget = R.string.key_activity_target
+ defaultTargetMMOL = Constants.defaultActivityTTmmol
+ defaultTargetMGDL = Constants.defaultActivityTTmgdl
+ } else if (isHypo) {
+ keyDuration = R.string.key_hypo_duration
+ defaultTargetDuration = Constants.defaultHypoTTDuration
+ keyTarget = R.string.key_hypo_target
+ defaultTargetMMOL = Constants.defaultHypoTTmmol
+ defaultTargetMGDL = Constants.defaultHypoTTmgdl
+ }
+ var ttDuration = SP.getInt(keyDuration, defaultTargetDuration)
+ ttDuration = if (ttDuration > 0) ttDuration else defaultTargetDuration
+ var tt = SP.getDouble(keyTarget, if (currentProfile.units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL)
+ tt = if (tt > 0) tt else if (currentProfile.units == Constants.MMOL) defaultTargetMMOL else defaultTargetMGDL
+ val tempTarget = TempTarget()
+ .date(System.currentTimeMillis())
+ .duration(ttDuration)
+ .reason(MainApp.gs(R.string.eatingsoon))
+ .source(Source.USER)
+ .low(Profile.toMgdl(tt, currentProfile.units))
+ .high(Profile.toMgdl(tt, currentProfile.units))
+ TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
+ val ttString = if (currentProfile.units == Constants.MMOL) DecimalFormatter.to1Decimal(tt) else DecimalFormatter.to0Decimal(tt)
+ val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_set), ttString, ttDuration)
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_unknowncommand))
+ }
+ }
+ })
+ } else if (isStop) {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_temptargetcancel), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() {
+ override fun run() {
+ val currentProfile = ProfileFunctions.getInstance().profile
+ if (currentProfile != null) {
+ val tempTarget = TempTarget()
+ .source(Source.USER)
+ .date(DateUtil.now())
+ .duration(0)
+ .low(0.0)
+ .high(0.0)
+ TreatmentsPlugin.getPlugin().addToHistoryTempTarget(tempTarget)
+ val replyText = String.format(MainApp.gs(R.string.smscommunicator_tt_canceled))
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ } else {
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_unknowncommand))
+ }
+ }
+ })
+ } else
+ sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processSMS(splitted: Array, receivedSms: Sms) {
+ val isStop = (splitted[1].equals("STOP", ignoreCase = true)
+ || splitted[1].equals("DISABLE", ignoreCase = true))
+ if (isStop) {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_stopsmswithcode), passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction() {
+ override fun run() {
+ SP.putBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)
+ val replyText = String.format(MainApp.gs(R.string.smscommunicator_stoppedsms))
+ sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText))
+ }
+ })
+ } else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ private fun processCAL(splitted: Array, receivedSms: Sms) {
+ val cal = SafeParse.stringToDouble(splitted[1])
+ if (cal > 0.0) {
+ val passCode = generatePasscode()
+ val reply = String.format(MainApp.gs(R.string.smscommunicator_calibrationreplywithcode), cal, passCode)
+ receivedSms.processed = true
+ messageToConfirm = AuthRequest(this, receivedSms, reply, passCode, object : SmsAction(cal) {
+ override fun run() {
+ val result = XdripCalibrations.sendIntent(aDouble)
+ if (result) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationsent)) else sendSMS(Sms(receivedSms.phoneNumber, R.string.smscommunicator_calibrationfailed))
+ }
+ })
+ } else sendSMS(Sms(receivedSms.phoneNumber, R.string.wrongformat))
+ }
+
+ fun sendNotificationToAllNumbers(text: String): Boolean {
+ var result = true
+ for (i in allowedNumbers.indices) {
+ val sms = Sms(allowedNumbers[i], text)
+ result = result && sendSMS(sms)
+ }
+ return result
+ }
+
+ private fun sendSMSToAllNumbers(sms: Sms) {
+ for (number in allowedNumbers) {
+ sms.phoneNumber = number
+ sendSMS(sms)
+ }
+ }
+
+ fun sendSMS(sms: Sms): Boolean {
+ val smsManager = SmsManager.getDefault()
+ sms.text = stripAccents(sms.text)
+ try {
+ if (L.isEnabled(L.SMS)) log.debug("Sending SMS to " + sms.phoneNumber + ": " + sms.text)
+ if (sms.text.toByteArray().size <= 140) smsManager.sendTextMessage(sms.phoneNumber, null, sms.text, null, null)
+ else {
+ val parts = smsManager.divideMessage(sms.text)
+ smsManager.sendMultipartTextMessage(sms.phoneNumber, null, parts,
+ null, null)
+ }
+ messages.add(sms)
+ } catch (e: IllegalArgumentException) {
+ return if (e.message == "Invalid message body") {
+ val notification = Notification(Notification.INVALID_MESSAGE_BODY, MainApp.gs(R.string.smscommunicator_messagebody), Notification.NORMAL)
+ send(EventNewNotification(notification))
+ false
+ } else {
+ val notification = Notification(Notification.INVALID_PHONE_NUMBER, MainApp.gs(R.string.smscommunicator_invalidphonennumber), Notification.NORMAL)
+ send(EventNewNotification(notification))
+ false
+ }
+ } catch (e: SecurityException) {
+ val notification = Notification(Notification.MISSING_SMS_PERMISSION, MainApp.gs(R.string.smscommunicator_missingsmspermission), Notification.NORMAL)
+ send(EventNewNotification(notification))
+ return false
+ }
+ send(EventSmsCommunicatorUpdateGui())
+ return true
+ }
+
+ private fun generatePasscode(): String {
+ val startChar1 = 'A'.toInt() // on iphone 1st char is uppercase :)
+ var passCode = Character.toString((startChar1 + Math.random() * ('z' - 'a' + 1)).toChar())
+ val startChar2: Int = if (Math.random() > 0.5) 'a'.toInt() else 'A'.toInt()
+ passCode += Character.toString((startChar2 + Math.random() * ('z' - 'a' + 1)).toChar())
+ val startChar3: Int = if (Math.random() > 0.5) 'a'.toInt() else 'A'.toInt()
+ passCode += Character.toString((startChar3 + Math.random() * ('z' - 'a' + 1)).toChar())
+ passCode = passCode.replace('l', 'k').replace('I', 'J')
+ return passCode
+ }
+
+ private fun stripAccents(str: String): String {
+ var s = str
+ s = Normalizer.normalize(s, Normalizer.Form.NFD)
+ s = s.replace("[\\p{InCombiningDiacriticalMarks}]".toRegex(), "")
+ return s
+ }
+
+ fun areMoreNumbers(allowednumbers: String?): Boolean {
+ return allowednumbers?.let {
+ var countNumbers = 0
+ val substrings = it.split(";").toTypedArray()
+ for (number in substrings) {
+ var cleaned = number.replace(Regex("\\s+"), "")
+ if (cleaned.length < 4) continue
+ cleaned = cleaned.replace("+", "")
+ cleaned = cleaned.replace("-", "")
+ if (!cleaned.matches(Regex("[0-9]+"))) continue
+ countNumbers++
+ }
+ countNumbers > 1
+ } ?: false
+ }
+}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java
deleted file mode 100644
index 7e50671c45..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.general.smsCommunicator.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventSmsCommunicatorUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt
new file mode 100644
index 0000000000..4a0f95b244
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/events/EventSmsCommunicatorUpdateGui.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.general.smsCommunicator.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventSmsCommunicatorUpdateGui : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt
index 78ad0ab37d..e8971ab9d5 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.general.tidepool
+import android.preference.PreferenceFragment
import android.text.Spanned
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
@@ -34,7 +35,6 @@ object TidepoolPlugin : PluginBase(PluginDescription()
.preferencesId(R.xml.pref_tidepool)
.description(R.string.description_tidepool)
) {
-
private val log = LoggerFactory.getLogger(L.TIDEPOOL)
private var disposable: CompositeDisposable = CompositeDisposable()
@@ -111,6 +111,16 @@ object TidepoolPlugin : PluginBase(PluginDescription()
super.onStop()
}
+ override fun preprocessPreferences(preferenceFragment: PreferenceFragment) {
+ super.preprocessPreferences(preferenceFragment)
+
+ val tidepoolTestLogin = preferenceFragment.findPreference(MainApp.gs(R.string.key_tidepool_test_login))
+ tidepoolTestLogin?.setOnPreferenceClickListener {
+ TidepoolUploader.testLogin(preferenceFragment.getActivity())
+ false
+ }
+ }
+
private fun doUpload() =
when (TidepoolUploader.connectionStatus) {
TidepoolUploader.ConnectionStatus.FAILED -> {}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt
index aa69c11e95..e7854f8ff2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolStatus.kt
@@ -17,7 +17,7 @@ class EventTidepoolStatus(val status: String) : Event() {
log.debug("New status: $status")
}
- private var timeFormat = SimpleDateFormat("HH:mm:ss", LocaleHelper.getLocale())
+ private var timeFormat = SimpleDateFormat("HH:mm:ss", LocaleHelper.currentLocale())
fun toPreparedHtml(): StringBuilder {
val stringBuilder = StringBuilder()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java
index 25a6540dbd..1cf4dd7539 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.java
@@ -437,11 +437,11 @@ public class ActionStringHandler {
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;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java
index 53b421ace3..ec01bff68b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.java
@@ -2,9 +2,6 @@ package info.nightscout.androidaps.plugins.general.wear;
import android.content.Context;
import android.content.Intent;
-import android.util.Log;
-
-import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -21,14 +18,13 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui;
import info.nightscout.androidaps.plugins.bus.RxBus;
-import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
+import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import io.reactivex.disposables.CompositeDisposable;
-import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
/**
@@ -72,7 +68,6 @@ public class WearPlugin extends PluginBase {
@Override
protected void onStart() {
- MainApp.bus().register(this);
if (watchUS != null) {
watchUS.setSettings();
}
@@ -81,15 +76,102 @@ public class WearPlugin extends PluginBase {
disposable.add(RxBus.INSTANCE
.toObservable(EventOpenAPSUpdateGui.class)
.observeOn(Schedulers.io())
- .subscribe(eventOpenAPSUpdateGui -> sendDataToWatch(true, true, false),
- error -> FabricPrivacy.logException(error)
+ .subscribe(event -> sendDataToWatch(true, true, false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendDataToWatch(true, true, false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempBasalChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendDataToWatch(true, true, false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTreatmentChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendDataToWatch(true, true, false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewBasalProfile.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendDataToWatch(false, true, false),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendDataToWatch(true, true, true),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ // possibly new high or low mark
+ resendDataToWatch();
+ // status may be formated differently
+ sendDataToWatch(true, false, false);
+ }, FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventRefreshOverview.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)))
+ sendDataToWatch(true, false, false);
+ }, FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventBolusRequested.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ String status = String.format(MainApp.gs(R.string.bolusrequested), event.getAmount());
+ Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
+ intent.putExtra("progresspercent", 0);
+ intent.putExtra("progressstatus", status);
+ ctx.startService(intent);
+ }, FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventDismissBolusProgressIfRunning.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (event.getResult() == null) return;
+ String status;
+ if (event.getResult().success) {
+ status = MainApp.gs(R.string.success);
+ } else {
+ status = MainApp.gs(R.string.nosuccess);
+ }
+ Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
+ intent.putExtra("progresspercent", 100);
+ intent.putExtra("progressstatus", status);
+ ctx.startService(intent);
+ }, FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventOverviewBolusProgress.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (!event.isSMB() || SP.getBoolean("wear_notifySMB", true)) {
+ Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
+ intent.putExtra("progresspercent", event.getPercent());
+ intent.putExtra("progressstatus", event.getStatus());
+ ctx.startService(intent);
+ }
+ }, FabricPrivacy::logException
));
}
@Override
protected void onStop() {
- MainApp.bus().unregister(this);
disposable.clear();
super.onStop();
}
@@ -133,84 +215,6 @@ public class WearPlugin extends PluginBase {
ctx.startService(intent);
}
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- // possibly new high or low mark
- resendDataToWatch();
- // status may be formated differently
- sendDataToWatch(true, false, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- sendDataToWatch(true, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- sendDataToWatch(true, true, true);
- }
-
- @Subscribe
- public void onStatusEvent(final EventNewBasalProfile ev) {
- sendDataToWatch(false, true, false);
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- if (WatchUpdaterService.shouldReportLoopStatus(LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) {
- sendDataToWatch(true, false, false);
- }
- }
-
-
- @Subscribe
- public void onStatusEvent(final EventOverviewBolusProgress ev) {
- if (!ev.isSMB() || SP.getBoolean("wear_notifySMB", true)) {
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", ev.percent);
- intent.putExtra("progressstatus", ev.status);
- ctx.startService(intent);
- }
- }
-
- @Subscribe
- public void onStatusEvent(final EventBolusRequested ev) {
- String status = String.format(MainApp.gs(R.string.bolusrequested), ev.getAmount());
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", 0);
- intent.putExtra("progressstatus", status);
- ctx.startService(intent);
-
- }
-
- @Subscribe
- public void onStatusEvent(final EventDismissBolusprogressIfRunning ev) {
- if (ev.result == null) return;
-
- String status;
- if (ev.result.success) {
- status = MainApp.gs(R.string.success);
- } else {
- status = MainApp.gs(R.string.nosuccess);
- }
- Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS);
- intent.putExtra("progresspercent", 100);
- intent.putExtra("progressstatus", status);
- ctx.startService(intent);
- }
-
public void requestActionConfirmation(String title, String message, String actionstring) {
Intent intent = new Intent(ctx, WatchUpdaterService.class).setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java
index 2421a1561e..da61b83b98 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatuslinePlugin.java
@@ -5,9 +5,8 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
-import androidx.annotation.NonNull;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -26,12 +25,16 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.TreatmentsInterface;
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.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by adrian on 17/11/16.
@@ -39,6 +42,8 @@ import info.nightscout.androidaps.utils.DecimalFormatter;
public class StatuslinePlugin extends PluginBase {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
private static StatuslinePlugin statuslinePlugin;
public static StatuslinePlugin getPlugin() {
@@ -80,14 +85,64 @@ public class StatuslinePlugin extends PluginBase {
@Override
protected void onStart() {
- MainApp.bus().register(this);
super.onStart();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventRefreshOverview.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if ((lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)))
+ sendStatus();
+ },
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempBasalChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTreatmentChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventConfigBuilderChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppInitialized.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> sendStatus(),
+ FabricPrivacy::logException
+ ));
}
@Override
protected void onStop() {
super.onStop();
- MainApp.bus().unregister(this);
+ disposable.clear();
sendStatus();
}
@@ -158,50 +213,4 @@ public class StatuslinePlugin extends PluginBase {
return status;
}
-
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange ev) {
- // status may be formated differently
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventAppInitialized ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventConfigBuilderChange ev) {
- sendStatus();
- }
-
- @Subscribe
- public void onStatusEvent(final EventRefreshOverview ev) {
- //Filter events where loop is (de)activated
- if ((lastLoopStatus != LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))) {
- sendStatus();
- }
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java
index 444b2db67a..67d46df22d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java
@@ -1,12 +1,11 @@
package info.nightscout.androidaps.plugins.iob.iobCobCalculator;
import android.os.SystemClock;
+
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.collection.LongSparseArray;
-import com.squareup.otto.Subscribe;
-
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,16 +30,20 @@ import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
-import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
import static info.nightscout.androidaps.utils.DateUtil.now;
@@ -50,6 +53,7 @@ import static info.nightscout.androidaps.utils.DateUtil.now;
public class IobCobCalculatorPlugin extends PluginBase {
private Logger log = LoggerFactory.getLogger(L.AUTOSENS);
+ private CompositeDisposable disposable = new CompositeDisposable();
private static IobCobCalculatorPlugin plugin = null;
@@ -83,14 +87,123 @@ public class IobCobCalculatorPlugin extends PluginBase {
@Override
protected void onStart() {
- MainApp.bus().register(this);
super.onStart();
+ // EventConfigBuilderChange
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventConfigBuilderChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (this != getPlugin()) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Ignoring event for non default instance");
+ return;
+ }
+ stopCalculation("onEventConfigBuilderChange");
+ synchronized (dataLock) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
+ iobTable = new LongSparseArray<>();
+ autosensDataTable = new LongSparseArray<>();
+ }
+ runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, event);
+ }, FabricPrivacy::logException)
+ );
+ // EventNewBasalProfile
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewBasalProfile.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (this != getPlugin()) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Ignoring event for non default instance");
+ return;
+ }
+ if (ConfigBuilderPlugin.getPlugin() == null)
+ return; // app still initializing
+ if (event == null) { // on init no need of reset
+ return;
+ }
+ stopCalculation("onNewProfile");
+ synchronized (dataLock) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
+ iobTable = new LongSparseArray<>();
+ autosensDataTable = new LongSparseArray<>();
+ basalDataTable = new LongSparseArray<>();
+ }
+ runCalculation("onNewProfile", System.currentTimeMillis(), false, true, event);
+ }, FabricPrivacy::logException)
+ );
+ // EventNewBG
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewBG.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (this != getPlugin()) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Ignoring event for non default instance");
+ return;
+ }
+ stopCalculation("onEventNewBG");
+ runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, event);
+ }, FabricPrivacy::logException)
+ );
+ // EventPreferenceChange
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (this != getPlugin()) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Ignoring event for non default instance");
+ return;
+ }
+ if (event.isChanged(R.string.key_openapsama_autosens_period) ||
+ event.isChanged(R.string.key_age) ||
+ event.isChanged(R.string.key_absorption_maxtime) ||
+ event.isChanged(R.string.key_openapsama_min_5m_carbimpact) ||
+ event.isChanged(R.string.key_absorption_cutoff) ||
+ event.isChanged(R.string.key_openapsama_autosens_max) ||
+ event.isChanged(R.string.key_openapsama_autosens_min) ||
+ event.isChanged(R.string.key_insulin_oref_peak)
+ ) {
+ stopCalculation("onEventPreferenceChange");
+ synchronized (dataLock) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records" + " BasalData: " + basalDataTable.size() + " records");
+ iobTable = new LongSparseArray<>();
+ autosensDataTable = new LongSparseArray<>();
+ basalDataTable = new LongSparseArray<>();
+ }
+ runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, event);
+ }
+ }, FabricPrivacy::logException)
+ );
+ // EventAppInitialized
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppInitialized.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (this != getPlugin()) {
+ if (L.isEnabled(L.AUTOSENS))
+ log.debug("Ignoring event for non default instance");
+ return;
+ }
+ runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, event);
+ }, FabricPrivacy::logException)
+ );
+ // EventNewHistoryData
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNewHistoryData.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> newHistoryData(event), FabricPrivacy::logException)
+ );
}
@Override
protected void onStop() {
+ disposable.clear();
super.onStop();
- MainApp.bus().unregister(this);
}
public LongSparseArray getAutosensDataTable() {
@@ -529,7 +642,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
count++;
}
}
- return sum /count;
+ return sum / count;
}
@Nullable
@@ -627,29 +740,6 @@ public class IobCobCalculatorPlugin extends PluginBase {
return array;
}
- @Subscribe
- @SuppressWarnings("unused")
- public void onEventAppInitialized(EventAppInitialized ev) {
- if (this != getPlugin()) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Ignoring event for non default instance");
- return;
- }
- runCalculation("onEventAppInitialized", System.currentTimeMillis(), true, true, ev);
- }
-
- @Subscribe
- @SuppressWarnings("unused")
- public void onEventNewBG(EventNewBG ev) {
- if (this != getPlugin()) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Ignoring event for non default instance");
- return;
- }
- stopCalculation("onEventNewBG");
- runCalculation("onEventNewBG", System.currentTimeMillis(), true, true, ev);
- }
-
public void stopCalculation(String from) {
if (thread != null && thread.getState() != Thread.State.TERMINATED) {
stopCalculationTrigger = true;
@@ -675,76 +765,8 @@ public class IobCobCalculatorPlugin extends PluginBase {
}
}
- @Subscribe
- public void onNewProfile(EventNewBasalProfile ev) {
- if (this != getPlugin()) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Ignoring event for non default instance");
- return;
- }
- if (ConfigBuilderPlugin.getPlugin() == null)
- return; // app still initializing
- if (ev == null) { // on init no need of reset
- return;
- }
- stopCalculation("onNewProfile");
- synchronized (dataLock) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
- iobTable = new LongSparseArray<>();
- autosensDataTable = new LongSparseArray<>();
- basalDataTable = new LongSparseArray<>();
- }
- runCalculation("onNewProfile", System.currentTimeMillis(), false, true, ev);
- }
-
- @Subscribe
- public void onEventPreferenceChange(EventPreferenceChange ev) {
- if (this != getPlugin()) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Ignoring event for non default instance");
- return;
- }
- if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
- ev.isChanged(R.string.key_age) ||
- ev.isChanged(R.string.key_absorption_maxtime) ||
- ev.isChanged(R.string.key_openapsama_min_5m_carbimpact) ||
- ev.isChanged(R.string.key_absorption_cutoff) ||
- ev.isChanged(R.string.key_openapsama_autosens_max) ||
- ev.isChanged(R.string.key_openapsama_autosens_min)
- ) {
- stopCalculation("onEventPreferenceChange");
- synchronized (dataLock) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records" + " BasalData: " + basalDataTable.size() + " records");
- iobTable = new LongSparseArray<>();
- autosensDataTable = new LongSparseArray<>();
- basalDataTable = new LongSparseArray<>();
- }
- runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, ev);
- }
- }
-
- @Subscribe
- public void onEventConfigBuilderChange(EventConfigBuilderChange ev) {
- if (this != getPlugin()) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Ignoring event for non default instance");
- return;
- }
- stopCalculation("onEventConfigBuilderChange");
- synchronized (dataLock) {
- if (L.isEnabled(L.AUTOSENS))
- log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
- iobTable = new LongSparseArray<>();
- autosensDataTable = new LongSparseArray<>();
- }
- runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, ev);
- }
-
// When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated
- @Subscribe
- public void onEventNewHistoryData(EventNewHistoryData ev) {
+ public void newHistoryData(EventNewHistoryData ev) {
if (this != getPlugin()) {
if (L.isEnabled(L.AUTOSENS))
log.debug("Ignoring event for non default instance");
@@ -754,7 +776,7 @@ public class IobCobCalculatorPlugin extends PluginBase {
stopCalculation("onEventNewHistoryData");
synchronized (dataLock) {
// clear up 5 min back for proper COB calculation
- long time = ev.time - 5 * 60 * 1000L;
+ long time = ev.getTime() - 5 * 60 * 1000L;
if (L.isEnabled(L.AUTOSENS))
log.debug("Invalidating cached data to: " + DateUtil.dateAndTimeFullString(time));
for (int index = iobTable.size() - 1; index >= 0; index--) {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java
index 2b427602f5..07d1b52947 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java
@@ -119,7 +119,7 @@ public class IobCobOref1Thread extends Thread {
// start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) {
String progress = i + (MainApp.isDev() ? " (" + from + ")" : "");
- MainApp.bus().post(new EventIobCalculationProgress(progress));
+ RxBus.INSTANCE.send(new EventIobCalculationProgress(progress));
if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false;
@@ -387,12 +387,12 @@ public class IobCobOref1Thread extends Thread {
}
new Thread(() -> {
SystemClock.sleep(1000);
- MainApp.bus().post(new EventAutosensCalculationFinished(cause));
+ RxBus.INSTANCE.send(new EventAutosensCalculationFinished(cause));
}).start();
} finally {
if (mWakeLock != null)
mWakeLock.release();
- MainApp.bus().post(new EventIobCalculationProgress(""));
+ RxBus.INSTANCE.send(new EventIobCalculationProgress(""));
if (L.isEnabled(L.AUTOSENS)) {
log.debug("AUTOSENSDATA thread ended: " + from);
log.debug("Midnights: " + MidnightTime.log());
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java
index 756cee9853..a8ecc2a06a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java
@@ -3,6 +3,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator;
import android.content.Context;
import android.os.PowerManager;
import android.os.SystemClock;
+
import androidx.collection.LongSparseArray;
import org.slf4j.Logger;
@@ -117,7 +118,7 @@ public class IobCobThread extends Thread {
// start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i--) {
String progress = i + (MainApp.isDev() ? " (" + from + ")" : "");
- MainApp.bus().post(new EventIobCalculationProgress(progress));
+ RxBus.INSTANCE.send(new EventIobCalculationProgress(progress));
if (iobCobCalculatorPlugin.stopCalculationTrigger) {
iobCobCalculatorPlugin.stopCalculationTrigger = false;
@@ -312,13 +313,12 @@ public class IobCobThread extends Thread {
}
new Thread(() -> {
SystemClock.sleep(1000);
- MainApp.bus().post(new EventAutosensCalculationFinished(cause));
RxBus.INSTANCE.send(new EventAutosensCalculationFinished(cause));
}).start();
} finally {
if (mWakeLock != null)
mWakeLock.release();
- MainApp.bus().post(new EventIobCalculationProgress(""));
+ RxBus.INSTANCE.send(new EventIobCalculationProgress(""));
if (L.isEnabled(L.AUTOSENS)) {
log.debug("AUTOSENSDATA thread ended: " + from);
log.debug("Midnights: " + MidnightTime.log());
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java
deleted file mode 100644
index 5a4a9a8eae..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events;
-
-import info.nightscout.androidaps.events.Event;
-
-public class EventIobCalculationProgress extends Event {
- public String progress;
-
- public EventIobCalculationProgress(String progress) {
- this.progress = progress;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt
new file mode 100644
index 0000000000..f2e8059b10
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventIobCalculationProgress.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventIobCalculationProgress(var progress: String) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java
deleted file mode 100644
index f84fdd1adf..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 26.04.2017.
- */
-
-public class EventNewHistoryData extends Event {
- public long time = 0;
-
- public EventNewHistoryData(long time) {
- this.time = time;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt
new file mode 100644
index 0000000000..c2372aff83
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryData.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventNewHistoryData(var time: Long) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java
index a8f77ea54c..f8969e9594 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.java
@@ -13,8 +13,7 @@ import android.widget.RadioButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
-
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.Fragment;
import java.text.DecimalFormat;
@@ -23,19 +22,24 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.interfaces.PumpDescription;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.NumberPicker;
import info.nightscout.androidaps.utils.SafeParse;
import info.nightscout.androidaps.utils.TimeListEdit;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.MIN_DIA;
-public class LocalProfileFragment extends SubscriberFragment {
+public class LocalProfileFragment extends Fragment {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
private NumberPicker diaView;
private RadioButton mgdlView;
private RadioButton mmolView;
@@ -143,6 +147,23 @@ public class LocalProfileFragment extends SubscriberFragment {
return layout;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventInitializationChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
+ updateGUI();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
public void doEdit() {
LocalProfilePlugin.getPlugin().setEdited(true);
updateGUI();
@@ -157,12 +178,6 @@ public class LocalProfileFragment extends SubscriberFragment {
return MainApp.gs(R.string.localprofile);
}
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged e) {
- updateGUI();
- }
-
- @Override
protected void updateGUI() {
Activity activity = getActivity();
if (activity != null)
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java
index 089611b40d..e3e068c1cb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.java
@@ -18,6 +18,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.utils.DecimalFormatter;
import info.nightscout.androidaps.utils.SP;
@@ -83,7 +84,7 @@ public class LocalProfilePlugin extends PluginBase implements ProfileInterface {
edited = false;
if (L.isEnabled(L.PROFILE))
log.debug("Storing settings: " + getRawProfile().getData().toString());
- MainApp.bus().post(new EventProfileStoreChanged());
+ RxBus.INSTANCE.send(new EventProfileStoreChanged());
}
public synchronized void loadSettings() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java
index a6088f5515..38afe62bdf 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.java
@@ -12,7 +12,6 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ProfileStore;
import info.nightscout.androidaps.events.EventProfileStoreChanged;
@@ -58,13 +57,11 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface {
@Override
protected void onStart() {
- MainApp.bus().register(this);
super.onStart();
}
@Override
protected void onStop() {
- MainApp.bus().unregister(this);
super.onStop();
}
@@ -78,7 +75,7 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface {
profile = new ProfileStore(new JSONObject(profileString));
storeNSProfile();
if (isEnabled(PluginType.PROFILE)) {
- MainApp.bus().post(new EventProfileStoreChanged());
+ RxBus.INSTANCE.send(new EventProfileStoreChanged());
RxBus.INSTANCE.send(new EventNSProfileUpdateGUI());
}
if (L.isEnabled(L.PROFILE))
@@ -111,7 +108,7 @@ public class NSProfilePlugin extends PluginBase implements ProfileInterface {
if (L.isEnabled(L.PROFILE))
log.debug("Stored profile not found");
// force restart of nsclient to fetch profile
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java
index b8a7d16be5..ecf4fc423b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfileFragment.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.profile.simple;
-import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
@@ -13,19 +12,24 @@ import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.Fragment;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventInitializationChanged;
+import info.nightscout.androidaps.plugins.bus.RxBus;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment;
import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog;
import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SafeParse;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
+
+public class SimpleProfileFragment extends Fragment {
+ private CompositeDisposable disposable = new CompositeDisposable();
-public class SimpleProfileFragment extends SubscriberFragment {
EditText diaView;
RadioButton mgdlView;
RadioButton mmolView;
@@ -122,27 +126,34 @@ public class SimpleProfileFragment extends SubscriberFragment {
return layout;
}
- @Subscribe
- public void onStatusEvent(final EventInitializationChanged e) {
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventInitializationChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
updateGUI();
}
@Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- boolean isValid = SimpleProfilePlugin.getPlugin().getProfile() != null && SimpleProfilePlugin.getPlugin().getProfile().getDefaultProfile().isValid(MainApp.gs(R.string.simpleprofile));
- if (!ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized() || ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !isValid) {
- profileswitchButton.setVisibility(View.GONE);
- } else {
- profileswitchButton.setVisibility(View.VISIBLE);
- }
- if (isValid)
- invalidProfile.setVisibility(View.GONE);
- else
- invalidProfile.setVisibility(View.VISIBLE);
- });
+ boolean isValid = SimpleProfilePlugin.getPlugin().getProfile() != null && SimpleProfilePlugin.getPlugin().getProfile().getDefaultProfile().isValid(MainApp.gs(R.string.simpleprofile));
+ if (!ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized() || ConfigBuilderPlugin.getPlugin().getActivePump().isSuspended() || !isValid) {
+ profileswitchButton.setVisibility(View.GONE);
+ } else {
+ profileswitchButton.setVisibility(View.VISIBLE);
+ }
+ if (isValid)
+ invalidProfile.setVisibility(View.GONE);
+ else
+ invalidProfile.setVisibility(View.VISIBLE);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java
index d3d3952fae..61ca403f55 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/simple/SimpleProfilePlugin.java
@@ -19,6 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.utils.SP;
/**
@@ -75,7 +76,7 @@ public class SimpleProfilePlugin extends PluginBase implements ProfileInterface
createConvertedProfile();
if (L.isEnabled(L.PROFILE))
log.debug("Storing settings: " + getRawProfile().getData().toString());
- MainApp.bus().post(new EventProfileStoreChanged());
+ RxBus.INSTANCE.send(new EventProfileStoreChanged());
}
private void loadSettings() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java
index 1a924fa9f5..bfd5c6104e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.java
@@ -5,28 +5,33 @@ import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
-import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
+import androidx.fragment.app.Fragment;
-import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
-import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.combo.events.EventComboPumpUpdateGUI;
+import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.PumpState;
+import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.events.EventQueueChanged;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
+
+public class ComboFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
-public class ComboFragment extends SubscriberFragment implements View.OnClickListener {
private TextView stateView;
private TextView activityView;
private TextView batteryView;
@@ -58,10 +63,31 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis
refreshButton = view.findViewById(R.id.combo_refresh_button);
refreshButton.setOnClickListener(this);
- updateGUI();
return view;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventComboPumpUpdateGUI.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventQueueChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
private void runOnUiThread(Runnable action) {
Activity activity = getActivity();
if (activity != null) {
@@ -84,148 +110,135 @@ public class ComboFragment extends SubscriberFragment implements View.OnClickLis
}
}
- @Subscribe
- public void onStatusEvent(final EventComboPumpUpdateGUI ignored) {
- updateGUI();
- }
+ public void updateGui() {
+ ComboPlugin plugin = ComboPlugin.getPlugin();
- @Subscribe
- public void onStatusEvent(final EventQueueChanged ignored) {
- updateGUI();
- }
+ // state
+ stateView.setText(plugin.getStateSummary());
+ PumpState ps = plugin.getPump().state;
+ if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY
+ || ps.activeAlert != null && ps.activeAlert.errorCode != null) {
+ stateView.setTextColor(Color.RED);
+ stateView.setTypeface(null, Typeface.BOLD);
+ } else if (plugin.getPump().state.suspended
+ || ps.activeAlert != null && ps.activeAlert.warningCode != null) {
+ stateView.setTextColor(Color.YELLOW);
+ stateView.setTypeface(null, Typeface.BOLD);
+ } else {
+ stateView.setTextColor(Color.WHITE);
+ stateView.setTypeface(null, Typeface.NORMAL);
+ }
+ // activity
+ String activity = plugin.getPump().activity;
+ if (activity != null) {
+ activityView.setTextColor(Color.WHITE);
+ activityView.setTextSize(14);
+ activityView.setText(activity);
+ } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) {
+ activityView.setTextColor(Color.WHITE);
+ activityView.setTextSize(14);
+ activityView.setText("");
+ } else if (plugin.isInitialized()) {
+ activityView.setTextColor(Color.WHITE);
+ activityView.setTextSize(20);
+ activityView.setText("{fa-bed}");
+ } else {
+ activityView.setTextColor(Color.RED);
+ activityView.setTextSize(14);
+ activityView.setText(MainApp.gs(R.string.pump_unreachable));
+ }
- public void updateGUI() {
- runOnUiThread(() -> {
- ComboPlugin plugin = ComboPlugin.getPlugin();
-
- // state
- stateView.setText(plugin.getStateSummary());
- PumpState ps = plugin.getPump().state;
- if (ps.insulinState == PumpState.EMPTY || ps.batteryState == PumpState.EMPTY
- || ps.activeAlert != null && ps.activeAlert.errorCode != null) {
- stateView.setTextColor(Color.RED);
- stateView.setTypeface(null, Typeface.BOLD);
- } else if (plugin.getPump().state.suspended
- || ps.activeAlert != null && ps.activeAlert.warningCode != null) {
- stateView.setTextColor(Color.YELLOW);
- stateView.setTypeface(null, Typeface.BOLD);
+ if (plugin.isInitialized()) {
+ // battery
+ batteryView.setTextSize(20);
+ if (ps.batteryState == PumpState.EMPTY) {
+ batteryView.setText("{fa-battery-empty}");
+ batteryView.setTextColor(Color.RED);
+ } else if (ps.batteryState == PumpState.LOW) {
+ batteryView.setText("{fa-battery-quarter}");
+ batteryView.setTextColor(Color.YELLOW);
} else {
- stateView.setTextColor(Color.WHITE);
- stateView.setTypeface(null, Typeface.NORMAL);
+ batteryView.setText("{fa-battery-full}");
+ batteryView.setTextColor(Color.WHITE);
}
- // activity
- String activity = plugin.getPump().activity;
- if (activity != null) {
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(14);
- activityView.setText(activity);
- } else if (ConfigBuilderPlugin.getPlugin().getCommandQueue().size() > 0) {
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(14);
- activityView.setText("");
- } else if (plugin.isInitialized()){
- activityView.setTextColor(Color.WHITE);
- activityView.setTextSize(20);
- activityView.setText("{fa-bed}");
+ // reservoir
+ int reservoirLevel = plugin.getPump().reservoirLevel;
+ if (reservoirLevel != -1) {
+ reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname));
+ } else if (ps.insulinState == PumpState.LOW) {
+ reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low));
+ } else if (ps.insulinState == PumpState.EMPTY) {
+ reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty));
} else {
- activityView.setTextColor(Color.RED);
- activityView.setTextSize(14);
- activityView.setText(MainApp.gs(R.string.pump_unreachable));
+ reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal));
}
- if (plugin.isInitialized()) {
- // battery
- batteryView.setTextSize(20);
- if (ps.batteryState == PumpState.EMPTY) {
- batteryView.setText("{fa-battery-empty}");
- batteryView.setTextColor(Color.RED);
- } else if (ps.batteryState == PumpState.LOW) {
- batteryView.setText("{fa-battery-quarter}");
- batteryView.setTextColor(Color.YELLOW);
- } else {
- batteryView.setText("{fa-battery-full}");
- batteryView.setTextColor(Color.WHITE);
- }
-
- // reservoir
- int reservoirLevel = plugin.getPump().reservoirLevel;
- if (reservoirLevel != -1) {
- reservoirView.setText(reservoirLevel + " " + MainApp.gs(R.string.insulin_unit_shortname));
- } else if (ps.insulinState == PumpState.LOW) {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_low));
- } else if (ps.insulinState == PumpState.EMPTY) {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_empty));
- } else {
- reservoirView.setText(MainApp.gs(R.string.combo_reservoir_normal));
- }
-
- if (ps.insulinState == PumpState.UNKNOWN) {
- reservoirView.setTextColor(Color.WHITE);
- reservoirView.setTypeface(null, Typeface.NORMAL);
- } else if (ps.insulinState == PumpState.LOW) {
- reservoirView.setTextColor(Color.YELLOW);
- reservoirView.setTypeface(null, Typeface.BOLD);
- } else if (ps.insulinState == PumpState.EMPTY) {
- reservoirView.setTextColor(Color.RED);
- reservoirView.setTypeface(null, Typeface.BOLD);
- } else {
- reservoirView.setTextColor(Color.WHITE);
- reservoirView.setTypeface(null, Typeface.NORMAL);
- }
-
- // last connection
- String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime);
- long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60;
- if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) {
- lastConnectionView.setText(R.string.combo_pump_connected_now);
- lastConnectionView.setTextColor(Color.WHITE);
- } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) {
- lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min));
- lastConnectionView.setTextColor(Color.RED);
- } else {
- lastConnectionView.setText(minAgo);
- lastConnectionView.setTextColor(Color.WHITE);
- }
-
- // last bolus
- Bolus bolus = plugin.getPump().lastBolus;
- if (bolus != null) {
- long agoMsc = System.currentTimeMillis() - bolus.timestamp;
- double bolusMinAgo = agoMsc / 60d / 1000d;
- String unit = MainApp.gs(R.string.insulin_unit_shortname);
- String ago;
- if ((agoMsc < 60 * 1000)) {
- ago = MainApp.gs(R.string.combo_pump_connected_now);
- } else if (bolusMinAgo < 60) {
- ago = DateUtil.minAgo(bolus.timestamp);
- } else {
- ago = DateUtil.hourAgo(bolus.timestamp);
- }
- lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago));
- } else {
- lastBolusView.setText("");
- }
-
- // base basal rate
- baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate()));
-
- // TBR
- String tbrStr = "";
- if (ps.tbrPercent != -1 && ps.tbrPercent != 100) {
- long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60;
- long remaining = ps.tbrRemainingDuration - minSinceRead;
- if (remaining >= 0) {
- tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining);
- }
- }
- tempBasalText.setText(tbrStr);
-
- // stats
- bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L)));
- tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L)));
+ if (ps.insulinState == PumpState.UNKNOWN) {
+ reservoirView.setTextColor(Color.WHITE);
+ reservoirView.setTypeface(null, Typeface.NORMAL);
+ } else if (ps.insulinState == PumpState.LOW) {
+ reservoirView.setTextColor(Color.YELLOW);
+ reservoirView.setTypeface(null, Typeface.BOLD);
+ } else if (ps.insulinState == PumpState.EMPTY) {
+ reservoirView.setTextColor(Color.RED);
+ reservoirView.setTypeface(null, Typeface.BOLD);
+ } else {
+ reservoirView.setTextColor(Color.WHITE);
+ reservoirView.setTypeface(null, Typeface.NORMAL);
}
- });
+
+ // last connection
+ String minAgo = DateUtil.minAgo(plugin.getPump().lastSuccessfulCmdTime);
+ long min = (System.currentTimeMillis() - plugin.getPump().lastSuccessfulCmdTime) / 1000 / 60;
+ if (plugin.getPump().lastSuccessfulCmdTime + 60 * 1000 > System.currentTimeMillis()) {
+ lastConnectionView.setText(R.string.combo_pump_connected_now);
+ lastConnectionView.setTextColor(Color.WHITE);
+ } else if (plugin.getPump().lastSuccessfulCmdTime + 30 * 60 * 1000 < System.currentTimeMillis()) {
+ lastConnectionView.setText(MainApp.gs(R.string.combo_no_pump_connection, min));
+ lastConnectionView.setTextColor(Color.RED);
+ } else {
+ lastConnectionView.setText(minAgo);
+ lastConnectionView.setTextColor(Color.WHITE);
+ }
+
+ // last bolus
+ Bolus bolus = plugin.getPump().lastBolus;
+ if (bolus != null) {
+ long agoMsc = System.currentTimeMillis() - bolus.timestamp;
+ double bolusMinAgo = agoMsc / 60d / 1000d;
+ String unit = MainApp.gs(R.string.insulin_unit_shortname);
+ String ago;
+ if ((agoMsc < 60 * 1000)) {
+ ago = MainApp.gs(R.string.combo_pump_connected_now);
+ } else if (bolusMinAgo < 60) {
+ ago = DateUtil.minAgo(bolus.timestamp);
+ } else {
+ ago = DateUtil.hourAgo(bolus.timestamp);
+ }
+ lastBolusView.setText(MainApp.gs(R.string.combo_last_bolus, bolus.amount, unit, ago));
+ } else {
+ lastBolusView.setText("");
+ }
+
+ // base basal rate
+ baseBasalRate.setText(MainApp.gs(R.string.pump_basebasalrate, plugin.getBaseBasalRate()));
+
+ // TBR
+ String tbrStr = "";
+ if (ps.tbrPercent != -1 && ps.tbrPercent != 100) {
+ long minSinceRead = (System.currentTimeMillis() - plugin.getPump().state.timestamp) / 1000 / 60;
+ long remaining = ps.tbrRemainingDuration - minSinceRead;
+ if (remaining >= 0) {
+ tbrStr = MainApp.gs(R.string.combo_tbr_remaining, ps.tbrPercent, remaining);
+ }
+ }
+ tempBasalText.setText(tbrStr);
+
+ // stats
+ bolusCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_BOLUSES_DELIVERED, 0L)));
+ tbrCount.setText(String.valueOf(SP.getLong(ComboPlugin.COMBO_TBRS_SET, 0L)));
+ }
}
}
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java
index 7058252eb3..32a17f8a89 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java
@@ -375,7 +375,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
setValidBasalRateProfileSelectedOnPump(true);
pump.initialized = true;
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
// show notification to check pump date if last bolus is older than 24 hours
// or is in the future
@@ -390,7 +390,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// ComboFragment updates state fully only after the pump has initialized,
// so force an update after initialization completed
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
/**
@@ -406,7 +406,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (result.state.menu != null) {
pump.state = result.state;
}
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
@Override
@@ -433,26 +433,26 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
}
private static BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
- EventOverviewBolusProgress event = EventOverviewBolusProgress.getInstance();
+ EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE;
switch (state) {
case PROGRAMMING:
- event.status = MainApp.gs(R.string.combo_programming_bolus);
+ event.setStatus(MainApp.gs(R.string.combo_programming_bolus));
break;
case DELIVERING:
- event.status = MainApp.gs(R.string.bolusdelivering, delivered);
+ event.setStatus(MainApp.gs(R.string.bolusdelivering, delivered));
break;
case DELIVERED:
- event.status = MainApp.gs(R.string.bolusdelivered, delivered);
+ event.setStatus(MainApp.gs(R.string.bolusdelivered, delivered));
break;
case STOPPING:
- event.status = MainApp.gs(R.string.bolusstopping);
+ event.setStatus(MainApp.gs(R.string.bolusstopping));
break;
case STOPPED:
- event.status = MainApp.gs(R.string.bolusstopped);
+ event.setStatus(MainApp.gs(R.string.bolusstopped));
break;
}
- event.percent = percent;
- MainApp.bus().post(event);
+ event.setPercent(percent);
+ RxBus.INSTANCE.send(event);
};
/**
@@ -474,18 +474,18 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
// no bolus required, carb only treatment
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = new Treatment();
- bolusingEvent.t.isSMB = detailedBolusInfo.isSMB;
- bolusingEvent.percent = 100;
- MainApp.bus().post(bolusingEvent);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(new Treatment());
+ bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB;
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(bolusingEvent);
return new PumpEnactResult().success(true).enacted(true)
.bolusDelivered(0d).carbsDelivered(detailedBolusInfo.carbs)
.comment(MainApp.gs(R.string.virtualpump_resultok));
}
} finally {
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
}
@@ -493,7 +493,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
private PumpEnactResult deliverBolus(final DetailedBolusInfo detailedBolusInfo) {
try {
pump.activity = MainApp.gs(R.string.combo_pump_action_bolusing, detailedBolusInfo.insulin);
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
// check pump is ready and all pump bolus records are known
CommandResult stateResult = runCommand(null, 2, () -> ruffyScripter.readQuickInfo(1));
@@ -558,7 +558,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
Treatment treatment = new Treatment();
treatment.isSMB = detailedBolusInfo.isSMB;
- EventOverviewBolusProgress.getInstance().t = treatment;
+ EventOverviewBolusProgress.INSTANCE.setT(treatment);
// start bolus delivery
scripterIsBolusing = true;
@@ -628,7 +628,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
.carbsDelivered(detailedBolusInfo.carbs);
} finally {
pump.activity = null;
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
RxBus.INSTANCE.send(new EventRefreshOverview("Bolus"));
cancelBolus = false;
}
@@ -760,7 +760,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
.source(Source.USER);
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempStart);
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
incrementTbrCount();
@@ -848,7 +848,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (!ruffyScripter.isConnected()) {
String originalActivity = pump.activity;
pump.activity = MainApp.gs(R.string.combo_activity_checking_pump_state);
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
CommandResult preCheckError = runOnConnectChecks();
pump.activity = originalActivity;
if (preCheckError != null) {
@@ -859,7 +859,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
if (activity != null) {
pump.activity = activity;
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
commandResult = commandExecution.execute();
@@ -892,7 +892,7 @@ public class ComboPlugin extends PluginBase implements PumpInterface, Constraint
} finally {
if (activity != null) {
pump.activity = null;
- MainApp.bus().post(new EventComboPumpUpdateGUI());
+ RxBus.INSTANCE.send(new EventComboPumpUpdateGUI());
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java
deleted file mode 100644
index 72359b7db2..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.combo.events;
-
-/**
- * Created by mike on 24.05.2017.
- */
-
-public class EventComboPumpUpdateGUI {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt
new file mode 100644
index 0000000000..604b55cd25
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/events/EventComboPumpUpdateGUI.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.combo.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventComboPumpUpdateGUI : EventUpdateGui()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java
index fa68e55616..b1d5db0e2a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java
@@ -6,8 +6,6 @@ import android.content.ServiceConnection;
import androidx.fragment.app.FragmentActivity;
-import com.squareup.otto.Subscribe;
-
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -31,14 +29,19 @@ import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.PumpDescription;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
+import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by andy on 23.04.18.
@@ -47,13 +50,14 @@ import info.nightscout.androidaps.utils.DecimalFormatter;
// When using this class, make sure that your first step is to create mConnection (see MedtronicPumpPlugin)
public abstract class PumpPluginAbstract extends PluginBase implements PumpInterface, ConstraintsInterface {
+ private CompositeDisposable disposable = new CompositeDisposable();
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false)
- .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver));
+ .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_supported_by_pump_driver));
protected static final PumpEnactResult OPERATION_NOT_YET_SUPPORTED = new PumpEnactResult().success(false)
- .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump));
+ .enacted(false).comment(MainApp.gs(R.string.pump_operation_not_yet_supported_by_pump));
protected PumpDescription pumpDescription = new PumpDescription();
protected PumpStatus pumpStatus;
@@ -80,15 +84,21 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
@Override
protected void onStart() {
+ super.onStart();
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, getServiceClass());
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
serviceRunning = true;
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ MainApp.instance().getApplicationContext().unbindService(serviceConnection);
+ }, FabricPrivacy::logException)
+ );
onStartCustomActions();
- super.onStart();
}
@@ -99,7 +109,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
serviceRunning = false;
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
@@ -121,14 +131,6 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
*/
public abstract Class getServiceClass();
-
- @SuppressWarnings("UnusedParameters")
- @Subscribe
- public void onStatusEvent(final EventAppExit e) {
- MainApp.instance().getApplicationContext().unbindService(serviceConnection);
- }
-
-
public PumpStatus getPumpStatusData() {
return pumpStatus;
}
@@ -239,7 +241,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
@Override
public PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile,
- boolean enforceNew) {
+ boolean enforceNew) {
if (isLoggingEnabled())
LOG.warn("setTempBasalAbsolute [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
@@ -248,7 +250,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile,
- boolean enforceNew) {
+ boolean enforceNew) {
if (isLoggingEnabled())
LOG.warn("setTempBasalPercent [PumpPluginAbstract] - Not implemented.");
return getOperationNotSupportedWithCustomText(R.string.pump_operation_not_supported_by_pump_driver);
@@ -340,7 +342,7 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
TemporaryBasal tb = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
if (tb != null) {
extended.put("TempBasalAbsoluteRate",
- tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile));
+ tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile));
extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date));
extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes());
}
@@ -372,20 +374,20 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
String ret = "";
if (pumpStatus.lastConnection != 0) {
Long agoMsec = System.currentTimeMillis() - pumpStatus.lastConnection;
- int agoMin = (int)(agoMsec / 60d / 1000d);
+ int agoMin = (int) (agoMsec / 60d / 1000d);
ret += "LastConn: " + agoMin + " min ago\n";
}
if (pumpStatus.lastBolusTime != null && pumpStatus.lastBolusTime.getTime() != 0) {
ret += "LastBolus: " + DecimalFormatter.to2Decimal(pumpStatus.lastBolusAmount) + "U @" + //
- android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n";
+ android.text.format.DateFormat.format("HH:mm", pumpStatus.lastBolusTime) + "\n";
}
TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin()
- .getRealTempBasalFromHistory(System.currentTimeMillis());
+ .getRealTempBasalFromHistory(System.currentTimeMillis());
if (activeTemp != null) {
ret += "Temp: " + activeTemp.toStringFull() + "\n";
}
ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(
- System.currentTimeMillis());
+ System.currentTimeMillis());
if (activeExtendedBolus != null) {
ret += "Extended: " + activeExtendedBolus.toString() + "\n";
}
@@ -409,25 +411,28 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter
if (isLoggingEnabled())
LOG.error("deliverTreatment: Invalid input");
return new PumpEnactResult().success(false).enacted(false).bolusDelivered(0d).carbsDelivered(0d)
- .comment(MainApp.gs(R.string.danar_invalidinput));
+ .comment(MainApp.gs(R.string.danar_invalidinput));
} else if (detailedBolusInfo.insulin > 0) {
// bolus needed, ask pump to deliver it
return deliverBolus(detailedBolusInfo);
} else {
+ if (MedtronicHistoryData.doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: deliverTreatment::(carb only entry)");
+
// no bolus required, carb only treatment
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = new Treatment();
- bolusingEvent.t.isSMB = detailedBolusInfo.isSMB;
- bolusingEvent.percent = 100;
- MainApp.bus().post(bolusingEvent);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(new Treatment());
+ bolusingEvent.getT().isSMB = detailedBolusInfo.isSMB;
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(bolusingEvent);
if (isLoggingEnabled())
LOG.debug("deliverTreatment: Carb only treatment.");
return new PumpEnactResult().success(true).enacted(true).bolusDelivered(0d)
- .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok));
+ .carbsDelivered(detailedBolusInfo.carbs).comment(MainApp.gs(R.string.virtualpump_resultok));
}
} finally {
triggerUIChange();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt
index 293babfc2b..d7833a4fe4 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/bolusInfo/DetailedBolusInfoStorage.kt
@@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.pump.common.bolusInfo
import info.nightscout.androidaps.data.DetailedBolusInfo
import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData
import info.nightscout.androidaps.utils.T
import org.slf4j.LoggerFactory
import java.util.*
@@ -19,6 +20,10 @@ object DetailedBolusInfoStorage {
@Synchronized
fun findDetailedBolusInfo(bolusTime: Long, bolus: Double): DetailedBolusInfo? {
+
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: findDetailedBolusInfo::bolusTime={}, bolus={}", bolusTime, bolus)
+
// Look for info with bolus
for (i in store.indices) {
val d = store[i]
@@ -28,6 +33,9 @@ object DetailedBolusInfoStorage {
if (L.isEnabled(L.PUMP))
log.debug("Using & removing bolus info: " + store[i])
store.removeAt(i)
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: findDetailedBolusInfo::selectedBolus[DetailedBolusInfo={}]", d)
+
return d
}
}
@@ -38,6 +46,8 @@ object DetailedBolusInfoStorage {
if (L.isEnabled(L.PUMP))
log.debug("Using & removing bolus info: " + store[i])
store.removeAt(i)
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: findDetailedBolusInfo::selectedBolus[DetailedBolusInfo={}]", d)
return d
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bLoop.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bLoop.java
index 3e551b6ccf..a7b005b9b8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bLoop.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/data/encoding/Encoding4b6bLoop.java
@@ -16,6 +16,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
*/
public class Encoding4b6bLoop extends Encoding4b6bAbstract {
+ private static final Logger log = LoggerFactory.getLogger(Encoding4b6bLoop.class);
public static final Logger LOG = LoggerFactory.getLogger(Encoding4b6bLoop.class);
public Map codesRev = null;
@@ -108,9 +109,8 @@ public class Encoding4b6bLoop extends Encoding4b6bAbstract {
int index2 = ((bitAccumulator >> (availBits - 12)) & 0b111111);
hiNibble = codesRev.get((bitAccumulator >> (availBits - 6)));
loNibble = codesRev.get(((bitAccumulator >> (availBits - 12)) & 0b111111));
- } catch (Exception ex) {
- System.out.println("Exception: " + ex.getMessage());
- ex.printStackTrace();
+ } catch (Exception e) {
+ log.error("Unhandled exception", e);
return null;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java
index b886861b00..021d1ee068 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneral.java
@@ -122,10 +122,10 @@ public class RileyLinkStatusGeneral extends Fragment implements RefreshableInter
this.medtronicPumpStatus = MedtronicUtil.getPumpStatus();
if (medtronicPumpStatus != null) {
- this.deviceType.setText(MainApp.gs(RileyLinkUtil.getTargetDevice().getResourceId()));
+ this.deviceType.setText(MainApp.gs(RileyLinkTargetDevice.MedtronicPump.getResourceId()));
this.deviceModel.setText(medtronicPumpStatus.pumpType.getDescription());
this.serialNumber.setText(medtronicPumpStatus.serialNumber);
- this.pumpFrequency.setText(medtronicPumpStatus.pumpFrequency);
+ this.pumpFrequency.setText(MainApp.gs(medtronicPumpStatus.pumpFrequency.equals("medtronic_pump_frequency_us_ca") ? R.string.medtronic_pump_frequency_us_ca : R.string.medtronic_pump_frequency_worldwide));
// TODO extend when Omnipod used
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
index e4f097e7db..783553f431 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/DateTimeUtil.java
@@ -250,4 +250,29 @@ public class DateTimeUtil {
return minutes.getMinutes();
}
+
+
+ public static long getMillisFromATDWithAddedMinutes(long atd, int minutesDiff) {
+ GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(atd);
+ oldestEntryTime.add(Calendar.MINUTE, minutesDiff);
+
+ return oldestEntryTime.getTimeInMillis();
+ }
+
+
+ public static long getATDWithAddedMinutes(long atd, int minutesDiff) {
+ GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(atd);
+ oldestEntryTime.add(Calendar.MINUTE, minutesDiff);
+
+ return oldestEntryTime.getTimeInMillis();
+ }
+
+
+ public static long getATDWithAddedMinutes(GregorianCalendar oldestEntryTime, int minutesDiff) {
+ oldestEntryTime.add(Calendar.MINUTE, minutesDiff);
+
+ return toATechDate(oldestEntryTime);
+ }
+
+
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt
index b01bb22104..3f58acf4d2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt
@@ -8,7 +8,6 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
-import com.squareup.otto.Subscribe
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.TDDStatsActivity
@@ -81,12 +80,39 @@ class DanaRFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
- MainApp.bus().register(this)
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += RxBus
.toObservable(EventDanaRNewStatus::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventExtendedBolusChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventTempBasalChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventQueueChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventPumpStatusChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({
+ when {
+ it.sStatus == EventPumpStatusChanged.Status.CONNECTING -> danar_btconnection?.text = "{fa-bluetooth-b spin} " + it.sSecondsElapsed + "s"
+ it.sStatus == EventPumpStatusChanged.Status.CONNECTED -> danar_btconnection?.text = "{fa-bluetooth}"
+ it.sStatus == EventPumpStatusChanged.Status.DISCONNECTED -> danar_btconnection?.text = "{fa-bluetooth-b}"
+ }
+ if (it.getStatus() != "") {
+ dana_pumpstatus?.text = it.getStatus()
+ dana_pumpstatuslayout?.visibility = View.VISIBLE
+ } else {
+ dana_pumpstatuslayout?.visibility = View.GONE
+ }
+ }, { FabricPrivacy.logException(it) })
updateGUI()
}
@@ -94,41 +120,9 @@ class DanaRFragment : Fragment() {
override fun onPause() {
super.onPause()
disposable.clear()
- MainApp.bus().unregister(this)
loopHandler.removeCallbacks(refreshLoop)
}
- @Subscribe
- fun onStatusEvent(c: EventPumpStatusChanged) {
- activity?.runOnUiThread {
- when {
- c.sStatus == EventPumpStatusChanged.CONNECTING -> danar_btconnection?.text = "{fa-bluetooth-b spin} " + c.sSecondsElapsed + "s"
- c.sStatus == EventPumpStatusChanged.CONNECTED -> danar_btconnection?.text = "{fa-bluetooth}"
- c.sStatus == EventPumpStatusChanged.DISCONNECTED -> danar_btconnection?.text = "{fa-bluetooth-b}"
- }
- if (c.textStatus() != "") {
- dana_pumpstatus?.text = c.textStatus()
- dana_pumpstatuslayout?.visibility = View.VISIBLE
- } else {
- dana_pumpstatuslayout?.visibility = View.GONE
- }
- }
-
- }
-
- @Subscribe
- fun onStatusEvent(s: EventTempBasalChange) =
- activity?.runOnUiThread { updateGUI() }
-
-
- @Subscribe
- fun onStatusEvent(s: EventExtendedBolusChange) =
- activity?.runOnUiThread { updateGUI() }
-
- @Subscribe
- fun onStatusEvent(s: EventQueueChanged) =
- activity?.runOnUiThread { updateGUI() }
-
// GUI functions
@Synchronized
internal fun updateGUI() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java
index 6a01c5fed8..e9293b39a6 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java
@@ -5,10 +5,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
-import androidx.fragment.app.FragmentActivity;
-import androidx.appcompat.app.AlertDialog;
-
-import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -22,19 +18,23 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType;
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.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStartWithSpeed;
import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 05.08.2016.
*/
public class DanaRPlugin extends AbstractDanaRPlugin {
+ private CompositeDisposable disposable = new CompositeDisposable();
private static DanaRPlugin plugin = null;
@@ -55,7 +55,27 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, DanaRExecutionService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (isEnabled(PluginType.PUMP)) {
+ boolean previousValue = useExtendedBoluses;
+ useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false);
+
+ if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
+ sExecutionService.extendedBolusStop();
+ }
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ }, FabricPrivacy::logException)
+ );
super.onStart();
}
@@ -64,7 +84,7 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
Context context = MainApp.instance().getApplicationContext();
context.unbindService(mConnection);
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
@@ -84,24 +104,6 @@ public class DanaRPlugin extends AbstractDanaRPlugin {
}
};
- @SuppressWarnings("UnusedParameters")
- @Subscribe
- public void onStatusEvent(final EventAppExit e) {
- MainApp.instance().getApplicationContext().unbindService(mConnection);
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange s) {
- if (isEnabled(PluginType.PUMP)) {
- boolean previousValue = useExtendedBoluses;
- useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false);
-
- if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- sExecutionService.extendedBolusStop();
- }
- }
- }
-
// Plugin base interface
@Override
public String getName() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java
index 2d31510e71..f20a74b024 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.java
@@ -15,8 +15,6 @@ import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,6 +30,7 @@ import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
+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.comm.RecordTypes;
@@ -41,10 +40,14 @@ import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.ToastUtils;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
public class DanaRHistoryActivity extends NoSplashActivity {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
+ private CompositeDisposable disposable = new CompositeDisposable();
static Profile profile = null;
@@ -81,13 +84,26 @@ public class DanaRHistoryActivity 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 -> {
+ if (L.isEnabled(L.PUMP))
+ log.debug("EventDanaRSyncStatus: " + event.getMessage());
+ statusView.setText(event.getMessage());
+ }, FabricPrivacy::logException)
+ );
}
@Override
protected void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
+ disposable.clear();
}
@Override
@@ -316,21 +332,4 @@ public class DanaRHistoryActivity extends NoSplashActivity {
historyList = new ArrayList<>();
runOnUiThread(() -> recyclerView.swapAdapter(new RecyclerViewAdapter(historyList), false));
}
-
- @Subscribe
- public void onStatusEvent(final EventDanaRSyncStatus s) {
- if (L.isEnabled(L.PUMP))
- log.debug("EventDanaRSyncStatus: " + s.message);
- runOnUiThread(
- () -> statusView.setText(s.message));
- }
-
- @Subscribe
- public void onStatusEvent(final EventPumpStatusChanged s) {
- runOnUiThread(
- () -> statusView.setText(s.textStatus())
- );
- }
-
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java
index a15c8d2883..dcb182a0d6 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRNSHistorySync.java
@@ -14,6 +14,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus;
@@ -28,13 +29,13 @@ public class DanaRNSHistorySync {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
private List historyRecords;
- public final static int SYNC_BOLUS = 0b00000001;
- public final static int SYNC_ERROR = 0b00000010;
- public final static int SYNC_REFILL = 0b00000100;
- public final static int SYNC_GLUCOSE = 0b00001000;
- public final static int SYNC_CARBO = 0b00010000;
- public final static int SYNC_ALARM = 0b00100000;
- public final static int SYNC_BASALHOURS = 0b01000000;
+ private final static int SYNC_BOLUS = 0b00000001;
+ private final static int SYNC_ERROR = 0b00000010;
+ private final static int SYNC_REFILL = 0b00000100;
+ private final static int SYNC_GLUCOSE = 0b00001000;
+ private final static int SYNC_CARBO = 0b00010000;
+ private final static int SYNC_ALARM = 0b00100000;
+ private final static int SYNC_BASALHOURS = 0b01000000;
public final static int SYNC_ALL = 0b11111111;
public final static String DANARSIGNATURE = "DANARMESSAGE";
@@ -52,13 +53,13 @@ public class DanaRNSHistorySync {
long uploaded = 0;
if (L.isEnabled(L.PUMP))
log.debug("Database contains " + records + " records");
- EventDanaRSyncStatus ev = new EventDanaRSyncStatus();
+ EventDanaRSyncStatus ev = new EventDanaRSyncStatus("");
for (DanaRHistoryRecord record : historyRecords) {
processing++;
if (record._id != null) continue;
//log.debug(record.bytes);
JSONObject nsrec = new JSONObject();
- ev.message = MainApp.gs(R.string.uploading) + " " + processing + "/" + records + " "; // TODO: translations
+ ev.setMessage(MainApp.gs(R.string.uploading) + " " + processing + "/" + records + " "); // TODO: translations
switch (record.recordCode) {
case RecordTypes.RECORD_TYPE_BOLUS:
if ((what & SYNC_BOLUS) == 0) break;
@@ -73,7 +74,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_sbolus);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_sbolus));
break;
case "E":
if (record.recordDuration > 0) {
@@ -92,7 +93,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_ebolus);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_ebolus));
} else {
if (L.isEnabled(L.PUMP))
log.debug("NOT Syncing extended bolus record " + record.recordValue + "U " + DateUtil.toISOString(record.recordDate) + " zero duration");
@@ -110,7 +111,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_dsbolus);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_dsbolus));
break;
case "DE":
if (L.isEnabled(L.PUMP))
@@ -127,7 +128,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_debolus);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_debolus));
break;
default:
log.error("Unknown bolus record");
@@ -145,7 +146,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_error);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_error));
break;
case RecordTypes.RECORD_TYPE_REFILL:
if ((what & SYNC_REFILL) == 0) break;
@@ -158,7 +159,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_refill);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_refill));
break;
case RecordTypes.RECORD_TYPE_BASALHOUR:
if ((what & SYNC_BASALHOURS) == 0) break;
@@ -172,7 +173,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_basalhour);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_basalhour));
break;
case RecordTypes.RECORD_TYPE_TB:
//log.debug("Ignoring TB record " + record.bytes + " " + DateUtil.toISOString(record.recordDate));
@@ -189,7 +190,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_glucose);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_glucose));
break;
case RecordTypes.RECORD_TYPE_CARBO:
if ((what & SYNC_CARBO) == 0) break;
@@ -202,7 +203,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_carbohydrate);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_carbohydrate));
break;
case RecordTypes.RECORD_TYPE_ALARM:
if ((what & SYNC_ALARM) == 0) break;
@@ -215,7 +216,7 @@ public class DanaRNSHistorySync {
nsrec.put("enteredBy", "openaps://" + MainApp.gs(R.string.app_name));
NSUpload.uploadCareportalEntryToNS(nsrec);
uploaded++;
- ev.message += MainApp.gs(R.string.danar_alarm);
+ ev.setMessage(ev.getMessage() + MainApp.gs(R.string.danar_alarm));
break;
case RecordTypes.RECORD_TYPE_SUSPEND: // TODO: this too
case RecordTypes.RECORD_TYPE_DAILY:
@@ -226,10 +227,10 @@ public class DanaRNSHistorySync {
log.error("Unknown record type");
break;
}
- MainApp.bus().post(ev);
+ RxBus.INSTANCE.send(ev);
}
- ev.message = String.format(MainApp.gs(R.string.danar_totaluploaded), uploaded);
- MainApp.bus().post(ev);
+ ev.setMessage(String.format(MainApp.gs(R.string.danar_totaluploaded), uploaded));
+ RxBus.INSTANCE.send(ev);
} catch (JSONException e) {
log.error("Unhandled exception", e);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java
index d5b4fd3158..f1181bb7cb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java
@@ -1,14 +1,11 @@
package info.nightscout.androidaps.plugins.pump.danaR.activities;
-import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Switch;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -21,12 +18,16 @@ import info.nightscout.androidaps.activities.NoSplashActivity;
import info.nightscout.androidaps.events.EventInitializationChanged;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.NumberPicker;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by Rumen Georgiev on 5/31/2018.
@@ -34,6 +35,7 @@ import info.nightscout.androidaps.utils.NumberPicker;
public class DanaRUserOptionsActivity extends NoSplashActivity {
private static Logger log = LoggerFactory.getLogger(L.PUMP);
+ private CompositeDisposable disposable = new CompositeDisposable();
Switch timeFormat;
Switch buttonScroll;
@@ -49,20 +51,24 @@ public class DanaRUserOptionsActivity extends NoSplashActivity {
NumberPicker lowReservoir;
Button saveToPumpButton;
// This is for Dana pumps only
- boolean isRS = MainApp.getSpecificPlugin(DanaRSPlugin.class) != null && MainApp.getSpecificPlugin(DanaRSPlugin.class).isEnabled(PluginType.PUMP);
- boolean isDanaR = MainApp.getSpecificPlugin(DanaRPlugin.class) != null && MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PUMP);
- boolean isDanaRv2 = MainApp.getSpecificPlugin(DanaRv2Plugin.class) != null && MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PUMP);
+ boolean isRS = DanaRSPlugin.getPlugin().isEnabled(PluginType.PUMP);
+ boolean isDanaR = DanaRPlugin.getPlugin().isEnabled(PluginType.PUMP);
+ boolean isDanaRv2 = DanaRv2Plugin.getPlugin().isEnabled(PluginType.PUMP);
@Override
- protected void onResume() {
+ protected synchronized void onResume() {
super.onResume();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventInitializationChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> setData(), FabricPrivacy::logException)
+ );
}
@Override
- protected void onPause() {
+ protected synchronized void onPause() {
+ disposable.clear();
super.onPause();
- MainApp.bus().unregister(this);
}
@Override
@@ -144,11 +150,6 @@ public class DanaRUserOptionsActivity extends NoSplashActivity {
lowReservoir.setValue((double) pump.lowReservoirRate);
}
- @Subscribe
- public void onEventInitializationChanged(EventInitializationChanged ignored) {
- runOnUiThread(this::setData);
- }
-
public void onSaveClick() {
if (!isRS && !isDanaR && !isDanaRv2) {
//exit if pump is not DanaRS, Dana!, or DanaR with upgraded firmware
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java
index 6fb1993237..362b72c929 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.java
@@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.treatments.Treatment;
@@ -37,15 +38,15 @@ public class MsgBolusProgress extends MessageBase {
lastReceive = System.currentTimeMillis();
Double done = (amount * 100 - progress) / 100d;
t.insulin = done;
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), done);
- bolusingEvent.t = t;
- bolusingEvent.percent = Math.min((int) (done / amount * 100), 100);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), done));
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(Math.min((int) (done / amount * 100), 100));
if (L.isEnabled(L.PUMPCOMM)) {
log.debug("Bolus remaining: " + progress + " delivered: " + done);
}
- MainApp.bus().post(bolusingEvent);
+ RxBus.INSTANCE.send(bolusingEvent);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java
index 39531b8b10..2ea50297fb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStop.java
@@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.treatments.Treatment;
@@ -35,15 +36,15 @@ public class MsgBolusStop extends MessageBase {
public void handleMessage(byte[] bytes) {
if (L.isEnabled(L.PUMPCOMM))
log.debug("Messsage received");
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
stopped = true;
if (!forced) {
t.insulin = amount;
- bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_delivered);
- bolusingEvent.percent = 100;
+ bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_delivered));
+ bolusingEvent.setPercent(100);
} else {
- bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_stoped);
+ bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_stoped));
}
- MainApp.bus().post(bolusingEvent);
+ RxBus.INSTANCE.send(bolusingEvent);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.java
index d40f8f0cd6..317fe9db81 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.java
@@ -32,7 +32,7 @@ public class MsgCheckValue extends MessageBase {
pump.protocol = intFromBuff(bytes, 1, 1);
pump.productCode = intFromBuff(bytes, 2, 1);
if (pump.model != DanaRPump.EXPORT_MODEL) {
- MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
+ DanaRPlugin.getPlugin().disconnect("Wrong Model");
log.debug("Wrong model selected");
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java
index f697894778..a6fdaa8d0d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgError.java
@@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
@@ -44,10 +45,10 @@ public class MsgError extends MessageBase {
}
if (errorCode < 8) { // bolus delivering stopped
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
MsgBolusStop.stopped = true;
- bolusingEvent.status = errorString;
- MainApp.bus().post(bolusingEvent);
+ bolusingEvent.setStatus(errorString);
+ RxBus.INSTANCE.send(bolusingEvent);
failed=true;
}
if (L.isEnabled(L.PUMPCOMM))
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java
index 7de2489c91..955d7fc090 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.java
@@ -6,6 +6,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.utils.DateUtil;
@@ -33,8 +34,6 @@ public class MsgHistoryAll extends MessageBase {
byte paramByte8 = (byte) intFromBuff(bytes, 7, 1);
double value = (double) intFromBuff(bytes, 8, 2);
- EventDanaRSyncStatus ev = new EventDanaRSyncStatus();
-
DanaRHistoryRecord danaRHistoryRecord = new DanaRHistoryRecord();
danaRHistoryRecord.recordCode = recordCode;
@@ -145,11 +144,6 @@ public class MsgHistoryAll extends MessageBase {
}
MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord);
-
- ev.message = DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate);
- ev.message += " " + messageType;
- MainApp.bus().post(ev);
-
- return;
+ RxBus.INSTANCE.send(new EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java
index 1ba35a3614..974e63fe80 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java
@@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
@@ -31,23 +31,23 @@ public class MsgInitConnStatusTime extends MessageBase {
if (bytes.length - 10 > 7) {
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(notification));
- MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
+ DanaRPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to Korean DanaR");
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true);
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, true);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, false);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setFragmentVisible(PluginType.PUMP, false);
+ DanaRKoreanPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
+ DanaRKoreanPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, true);
+ DanaRPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, false);
+ DanaRPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, false);
DanaRPump.reset(); // mark not initialized
//If profile coming from pump, switch it as well
- if (MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PROFILE)) {
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PROFILE, false);
- (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class)).setPluginEnabled(PluginType.PROFILE, true);
+ if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
+ (DanaRPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, false);
+ (DanaRKoreanPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, true);
}
ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaDriver");
- MainApp.bus().post(new EventRefreshGui());
+ RxBus.INSTANCE.send(new EventRebuildTabs());
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection
failed = false;
return;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java
deleted file mode 100644
index 5fc0bd740f..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.danaR.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 20.07.2016.
- */
-public class EventDanaRSyncStatus extends Event {
- public String message;
-
- public EventDanaRSyncStatus() {
- }
-
- }
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt
new file mode 100644
index 0000000000..59ad7e2d83
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/events/EventDanaRSyncStatus.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.danaR.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventDanaRSyncStatus(var message: String) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java
index 9e3c1ff3ca..839debe9be 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java
@@ -23,6 +23,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStop;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgHistoryAlarm;
@@ -105,7 +106,7 @@ public abstract class AbstractDanaRExecutionService extends Service {
if (mSerialIOThread != null) {
mSerialIOThread.disconnect("BT disconnection broadcast");
}
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
}
}
}
@@ -135,7 +136,7 @@ public abstract class AbstractDanaRExecutionService extends Service {
public void finishHandshaking() {
mHandshakeInProgress = false;
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED, 0));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED, 0));
}
public void disconnect(String from) {
@@ -243,7 +244,7 @@ public abstract class AbstractDanaRExecutionService extends Service {
long timeToWholeMinute = (60000 - time % 60000);
if (timeToWholeMinute > 59800 || timeToWholeMinute < 3000)
break;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000))));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000))));
SystemClock.sleep(Math.min(timeToWholeMinute, 100));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java
index f623f292aa..dba3b4ca77 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java
@@ -5,8 +5,6 @@ import android.content.IntentFilter;
import android.os.Binder;
import android.os.SystemClock;
-import com.squareup.otto.Subscribe;
-
import java.io.IOException;
import java.util.Date;
@@ -67,15 +65,50 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class DanaRExecutionService extends AbstractDanaRExecutionService {
+ private CompositeDisposable disposable = new CompositeDisposable();
public DanaRExecutionService() {
mBinder = new LocalBinder();
- registerBus();
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("EventPreferenceChange");
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.PUMP))
+ log.debug("EventAppExit received");
+
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("Application exit");
+ MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
+ }
+
+ @Override
+ public void onDestroy() {
+ disposable.clear();
+ super.onDestroy();
}
public class LocalBinder extends Binder {
@@ -84,21 +117,6 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
}
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange pch) {
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("EventPreferenceChange");
- }
-
public void connect() {
if (mConnectionInProgress)
return;
@@ -127,7 +145,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableR.INSTANCE);
mHandshakeInProgress = true;
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0));
}
mConnectionInProgress = false;
@@ -137,7 +155,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
public void getPumpStatus() {
DanaRPump danaRPump = DanaRPump.getInstance();
try {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@@ -153,11 +171,11 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
long now = System.currentTimeMillis();
danaRPump.lastConnection = now;
@@ -165,15 +183,15 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
Profile profile = ProfileFunctions.getInstance().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingBasal());
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
- MainApp.bus().post(new EventProfileNeedsUpdate());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
}
}
if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingMeal());
@@ -185,7 +203,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll());
mSerialIOThread.sendMessage(new MsgSettingUserOptions());
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
if (danaRPump.pumpTime == 0) {
// initial handshake was not successfull
@@ -193,7 +211,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
danaRPump.lastConnection = 0;
danaRPump.lastSettingsRead = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
}
long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
@@ -210,7 +228,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
if (L.isEnabled(L.PUMP))
@@ -231,41 +249,41 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolus(double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -313,9 +331,9 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
}
SystemClock.sleep(300);
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = t;
- bolusingEvent.percent = 99;
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(99);
mBolusingTreatment = null;
@@ -339,8 +357,8 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
- bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000);
- MainApp.bus().post(bolusingEvent);
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000));
+ RxBus.INSTANCE.send(bolusingEvent);
SystemClock.sleep(1000);
}
@@ -365,7 +383,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
try {
o.wait();
} catch (InterruptedException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
} else {
@@ -395,7 +413,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
public boolean updateBasalsInPump(final Profile profile) {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet);
@@ -403,23 +421,10 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(msgActivate);
danaRPump.lastSettingsRead = 0; // force read full settings
getPumpStatus();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.PUMP))
- log.debug("EventAppExit received");
-
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("Application exit");
-
- MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
-
- stopSelf();
- }
-
public PumpEnactResult setUserOptions() {
if (!isConnected())
return new PumpEnactResult().success(false);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java
index 64eccf05f1..2645e25ade 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java
@@ -5,10 +5,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
-import androidx.fragment.app.FragmentActivity;
-import androidx.appcompat.app.AlertDialog;
-
-import com.squareup.otto.Subscribe;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -22,7 +18,7 @@ import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType;
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.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
@@ -30,13 +26,17 @@ import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgBolusStart;
import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 05.08.2016.
*/
public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
+ private CompositeDisposable disposable = new CompositeDisposable();
private static DanaRKoreanPlugin plugin = null;
@@ -58,7 +58,27 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, DanaRKoreanExecutionService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (isEnabled(PluginType.PUMP)) {
+ boolean previousValue = useExtendedBoluses;
+ useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false);
+
+ if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
+ sExecutionService.extendedBolusStop();
+ }
+ }
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ }, FabricPrivacy::logException)
+ );
super.onStart();
}
@@ -67,7 +87,7 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
Context context = MainApp.instance().getApplicationContext();
context.unbindService(mConnection);
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
@@ -87,24 +107,6 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin {
}
};
- @SuppressWarnings("UnusedParameters")
- @Subscribe
- public void onStatusEvent(final EventAppExit e) {
- MainApp.instance().getApplicationContext().unbindService(mConnection);
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange s) {
- if (isEnabled(PluginType.PUMP)) {
- boolean previousValue = useExtendedBoluses;
- useExtendedBoluses = SP.getBoolean(R.string.key_danar_useextended, false);
-
- if (useExtendedBoluses != previousValue && TreatmentsPlugin.getPlugin().isInHistoryExtendedBoluslInProgress()) {
- sExecutionService.extendedBolusStop();
- }
- }
- }
-
// Plugin base interface
@Override
public String getName() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java
index 020bc3f3b5..8a642a89f8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.java
@@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
@@ -35,21 +35,21 @@ public class MsgInitConnStatusTime_k extends MessageBase {
RxBus.INSTANCE.send(new EventNewNotification(notification));
DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to export DanaR");
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, false);
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, false);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, true);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setFragmentVisible(PluginType.PUMP, true);
+ DanaRKoreanPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, false);
+ DanaRKoreanPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, false);
+ DanaRPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
+ DanaRPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, true);
DanaRPump.reset(); // mark not initialized
//If profile coming from pump, switch it as well
- if (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).isEnabled(PluginType.PROFILE)) {
- (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class)).setPluginEnabled(PluginType.PROFILE, false);
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PROFILE, true);
+ if (DanaRKoreanPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
+ (DanaRKoreanPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, false);
+ (DanaRPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, true);
}
ConfigBuilderPlugin.getPlugin().storeSettings("ChangingKoreanDanaDriver");
- MainApp.bus().post(new EventRefreshGui());
+ RxBus.INSTANCE.send(new EventRebuildTabs());
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection
return;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java
index 6a10ffd7f6..bb1f226730 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java
@@ -5,8 +5,6 @@ import android.content.IntentFilter;
import android.os.Binder;
import android.os.SystemClock;
-import com.squareup.otto.Subscribe;
-
import java.io.IOException;
import java.util.Date;
@@ -59,51 +57,58 @@ import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MsgStatusBasic_k
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
+ private CompositeDisposable disposable = new CompositeDisposable();
public DanaRKoreanExecutionService() {
mBinder = new LocalBinder();
- registerBus();
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
}
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("EventPreferenceChange");
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.PUMP))
+ log.debug("EventAppExit received");
+
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("Application exit");
+ MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
+ }
+
+ @Override
+ public void onDestroy() {
+ disposable.clear();
+ super.onDestroy();
+ }
+
public class LocalBinder extends Binder {
public DanaRKoreanExecutionService getServiceInstance() {
return DanaRKoreanExecutionService.this;
}
}
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
- }
-
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.PUMP))
- log.debug("EventAppExit received");
-
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("Application exit");
-
- MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
-
- stopSelf();
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange pch) {
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("EventPreferenceChange");
- }
-
public void connect() {
if (mConnectionInProgress)
return;
@@ -132,7 +137,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
}
mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableRkorean.INSTANCE);
mHandshakeInProgress = true;
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0));
}
mConnectionInProgress = false;
@@ -142,7 +147,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public void getPumpStatus() {
DanaRPump danaRPump = DanaRPump.getInstance();
try {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
//MsgStatus_k statusMsg = new MsgStatus_k();
MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k();
MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal();
@@ -158,11 +163,11 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
//mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
long now = System.currentTimeMillis();
danaRPump.lastConnection = now;
@@ -170,15 +175,15 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
Profile profile = ProfileFunctions.getInstance().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingBasal());
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
- MainApp.bus().post(new EventProfileNeedsUpdate());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
}
}
if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingMeal());
mSerialIOThread.sendMessage(new MsgSettingBasal_k());
@@ -186,7 +191,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(new MsgSettingMaxValues());
mSerialIOThread.sendMessage(new MsgSettingGlucose());
mSerialIOThread.sendMessage(new MsgSettingProfileRatios());
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
if (danaRPump.pumpTime == 0) {
// initial handshake was not successfull
@@ -194,7 +199,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
danaRPump.lastConnection = 0;
danaRPump.lastSettingsRead = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
}
long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
@@ -213,7 +218,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
}
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
if (L.isEnabled(L.PUMP))
@@ -234,41 +239,41 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolus(double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended());
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -336,13 +341,13 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService {
public boolean updateBasalsInPump(final Profile profile) {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile);
MsgSetSingleBasalProfile msgSet = new MsgSetSingleBasalProfile(basal);
mSerialIOThread.sendMessage(msgSet);
danaRPump.lastSettingsRead = 0; // force read full settings
getPumpStatus();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java
index ef44cad527..55be88996b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java
@@ -5,12 +5,12 @@ import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
+import android.preference.Preference;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
-import com.squareup.otto.Subscribe;
-
+import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -40,7 +40,6 @@ import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.common.ManufacturerType;
-import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction;
import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType;
@@ -48,6 +47,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNo
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin;
+import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
@@ -59,9 +59,12 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 03.09.2017.
@@ -69,6 +72,8 @@ import info.nightscout.androidaps.utils.T;
public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface, ProfileInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP);
+ private CompositeDisposable disposable = new CompositeDisposable();
+
private static DanaRSPlugin plugin = null;
public static DanaRSPlugin getPlugin() {
@@ -107,14 +112,35 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
}
+ @Override
+ public void updatePreferenceSummary(@NotNull Preference pref) {
+ super.updatePreferenceSummary(pref);
+
+ if (pref.getKey().equals(MainApp.gs(R.string.key_danars_name)))
+ pref.setSummary(SP.getString(R.string.key_danars_name, ""));
+ }
+
@Override
protected void onStart() {
Context context = MainApp.instance().getApplicationContext();
Intent intent = new Intent(context, DanaRSService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- MainApp.bus().register(this);
- onStatusEvent(new EventDanaRSDeviceChange()); // load device name
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventDanaRSDeviceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ loadAddress();
+ }, FabricPrivacy::logException)
+ );
+ loadAddress(); // load device name
super.onStart();
}
@@ -123,7 +149,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
Context context = MainApp.instance().getApplicationContext();
context.unbindService(mConnection);
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
@@ -148,14 +174,7 @@ public class DanaRSPlugin extends PluginBase implements PumpInterface, DanaRInte
}
};
- @SuppressWarnings("UnusedParameters")
- @Subscribe
- public void onStatusEvent(final EventAppExit e) {
- MainApp.instance().getApplicationContext().unbindService(mConnection);
- }
-
- @Subscribe
- public void onStatusEvent(final EventDanaRSDeviceChange e) {
+ private void loadAddress() {
mDeviceAddress = SP.getString(R.string.key_danars_address, "");
mDeviceName = SP.getString(R.string.key_danars_name, "");
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java
index 7262153d5c..42e910f291 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java
@@ -17,9 +17,9 @@ import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange;
import info.nightscout.androidaps.utils.SP;
@@ -156,7 +156,7 @@ public class BLEScanActivity extends NoSplashAppCompatActivity {
SP.putString(R.string.key_danars_address, item.device.getAddress());
SP.putString(R.string.key_danars_name, mName.getText().toString());
item.device.createBond();
- MainApp.bus().post(new EventDanaRSDeviceChange());
+ RxBus.INSTANCE.send(new EventDanaRSDeviceChange());
finish();
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java
index 544b0c862e..afb5e86387 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingProgressDialog.java
@@ -5,7 +5,6 @@ import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
-import androidx.fragment.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -13,14 +12,19 @@ import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.DialogFragment;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class PairingProgressDialog extends DialogFragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
TextView statusView;
ProgressBar progressBar;
@@ -101,7 +105,11 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic
@Override
public void onResume() {
super.onResume();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventDanaRSPairingSuccess.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> pairingEnded = true, FabricPrivacy::logException)
+ );
running = true;
if (pairingEnded) dismiss();
}
@@ -117,15 +125,10 @@ public class PairingProgressDialog extends DialogFragment implements View.OnClic
@Override
public void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
+ disposable.clear();
running = false;
}
- @Subscribe
- public void onStatusEvent(final EventDanaRSPairingSuccess ev) {
- pairingEnded = true;
- }
-
public void setHelperActivity(PairingHelperActivity activity) {
this.helperActivity = activity;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet.java
index 3d59b34e16..55a2e0c51e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet.java
@@ -4,11 +4,15 @@ import android.annotation.TargetApi;
import android.os.Build;
import com.cozmo.danar.util.BleCommandUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.Date;
public class DanaRS_Packet {
+ private static final Logger log = LoggerFactory.getLogger(DanaRS_Packet.class);
+
protected static final int TYPE_START = 0;
protected static final int OPCODE_START = 1;
protected static final int DATA_START = 2;
@@ -73,7 +77,7 @@ public class DanaRS_Packet {
return ret;
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
return null;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java
index 6723e5a0a2..fde34c58e0 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.java
@@ -17,6 +17,7 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
@@ -223,7 +224,7 @@ public class DanaRS_Packet_APS_History_Events extends DanaRS_Packet {
if (datetime > lastEventTimeLoaded)
lastEventTimeLoaded = datetime;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
}
@Override
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java
index 5e3fe3fbcd..7cb0a11f9b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_Stop.java
@@ -9,6 +9,7 @@ import info.nightscout.androidaps.R;
import com.cozmo.danar.util.BleCommandUtil;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
@@ -47,16 +48,16 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_Stop extends DanaRS_Packet {
}
}
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
stopped = true;
if (!forced) {
t.insulin = amount;
- bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_delivered);
- bolusingEvent.percent = 100;
+ bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_delivered));
+ bolusingEvent.setPercent(100);
} else {
- bolusingEvent.status = MainApp.gs(R.string.overview_bolusprogress_stoped);
+ bolusingEvent.setStatus(MainApp.gs(R.string.overview_bolusprogress_stoped));
}
- MainApp.bus().post(bolusingEvent);
+ RxBus.INSTANCE.send(bolusingEvent);
}
@Override
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java
index ceaf49908b..07893346d7 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.java
@@ -10,6 +10,7 @@ import java.util.GregorianCalendar;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DanaRHistoryRecord;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes;
import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus;
import info.nightscout.androidaps.utils.DateUtil;
@@ -109,7 +110,6 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet {
log.debug("History packet: " + recordCode + " Date: " + datetimewihtsec.toLocaleString() + " Code: " + historyCode + " Value: " + value);
- EventDanaRSyncStatus ev = new EventDanaRSyncStatus();
DanaRHistoryRecord danaRHistoryRecord = new DanaRHistoryRecord();
danaRHistoryRecord.setBytes(data);
@@ -224,9 +224,7 @@ public abstract class DanaRS_Packet_History_ extends DanaRS_Packet {
MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord);
- ev.message = DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate);
- ev.message += " " + messageType;
- MainApp.bus().post(ev);
+ RxBus.INSTANCE.send(new EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java
index 3c916dc399..00b6483fbb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Complete.java
@@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.treatments.Treatment;
@@ -39,12 +40,12 @@ public class DanaRS_Packet_Notify_Delivery_Complete extends DanaRS_Packet {
if (t != null) {
t.insulin = deliveredInsulin;
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin);
- bolusingEvent.t = t;
- bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin));
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(Math.min((int) (deliveredInsulin / amount * 100), 100));
done = true;
- MainApp.bus().post(bolusingEvent);
+ RxBus.INSTANCE.send(bolusingEvent);
}
if (L.isEnabled(L.PUMPCOMM))
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java
index 290e9743ef..1d650cb779 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_Display.java
@@ -8,6 +8,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
import info.nightscout.androidaps.plugins.treatments.Treatment;
@@ -40,12 +41,12 @@ public class DanaRS_Packet_Notify_Delivery_Rate_Display extends DanaRS_Packet {
if (t != null) {
lastReceive = System.currentTimeMillis();
t.insulin = deliveredInsulin;
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin);
- bolusingEvent.t = t;
- bolusingEvent.percent = Math.min((int) (deliveredInsulin / amount * 100), 100);
- failed = bolusingEvent.percent < 100? true: false;
- MainApp.bus().post(bolusingEvent);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), deliveredInsulin));
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(Math.min((int) (deliveredInsulin / amount * 100), 100));
+ failed = bolusingEvent.getPercent() < 100? true: false;
+ RxBus.INSTANCE.send(bolusingEvent);
}
if (L.isEnabled(L.PUMPCOMM))
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java
deleted file mode 100644
index 224f939ad7..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.danaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 05.09.2017.
- */
-
-public class EventDanaRSDeviceChange extends Event {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt
new file mode 100644
index 0000000000..8b87d59ec1
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSDeviceChange.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.danaRS.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventDanaRSDeviceChange : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java
deleted file mode 100644
index e0c401a27f..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPacket.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.danaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet;
-
-/**
- * Created by mike on 01.09.2017.
- */
-
-public class EventDanaRSPacket extends Event{
- public EventDanaRSPacket(DanaRS_Packet data) {
- this.data = data;
- }
-
- public DanaRS_Packet data;
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java
deleted file mode 100644
index e332e9e0b2..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.danaRS.events;
-
-import info.nightscout.androidaps.events.Event;
-
-/**
- * Created by mike on 01.09.2017.
- */
-
-public class EventDanaRSPairingSuccess extends Event{
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt
new file mode 100644
index 0000000000..6e0379a4d3
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/events/EventDanaRSPairingSuccess.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.danaRS.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventDanaRSPairingSuccess : Event()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java
index 3ce5c49a1e..253b861811 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java
@@ -35,7 +35,6 @@ import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin;
import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable;
import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet;
-import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPacket;
import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess;
import info.nightscout.androidaps.utils.SP;
@@ -339,7 +338,7 @@ public class BLEComm {
close();
isConnected = false;
isConnecting = false;
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected
}
@@ -452,7 +451,7 @@ public class BLEComm {
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumperror)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumperror)));
NSUpload.uploadError(MainApp.gs(R.string.pumperror));
Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(n));
@@ -460,13 +459,13 @@ public class BLEComm {
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.pumpbusy)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumpbusy)));
} else {
// ERROR in response, wrong serial number
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer));
mSendQueue.clear();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED, MainApp.gs(R.string.connectionerror)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.connectionerror)));
SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName);
Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT);
RxBus.INSTANCE.send(new EventNewNotification(n));
@@ -496,7 +495,7 @@ public class BLEComm {
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer));
// Paring is successfull, sending time info
- MainApp.bus().post(new EventDanaRSPairingSuccess());
+ RxBus.INSTANCE.send(new EventDanaRSPairingSuccess());
SendTimeInfo();
byte[] pairingKey = {inputBuffer[2], inputBuffer[3]};
// store pairing key to preferences
@@ -515,7 +514,7 @@ public class BLEComm {
if (L.isEnabled(L.PUMPBTCOMM))
log.debug("Pump user password: " + Integer.toHexString(pass));
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTED));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED));
isConnected = true;
isConnecting = false;
if (L.isEnabled(L.PUMPBTCOMM))
@@ -546,14 +545,13 @@ public class BLEComm {
// notify to sendMessage
message.notify();
}
- MainApp.bus().post(new EventDanaRSPacket(message));
} else {
log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer));
}
break;
}
} catch (Exception e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
startSignatureFound = false;
packetIsValid = false;
@@ -637,7 +635,7 @@ public class BLEComm {
message.wait(5000);
} catch (InterruptedException e) {
log.error("sendMessage InterruptedException", e);
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java
index 4c46f80de7..2850f08c8d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java
@@ -6,8 +6,6 @@ import android.os.Binder;
import android.os.IBinder;
import android.os.SystemClock;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -27,6 +25,7 @@ import info.nightscout.androidaps.logging.L;
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.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
@@ -80,12 +79,15 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.DateUtil;
-import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class DanaRSService extends Service {
private Logger log = LoggerFactory.getLogger(L.PUMPCOMM);
+ private CompositeDisposable disposable = new CompositeDisposable();
private BLEComm bleComm = BLEComm.getInstance(this);
@@ -97,12 +99,25 @@ public class DanaRSService extends Service {
private long lastApproachingDailyLimit = 0;
public DanaRSService() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
+ }
+
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.PUMP)) log.debug("EventAppExit received");
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
+ }
+
+ @Override
+ public void onDestroy() {
+ disposable.clear();
+ super.onDestroy();
}
public boolean isConnected() {
@@ -132,14 +147,14 @@ public class DanaRSService extends Service {
public void getPumpStatus() {
DanaRPump danaRPump = DanaRPump.getInstance();
try {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information());
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus, bolusStep, maxBolus
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
danaRPump.lastConnection = System.currentTimeMillis();
@@ -147,14 +162,14 @@ public class DanaRSService extends Service {
Profile profile = ProfileFunctions.getInstance().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate()); // basal profile, basalStep, maxBasal
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
- MainApp.bus().post(new EventProfileNeedsUpdate());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
}
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time());
long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
@@ -163,7 +178,7 @@ public class DanaRSService extends Service {
// deinitialize pump
danaRPump.lastConnection = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
}
if (L.isEnabled(L.PUMPCOMM))
@@ -183,7 +198,7 @@ public class DanaRSService extends Service {
//deinitialize pump
danaRPump.lastConnection = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
} else {
waitForWholeMinute(); // Dana can set only whole minute
@@ -198,7 +213,7 @@ public class DanaRSService extends Service {
long now = System.currentTimeMillis();
if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information()); // serial no
bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check()); // firmware
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number());
@@ -212,8 +227,8 @@ public class DanaRSService extends Service {
loadEvents();
- MainApp.bus().post(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventDanaRNewStatus());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
if (L.isEnabled(L.PUMPCOMM))
@@ -234,7 +249,7 @@ public class DanaRSService extends Service {
public PumpEnactResult loadEvents() {
- if (!MainApp.getSpecificPlugin(DanaRSPlugin.class).isInitialized()) {
+ if (!DanaRSPlugin.getPlugin().isInitialized()) {
PumpEnactResult result = new PumpEnactResult().success(false);
result.comment = "pump not initialized";
return result;
@@ -250,7 +265,7 @@ public class DanaRSService extends Service {
} else {
msg = new DanaRS_Packet_APS_History_Events(lastHistoryFetched);
if (L.isEnabled(L.PUMPCOMM))
- log.debug("Loading event history from: " +DateUtil.dateAndTimeFullString(lastHistoryFetched));
+ log.debug("Loading event history from: " + DateUtil.dateAndTimeFullString(lastHistoryFetched));
}
bleComm.sendMessage(msg);
while (!msg.done && bleComm.isConnected()) {
@@ -278,7 +293,7 @@ public class DanaRSService extends Service {
if (!isConnected()) return false;
if (BolusProgressDialog.stopPressed) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus)));
bolusingTreatment = t;
final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0);
DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(insulin, preferencesSpeed);
@@ -314,9 +329,9 @@ public class DanaRSService extends Service {
}
}
- final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = t;
- bolusingEvent.percent = 99;
+ final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(99);
bolusingTreatment = null;
int speed = 12;
@@ -335,8 +350,8 @@ public class DanaRSService extends Service {
long expectedEnd = bolusStart + bolusDurationInMSec + 2000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
- bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000);
- MainApp.bus().post(bolusingEvent);
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000));
+ RxBus.INSTANCE.send(bolusingEvent);
SystemClock.sleep(1000);
}
// do not call loadEvents() directly, reconnection may be needed
@@ -344,10 +359,10 @@ public class DanaRSService extends Service {
@Override
public void run() {
// reread bolus status
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information()); // last bolus
- bolusingEvent.percent = 100;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting)));
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting)));
}
});
return !start.failed;
@@ -372,30 +387,30 @@ public class DanaRSService extends Service {
public boolean tempBasal(Integer percent, int durationInHours) {
if (!isConnected()) return false;
if (DanaRPump.getInstance().isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(percent, durationInHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean highTempBasal(Integer percent) {
if (DanaRPump.getInstance().isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(percent));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -406,52 +421,52 @@ public class DanaRSService extends Service {
}
if (DanaRPump.getInstance().isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(percent, durationInMinutes == 15, durationInMinutes == 30));
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal());
bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolus(Double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(insulin, durationInHalfHours));
SystemClock.sleep(200);
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel());
bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean updateBasalsInPump(Profile profile) {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile);
DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(0, basal);
bleComm.sendMessage(msgSet);
@@ -459,7 +474,7 @@ public class DanaRSService extends Service {
bleComm.sendMessage(msgActivate);
DanaRPump.getInstance().lastSettingsRead = 0; // force read full settings
getPumpStatus();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -529,21 +544,13 @@ public class DanaRSService extends Service {
return START_STICKY;
}
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.PUMP))
- log.debug("EventAppExit received");
-
- stopSelf();
- }
-
void waitForWholeMinute() {
while (true) {
long time = DateUtil.now();
long timeToWholeMinute = (60000 - time % 60000);
if (timeToWholeMinute > 59800 || timeToWholeMinute < 300)
break;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000))));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000))));
SystemClock.sleep(Math.min(timeToWholeMinute, 100));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java
index 94e6929d21..3437d37656 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java
@@ -6,8 +6,6 @@ import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
-import com.squareup.otto.Subscribe;
-
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.DetailedBolusInfo;
@@ -17,6 +15,7 @@ import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin;
@@ -26,14 +25,18 @@ import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2Execution
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.Round;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 05.08.2016.
*/
public class DanaRv2Plugin extends AbstractDanaRPlugin {
+ private CompositeDisposable disposable = new CompositeDisposable();
private static DanaRv2Plugin plugin = null;
@@ -56,7 +59,13 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
Intent intent = new Intent(context, DanaRv2ExecutionService.class);
context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ MainApp.instance().getApplicationContext().unbindService(mConnection);
+ }, FabricPrivacy::logException)
+ );
super.onStart();
}
@@ -65,7 +74,7 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
Context context = MainApp.instance().getApplicationContext();
context.unbindService(mConnection);
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
@@ -85,12 +94,6 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin {
}
};
- @SuppressWarnings("UnusedParameters")
- @Subscribe
- public void onStatusEvent(final EventAppExit e) {
- MainApp.instance().getApplicationContext().unbindService(mConnection);
- }
-
// Plugin base interface
@Override
public String getName() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java
index f5341f033c..3070c52b64 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2.java
@@ -5,7 +5,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.events.EventRefreshGui;
+import info.nightscout.androidaps.events.EventRebuildTabs;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
@@ -45,23 +45,23 @@ public class MsgCheckValue_v2 extends MessageBase {
pump.lastConnection = 0;
Notification notification = new Notification(Notification.WRONG_DRIVER, MainApp.gs(R.string.pumpdrivercorrected), Notification.NORMAL);
RxBus.INSTANCE.send(new EventNewNotification(notification));
- MainApp.getSpecificPlugin(DanaRPlugin.class).disconnect("Wrong Model");
+ DanaRPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to Korean DanaR");
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setPluginEnabled(PluginType.PUMP, true);
- MainApp.getSpecificPlugin(DanaRKoreanPlugin.class).setFragmentVisible(PluginType.PUMP, true);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setPluginEnabled(PluginType.PUMP, false);
- MainApp.getSpecificPlugin(DanaRPlugin.class).setFragmentVisible(PluginType.PUMP, false);
+ DanaRKoreanPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, true);
+ DanaRKoreanPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, true);
+ DanaRPlugin.getPlugin().setPluginEnabled(PluginType.PUMP, false);
+ DanaRPlugin.getPlugin().setFragmentVisible(PluginType.PUMP, false);
DanaRPump.reset(); // mark not initialized
//If profile coming from pump, switch it as well
- if (MainApp.getSpecificPlugin(DanaRPlugin.class).isEnabled(PluginType.PROFILE)) {
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PROFILE, false);
- (MainApp.getSpecificPlugin(DanaRKoreanPlugin.class)).setPluginEnabled(PluginType.PROFILE, true);
+ if (DanaRPlugin.getPlugin().isEnabled(PluginType.PROFILE)) {
+ (DanaRPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, false);
+ (DanaRKoreanPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, true);
}
ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaRv2Driver");
- MainApp.bus().post(new EventRefreshGui());
+ RxBus.INSTANCE.send(new EventRebuildTabs());
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection
return;
}
@@ -72,19 +72,19 @@ public class MsgCheckValue_v2 extends MessageBase {
RxBus.INSTANCE.send(new EventNewNotification(notification));
DanaRKoreanPlugin.getPlugin().disconnect("Wrong Model");
log.error("Wrong model selected. Switching to non APS DanaR");
- (MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setPluginEnabled(PluginType.PUMP, false);
- (MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setFragmentVisible(PluginType.PUMP, false);
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PUMP, true);
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setFragmentVisible(PluginType.PUMP, true);
+ (DanaRv2Plugin.getPlugin()).setPluginEnabled(PluginType.PUMP, false);
+ (DanaRv2Plugin.getPlugin()).setFragmentVisible(PluginType.PUMP, false);
+ (DanaRPlugin.getPlugin()).setPluginEnabled(PluginType.PUMP, true);
+ (DanaRPlugin.getPlugin()).setFragmentVisible(PluginType.PUMP, true);
//If profile coming from pump, switch it as well
- if (MainApp.getSpecificPlugin(DanaRv2Plugin.class).isEnabled(PluginType.PROFILE)) {
- (MainApp.getSpecificPlugin(DanaRv2Plugin.class)).setPluginEnabled(PluginType.PROFILE, false);
- (MainApp.getSpecificPlugin(DanaRPlugin.class)).setPluginEnabled(PluginType.PROFILE, true);
+ if (DanaRv2Plugin.getPlugin().isEnabled(PluginType.PROFILE)) {
+ (DanaRv2Plugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, false);
+ (DanaRPlugin.getPlugin()).setPluginEnabled(PluginType.PROFILE, true);
}
ConfigBuilderPlugin.getPlugin().storeSettings("ChangingDanaRv2Driver");
- MainApp.bus().post(new EventRefreshGui());
+ RxBus.INSTANCE.send(new EventRebuildTabs());
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("PumpDriverChange", null); // force new connection
return;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java
index 43ec35702f..3ef43cad86 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.java
@@ -13,6 +13,7 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase;
@@ -199,6 +200,6 @@ public class MsgHistoryEvents_v2 extends MessageBase {
if (datetime > lastEventTimeLoaded)
lastEventTimeLoaded = datetime;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.processinghistory) + ": " + status));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java
index 2721ec7ff8..e528a67fae 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java
@@ -6,8 +6,6 @@ import android.content.IntentFilter;
import android.os.Binder;
import android.os.SystemClock;
-import com.squareup.otto.Subscribe;
-
import java.io.IOException;
import java.util.Date;
@@ -74,17 +72,20 @@ import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.queue.commands.Command;
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.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
+ private CompositeDisposable disposable = new CompositeDisposable();
private long lastHistoryFetched = 0;
public DanaRv2ExecutionService() {
mBinder = new LocalBinder();
- registerBus();
MainApp.instance().getApplicationContext().registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
}
@@ -94,32 +95,36 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
}
}
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
+ @Override
+ public void onCreate() {
+ super.onCreate();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("EventPreferenceChange");
+ }, FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.PUMP))
+ log.debug("EventAppExit received");
+
+ if (mSerialIOThread != null)
+ mSerialIOThread.disconnect("Application exit");
+ MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
}
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.PUMP))
- log.debug("EventAppExit received");
-
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("Application exit");
-
- MainApp.instance().getApplicationContext().unregisterReceiver(receiver);
-
- stopSelf();
- }
-
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange pch) {
- if (mSerialIOThread != null)
- mSerialIOThread.disconnect("EventPreferenceChange");
+ @Override
+ public void onDestroy() {
+ disposable.clear();
+ super.onDestroy();
}
public void connect() {
@@ -150,7 +155,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
}
mSerialIOThread = new SerialIOThread(mRfcommSocket, MessageHashTableRv2.INSTANCE);
mHandshakeInProgress = true;
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, 0));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, 0));
}
mConnectionInProgress = false;
@@ -160,7 +165,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
public void getPumpStatus() {
DanaRPump danaRPump = DanaRPump.getInstance();
try {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpstatus)));
MsgStatus statusMsg = new MsgStatus();
MsgStatusBasic statusBasicMsg = new MsgStatusBasic();
MsgStatusTempBasal_v2 tempStatusMsg = new MsgStatusTempBasal_v2();
@@ -174,12 +179,12 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
}
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
mSerialIOThread.sendMessage(statusMsg);
mSerialIOThread.sendMessage(statusBasicMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingtempbasalstatus)));
mSerialIOThread.sendMessage(tempStatusMsg);
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingextendedbolusstatus)));
mSerialIOThread.sendMessage(exStatusMsg);
danaRPump.lastConnection = System.currentTimeMillis();
@@ -187,14 +192,14 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
Profile profile = ProfileFunctions.getInstance().getProfile();
PumpInterface pump = ConfigBuilderPlugin.getPlugin().getActivePump();
if (profile != null && Math.abs(danaRPump.currentBasal - profile.getBasal()) >= pump.getPumpDescription().basalStep) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingBasal());
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
- MainApp.bus().post(new EventProfileNeedsUpdate());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
}
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumptime)));
mSerialIOThread.sendMessage(new MsgSettingPumpTime());
if (danaRPump.pumpTime == 0) {
// initial handshake was not successfull
@@ -202,7 +207,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
danaRPump.lastConnection = 0;
danaRPump.lastSettingsRead = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
}
long timeDiff = (danaRPump.pumpTime - System.currentTimeMillis()) / 1000L;
@@ -223,7 +228,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
//deinitialize pump
danaRPump.lastConnection = 0;
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
return;
} else {
waitForWholeMinute(); // Dana can set only whole minute
@@ -238,7 +243,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
long now = System.currentTimeMillis();
if (danaRPump.lastSettingsRead + 60 * 60 * 1000L < now || !pump.isInitialized()) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingpumpsettings)));
mSerialIOThread.sendMessage(new MsgSettingShippingInfo());
mSerialIOThread.sendMessage(new MsgSettingActiveProfile());
mSerialIOThread.sendMessage(new MsgSettingMeal());
@@ -256,7 +261,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
loadEvents();
RxBus.INSTANCE.send(new EventDanaRNewStatus());
- MainApp.bus().post(new EventInitializationChanged());
+ RxBus.INSTANCE.send(new EventInitializationChanged());
NSUpload.uploadDeviceStatus();
if (danaRPump.dailyTotalUnits > danaRPump.maxDailyTotalUnits * Constants.dailyLimitWarning) {
if (L.isEnabled(L.PUMP))
@@ -277,15 +282,15 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStart(percent, durationInHours));
mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -293,15 +298,15 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent));
mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -314,45 +319,45 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
if (danaRPump.isTempBasalInProgress) {
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
SystemClock.sleep(500);
}
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(percent, durationInMinutes == 15, durationInMinutes == 30));
mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean tempBasalStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingtempbasal)));
mSerialIOThread.sendMessage(new MsgSetTempBasalStop());
mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolus(double insulin, int durationInHalfHours) {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.settingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(insulin, (byte) (durationInHalfHours & 0xFF)));
mSerialIOThread.sendMessage(new MsgStatusBolusExtended_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
public boolean extendedBolusStop() {
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.stoppingextendedbolus)));
mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop());
mSerialIOThread.sendMessage(new MsgStatusBolusExtended_v2());
loadEvents();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
@@ -360,7 +365,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
if (!isConnected()) return false;
if (BolusProgressDialog.stopPressed) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.startingbolus)));
mBolusingTreatment = t;
final int preferencesSpeed = SP.getInt(R.string.key_danars_bolusspeed, 0);
MessageBase start;
@@ -398,9 +403,9 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
}
}
- final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = t;
- bolusingEvent.percent = 99;
+ final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(t);
+ bolusingEvent.setPercent(99);
mBolusingTreatment = null;
int speed = 12;
@@ -419,8 +424,8 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
long expectedEnd = bolusStart + bolusDurationInMSec + 2000;
while (System.currentTimeMillis() < expectedEnd) {
long waitTime = expectedEnd - System.currentTimeMillis();
- bolusingEvent.status = String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000);
- MainApp.bus().post(bolusingEvent);
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.waitingforestimatedbolusend), waitTime / 1000));
+ RxBus.INSTANCE.send(bolusingEvent);
SystemClock.sleep(1000);
}
// do not call loadEvents() directly, reconnection may be needed
@@ -428,10 +433,10 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
@Override
public void run() {
// load last bolus status
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.gettingbolusstatus)));
mSerialIOThread.sendMessage(new MsgStatus());
- bolusingEvent.percent = 100;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting)));
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.disconnecting)));
}
});
return !start.failed;
@@ -466,7 +471,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
public PumpEnactResult loadEvents() {
DanaRPump danaRPump = DanaRPump.getInstance();
- if (!MainApp.getSpecificPlugin(DanaRv2Plugin.class).isInitialized()) {
+ if (!DanaRv2Plugin.getPlugin().isInitialized()) {
PumpEnactResult result = new PumpEnactResult().success(false);
result.comment = "pump not initialized";
return result;
@@ -496,7 +501,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
public boolean updateBasalsInPump(final Profile profile) {
DanaRPump danaRPump = DanaRPump.getInstance();
if (!isConnected()) return false;
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.updatingbasalrates)));
double[] basal = DanaRPump.getInstance().buildDanaRProfileRecord(profile);
MsgSetBasalProfile msgSet = new MsgSetBasalProfile((byte) 0, basal);
mSerialIOThread.sendMessage(msgSet);
@@ -504,7 +509,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService {
mSerialIOThread.sendMessage(msgActivate);
danaRPump.lastSettingsRead = 0; // force read full settings
getPumpStatus();
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
return true;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java
deleted file mode 100644
index 89b001891c..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/EventLocalInsightUpdateGUI.java
+++ /dev/null
@@ -1,6 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.insight;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-public class EventLocalInsightUpdateGUI extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java
index b973424d71..3464a1803a 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java
@@ -3,8 +3,6 @@ package info.nightscout.androidaps.plugins.pump.insight;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
-import androidx.annotation.NonNull;
-import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -12,14 +10,16 @@ import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
+import androidx.fragment.app.Fragment;
import java.util.ArrayList;
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.TBROverNotificationBlock;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveBasalRate;
@@ -28,11 +28,16 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.ActiveTBR;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.CartridgeStatus;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose;
+import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class LocalInsightFragment extends SubscriberFragment implements View.OnClickListener {
+public class LocalInsightFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
private static final boolean ENABLE_OPERATING_MODE_BUTTON = false;
@@ -61,6 +66,23 @@ public class LocalInsightFragment extends SubscriberFragment implements View.OnC
return view;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventLocalInsightUpdateGUI.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
+ updateGUI();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
@Override
public synchronized void onDestroyView() {
super.onDestroyView();
@@ -121,12 +143,6 @@ public class LocalInsightFragment extends SubscriberFragment implements View.OnC
}
}
- @Subscribe
- public void onUpdateGUIEvent(EventLocalInsightUpdateGUI event) {
- updateGUI();
- }
-
- @Override
protected void updateGUI() {
if (!viewsCreated) return;
statusItemContainer.removeAllViews();
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java
index 087e9e8d7a..5104e70fe8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java
@@ -78,6 +78,7 @@ import info.nightscout.androidaps.plugins.pump.insight.app_layer.history.history
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.ActiveBRProfileBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfile1Block;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.BRProfileBlock;
+import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.FactoryMinBasalAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.FactoryMinBolusAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBasalAmountBlock;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.parameter_blocks.MaxBolusAmountBlock;
@@ -118,6 +119,7 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.InsightState;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.OperatingMode;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.PumpTime;
import info.nightscout.androidaps.plugins.pump.insight.descriptors.TotalDailyDose;
+import info.nightscout.androidaps.plugins.pump.insight.events.EventLocalInsightUpdateGUI;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightException;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException;
import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException;
@@ -147,8 +149,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
} else if (binder instanceof InsightAlertService.LocalBinder) {
alertService = ((InsightAlertService.LocalBinder) binder).getService();
}
- if (connectionService != null && alertService != null)
- MainApp.bus().post(new EventInitializationChanged());
+ if (connectionService != null && alertService != null) {
+ RxBus.INSTANCE.send(new EventInitializationChanged());
+ }
}
@Override
@@ -423,8 +426,8 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
}
lastUpdated = System.currentTimeMillis();
new Handler(Looper.getMainLooper()).post(() -> {
- MainApp.bus().post(new EventLocalInsightUpdateGUI());
- MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::fetchStatus"));
+ RxBus.INSTANCE.send(new EventLocalInsightUpdateGUI());
+ RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::fetchStatus"));
});
}
@@ -432,7 +435,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
maximumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBolusAmountBlock.class).getAmountLimitation();
maximumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, MaxBasalAmountBlock.class).getAmountLimitation();
minimumBolusAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBolusAmountBlock.class).getAmountLimitation();
- minimumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBolusAmountBlock.class).getAmountLimitation();
+ minimumBasalAmount = ParameterBlockUtil.readParameterBlock(connectionService, Service.CONFIGURATION, FactoryMinBasalAmountBlock.class).getAmountLimitation();
this.pumpDescription.basalMaximumRate = maximumBasalAmount;
this.pumpDescription.basalMinimumRate = minimumBasalAmount;
limitsFetched = true;
@@ -554,11 +557,11 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
result.enacted = true;
Treatment t = new Treatment();
t.isSMB = detailedBolusInfo.isSMB;
- final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.t = t;
- bolusingEvent.status = MainApp.gs(R.string.insight_delivered, 0d, insulin);
- bolusingEvent.percent = 0;
- MainApp.bus().post(bolusingEvent);
+ final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setT(t);
+ bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, 0d, insulin));
+ bolusingEvent.setPercent(0);
+ RxBus.INSTANCE.send(bolusingEvent);
int trials = 0;
InsightBolusID insightBolusID = new InsightBolusID();
insightBolusID.bolusID = bolusID;
@@ -585,18 +588,18 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
}
if (activeBolus != null) {
trials = -1;
- int percentBefore = bolusingEvent.percent;
- bolusingEvent.percent = (int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount()));
- bolusingEvent.status = MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount());
- if (percentBefore != bolusingEvent.percent)
- MainApp.bus().post(bolusingEvent);
+ int percentBefore = bolusingEvent.getPercent();
+ bolusingEvent.setPercent((int) (100D / activeBolus.getInitialAmount() * (activeBolus.getInitialAmount() - activeBolus.getRemainingAmount())));
+ bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, activeBolus.getInitialAmount() - activeBolus.getRemainingAmount(), activeBolus.getInitialAmount()));
+ if (percentBefore != bolusingEvent.getPercent())
+ RxBus.INSTANCE.send(bolusingEvent);
} else {
synchronized ($bolusLock) {
if (bolusCancelled || trials == -1 || trials++ >= 5) {
if (!bolusCancelled) {
- bolusingEvent.status = MainApp.gs(R.string.insight_delivered, insulin, insulin);
- bolusingEvent.percent = 100;
- MainApp.bus().post(bolusingEvent);
+ bolusingEvent.setStatus(MainApp.gs(R.string.insight_delivered, insulin, insulin));
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(bolusingEvent);
}
break;
}
@@ -1164,7 +1167,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
} catch (Exception e) {
log.error("Exception while reading history", e);
}
- new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::readHistory")));
+ new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::readHistory")));
}
private void processHistoryEvents(String serial, List historyEvents) {
@@ -1523,7 +1526,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
data.put("notes", note);
NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
@@ -1551,7 +1554,7 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
data.put("eventType", event);
NSUpload.uploadCareportalEntryToNS(data);
} catch (JSONException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
@@ -1599,9 +1602,9 @@ public class LocalInsightPlugin extends PluginBase implements PumpInterface, Con
activeTBR = null;
activeBoluses = null;
tbrOverNotificationBlock = null;
- new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventRefreshOverview("LocalInsightPlugin::onStateChanged")));
+ new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventRefreshOverview("LocalInsightPlugin::onStateChanged")));
}
- new Handler(Looper.getMainLooper()).post(() -> MainApp.bus().post(new EventLocalInsightUpdateGUI()));
+ new Handler(Looper.getMainLooper()).post(() -> RxBus.INSTANCE.send(new EventLocalInsightUpdateGUI()));
}
@Override
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/history/history_events/HistoryEvent.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/history/history_events/HistoryEvent.java
index 874c908ca5..f6b3dc588c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/history/history_events/HistoryEvent.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/history/history_events/HistoryEvent.java
@@ -3,8 +3,11 @@ package info.nightscout.androidaps.plugins.pump.insight.app_layer.history.histor
import info.nightscout.androidaps.plugins.pump.insight.ids.HistoryEventIDs;
import info.nightscout.androidaps.plugins.pump.insight.utils.BOCUtil;
import info.nightscout.androidaps.plugins.pump.insight.utils.ByteBuf;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class HistoryEvent implements Comparable {
+ private static final Logger log = LoggerFactory.getLogger(HistoryEvent.class);
private int eventYear;
private int eventMonth;
@@ -22,10 +25,8 @@ public class HistoryEvent implements Comparable {
else {
try {
event = eventClass.newInstance();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
+ } catch (IllegalAccessException | InstantiationException e) {
+ log.error("Unhandled exception", e);
}
}
event.parseHeader(byteBuf);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt
new file mode 100644
index 0000000000..d89515fe56
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/events/EventLocalInsightUpdateGUI.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.insight.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventLocalInsightUpdateGUI : EventUpdateGui()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt
index d60a639106..69e0e0bbe8 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt
@@ -8,7 +8,6 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
-import com.squareup.otto.Subscribe
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventExtendedBolusChange
@@ -104,7 +103,6 @@ class MedtronicFragment : Fragment() {
@Synchronized
override fun onResume() {
super.onResume()
- MainApp.bus().register(this)
loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
disposable += RxBus
.toObservable(EventRefreshButtonState::class.java)
@@ -122,6 +120,14 @@ class MedtronicFragment : Fragment() {
.toObservable(EventMedtronicPumpValuesChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventExtendedBolusChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventTempBasalChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
disposable += RxBus
.toObservable(EventMedtronicPumpConfigurationChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
@@ -131,6 +137,14 @@ class MedtronicFragment : Fragment() {
MedtronicUtil.getPumpStatus().verifyConfiguration()
updateGUI()
}, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventPumpStatusChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
+ disposable += RxBus
+ .toObservable(EventQueueChanged::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGUI() }, { FabricPrivacy.logException(it) })
updateGUI()
}
@@ -139,30 +153,9 @@ class MedtronicFragment : Fragment() {
override fun onPause() {
super.onPause()
disposable.clear()
- MainApp.bus().unregister(this)
loopHandler.removeCallbacks(refreshLoop)
}
- @Subscribe
- fun onStatusEvent(c: EventPumpStatusChanged) {
- activity?.runOnUiThread { updateGUI() }
- }
-
- @Subscribe
- fun onStatusEvent(s: EventTempBasalChange) {
- activity?.runOnUiThread { updateGUI() }
- }
-
- @Subscribe
- fun onStatusEvent(s: EventExtendedBolusChange) {
- activity?.runOnUiThread { updateGUI() }
- }
-
- @Subscribe
- fun onStatusEvent(s: EventQueueChanged) {
- activity?.runOnUiThread { updateGUI() }
- }
-
@Synchronized
private fun setDeviceStatus() {
val pumpStatus: MedtronicPumpStatus = MedtronicUtil.getPumpStatus()
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java
index cd5066d645..f0d10e0370 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java
@@ -48,6 +48,7 @@ import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperAc
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.pump.common.PumpPluginAbstract;
+import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState;
import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst;
@@ -372,7 +373,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
refreshAnyStatusThatNeedsToBeRefreshed();
}
- RxBus.INSTANCE.send(new EventMedtronicPumpValuesChanged());
+ RxBus.INSTANCE.send(new EventMedtronicPumpValuesChanged());
}
@@ -386,7 +387,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
RileyLinkServiceState rileyLinkServiceState = MedtronicUtil.getServiceState();
- if (rileyLinkServiceState==null) {
+ if (rileyLinkServiceState == null) {
LOG.error("RileyLink unreachable. RileyLinkServiceState is null.");
return false;
}
@@ -744,13 +745,13 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
ClockDTO clock = MedtronicUtil.getPumpTime();
- if (clock==null) { // retry
+ if (clock == null) { // retry
medtronicUIComm.executeCommand(MedtronicCommandType.GetRealTimeClock);
clock = MedtronicUtil.getPumpTime();
}
- if (clock==null)
+ if (clock == null)
return;
int timeDiff = Math.abs(clock.timeDifference);
@@ -866,6 +867,11 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}).start();
}
+ long now = System.currentTimeMillis();
+
+ detailedBolusInfo.date = now;
+ detailedBolusInfo.deliverAt = now; // not sure about that one
+
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, true);
// we subtract insulin, exact amount will be visible with next remainingInsulin update.
@@ -877,7 +883,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
// calculate time for bolus and set driver to busy for that time
int bolusTime = (int) (detailedBolusInfo.insulin * 42.0d);
- long time = System.currentTimeMillis() + (bolusTime * 1000);
+ long time = now + (bolusTime * 1000);
this.busyTimestamps.add(time);
setEnableCustomAction(MedtronicCustomActionType.ClearBolusBlock, true);
@@ -1065,10 +1071,10 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
@Override
public PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile,
boolean enforceNew) {
- if (percent==0) {
+ if (percent == 0) {
return setTempBasalAbsolute(0.0d, durationInMinutes, profile, enforceNew);
} else {
- double absoluteValue = profile.getBasal() * (percent /100.0d);
+ double absoluteValue = profile.getBasal() * (percent / 100.0d);
getMDTPumpStatus();
absoluteValue = pumpStatusLocal.pumpType.determineCorrectBasalSize(absoluteValue);
LOG.warn("setTempBasalPercent [MedtronicPumpPlugin] - You are trying to use setTempBasalPercent with percent other then 0% (%d). This will start setTempBasalAbsolute, with calculated value (%.3f). Result might not be 100% correct.", percent, absoluteValue);
@@ -1080,7 +1086,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
private void finishAction(String overviewKey) {
if (overviewKey != null)
- MainApp.bus().post(new EventRefreshOverview(overviewKey));
+ RxBus.INSTANCE.send(new EventRefreshOverview(overviewKey));
triggerUIChange();
@@ -1603,7 +1609,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter
}
private void refreshCustomActionsList() {
- MainApp.bus().post(new EventCustomActionsChanged());
+ RxBus.INSTANCE.send(new EventCustomActionsChanged());
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java
index 2562ac9376..e054539e8f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicCommunicationManager.java
@@ -788,7 +788,7 @@ public class MedtronicCommunicationManager extends RileyLinkCommunicationManager
return false;
}
- if (responseRaw.length == 1) {
+ if (responseRaw.length < 2) {
return false;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java
index 32ca320de2..71f387d176 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoder.java
@@ -412,25 +412,18 @@ public class MedtronicPumpHistoryDecoder extends MedtronicHistoryDecoder validEntries;
- // private Object validValues;
-
public PumpHistoryResult(PumpHistoryEntry searchEntry, Long targetDate) {
if (searchEntry != null) {
/*
@@ -109,9 +105,8 @@ public class PumpHistoryResult {
if (unprocessedEntry.isAfter(this.searchDate)) {
this.validEntries.add(unprocessedEntry);
} else {
- LOG.debug("PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]",
- DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry);
-
+// LOG.debug("PE. PumpHistoryResult. Not after.. Unprocessed Entry [year={},entry={}]",
+// DateTimeUtil.getYear(unprocessedEntry.atechDateTime), unprocessedEntry);
if (DateTimeUtil.getYear(unprocessedEntry.atechDateTime) > 2015)
olderEntries++;
}
@@ -131,14 +126,6 @@ public class PumpHistoryResult {
}
- private void clearOrPrepareList() {
- if (this.validEntries == null)
- this.validEntries = new ArrayList<>();
- else
- this.validEntries.clear();
- }
-
-
public String toString() {
return "PumpHistoryResult [unprocessed=" + (unprocessedEntries != null ? "" + unprocessedEntries.size() : "0") + //
", valid=" + (validEntries != null ? "" + validEntries.size() : "0") + //
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java
index 00cda7feca..2e23d2a955 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java
@@ -6,6 +6,8 @@ import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.LocalDateTime;
import org.joda.time.Minutes;
+import org.json.JSONException;
+import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -20,6 +22,7 @@ import java.util.Map;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo;
+import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.DbObjectBase;
import info.nightscout.androidaps.db.ExtendedBolus;
@@ -27,6 +30,7 @@ import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TDD;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage;
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil;
import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil;
@@ -45,7 +49,9 @@ import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpSta
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.treatments.Treatment;
+import info.nightscout.androidaps.plugins.treatments.TreatmentService;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
@@ -59,9 +65,9 @@ import info.nightscout.androidaps.utils.SP;
// all times that time changed (TZ, DST, etc.). Data needs to be returned in batches (time_changed batches, so that we can
// handle it. It would help to assign sort_ids to items (from oldest (1) to newest (x)
+// All things marked with "TODO: Fix db code" needs to be updated in new 2.5 database code
public class MedtronicHistoryData {
-
private static final Logger LOG = LoggerFactory.getLogger(L.PUMP);
private List allHistory = null;
@@ -71,20 +77,33 @@ public class MedtronicHistoryData {
private boolean isInit = false;
private Gson gson;
+ private Gson gsonCore;
private DatabaseHelper databaseHelper = MainApp.getDbHelper();
private ClockDTO pumpTime;
private long lastIdUsed = 0;
+ /**
+ * Double bolus debug. We seem to have small problem with double Boluses (or sometimes also missing boluses
+ * from history. This flag turns on debugging for that (default is off=false)... Debuging is pretty detailed,
+ * so log files will get bigger.
+ */
+ public static boolean doubleBolusDebug = false;
+
public MedtronicHistoryData() {
this.allHistory = new ArrayList<>();
this.gson = MedtronicUtil.gsonInstance;
+ this.gsonCore = MedtronicUtil.getGsonInstanceCore();
if (this.gson == null) {
this.gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}
+
+ if (this.gsonCore == null) {
+ this.gsonCore = new GsonBuilder().create();
+ }
}
@@ -311,6 +330,7 @@ public class MedtronicHistoryData {
pumpHistoryEntryType == PumpHistoryEntryType.BasalProfileStart || //
pumpHistoryEntryType == PumpHistoryEntryType.Bolus || //
pumpHistoryEntryType == PumpHistoryEntryType.Resume || //
+ pumpHistoryEntryType == PumpHistoryEntryType.BatteryChange || //
pumpHistoryEntryType == PumpHistoryEntryType.Prime);
if (isLogEnabled())
@@ -353,6 +373,7 @@ public class MedtronicHistoryData {
PumpHistoryEntryType.Resume, //
PumpHistoryEntryType.Rewind, //
PumpHistoryEntryType.NoDeliveryAlarm, //
+ PumpHistoryEntryType.BatteryChange, //
PumpHistoryEntryType.BasalProfileStart);
newAndAll2 = filterPumpSuspend(newAndAll2, 10);
@@ -382,6 +403,22 @@ public class MedtronicHistoryData {
*/
public void processNewHistoryData() {
+ // TODO: Fix db code
+ // Prime (for reseting autosense)
+ List primeRecords = getFilteredItems(PumpHistoryEntryType.Prime);
+
+ if (isLogEnabled())
+ LOG.debug("ProcessHistoryData: Prime [count={}, items={}]", primeRecords.size(), gson.toJson(primeRecords));
+
+ if (isCollectionNotEmpty(primeRecords)) {
+ try {
+ processPrime(primeRecords);
+ } catch (Exception ex) {
+ LOG.error("ProcessHistoryData: Error processing Prime entries: " + ex.getMessage(), ex);
+ throw ex;
+ }
+ }
+
// TDD
List tdds = getFilteredItems(PumpHistoryEntryType.EndResultTotals, getTDDType());
@@ -454,6 +491,49 @@ public class MedtronicHistoryData {
}
+ private void processPrime(List primeRecords) {
+
+ long maxAllowedTimeInPast = DateTimeUtil.getATDWithAddedMinutes(new GregorianCalendar(), -30);
+
+ long lastPrimeRecord = 0L;
+
+ for (PumpHistoryEntry primeRecord : primeRecords) {
+
+ if (primeRecord.atechDateTime > maxAllowedTimeInPast) {
+ if (lastPrimeRecord < primeRecord.atechDateTime) {
+ lastPrimeRecord = primeRecord.atechDateTime;
+ }
+ }
+ }
+
+ if (lastPrimeRecord != 0L) {
+ long lastPrimeFromAAPS = SP.getLong(MedtronicConst.Statistics.LastPrime, 0L);
+
+ if (lastPrimeRecord != lastPrimeFromAAPS) {
+ uploadCareportalEvent(DateTimeUtil.toMillisFromATD(lastPrimeRecord), CareportalEvent.SITECHANGE);
+
+ SP.putLong(MedtronicConst.Statistics.LastPrime, lastPrimeRecord);
+ }
+ }
+ }
+
+
+ private void uploadCareportalEvent(long date, String event) {
+ if (MainApp.getDbHelper().getCareportalEventFromTimestamp(date) != null)
+ return;
+ try {
+ JSONObject data = new JSONObject();
+ String enteredBy = SP.getString("careportal_enteredby", "");
+ if (!enteredBy.equals("")) data.put("enteredBy", enteredBy);
+ data.put("created_at", DateUtil.toISOString(date));
+ data.put("eventType", event);
+ NSUpload.uploadCareportalEntryToNS(data);
+ } catch (JSONException e) {
+ LOG.error("Unhandled exception", e);
+ }
+ }
+
+
private void processTDDs(List tddsIn) {
List tdds = filterTDDs(tddsIn);
@@ -517,23 +597,32 @@ public class MedtronicHistoryData {
long oldestTimestamp = getOldestTimestamp(entryList);
+ Gson gson = MedtronicUtil.getGsonInstance();
+
List extends DbObjectBase> entriesFromHistory = getDatabaseEntriesByLastTimestamp(oldestTimestamp, ProcessHistoryRecord.Bolus);
-// LOG.debug(processHistoryRecord.getDescription() + " List (before filter): {}, FromDb={}", gsonPretty.toJson(entryList),
-// gsonPretty.toJson(entriesFromHistory));
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: List (before filter): {}, FromDb={}", gson.toJson(entryList),
+ gsonCore.toJson(entriesFromHistory));
filterOutAlreadyAddedEntries(entryList, entriesFromHistory);
- if (entryList.isEmpty())
+ if (entryList.isEmpty()) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: EntryList was filtered out.");
return;
+ }
-// LOG.debug(processHistoryRecord.getDescription() + " List (after filter): {}, FromDb={}", gsonPretty.toJson(entryList),
-// gsonPretty.toJson(entriesFromHistory));
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: List (after filter): {}, FromDb={}", gson.toJson(entryList),
+ gsonCore.toJson(entriesFromHistory));
if (isCollectionEmpty(entriesFromHistory)) {
for (PumpHistoryEntry treatment : entryList) {
if (isLogEnabled())
LOG.debug("Add Bolus (no db entry): " + treatment);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: Add Bolus: FromDb=null, Treatment={}", treatment);
addBolus(treatment, null);
}
@@ -542,6 +631,8 @@ public class MedtronicHistoryData {
DbObjectBase treatmentDb = findDbEntry(treatment, entriesFromHistory);
if (isLogEnabled())
LOG.debug("Add Bolus {} - (entryFromDb={}) ", treatment, treatmentDb);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: Add Bolus: FromDb={}, Treatment={}", treatmentDb, treatment);
addBolus(treatment, (Treatment) treatmentDb);
}
@@ -681,12 +772,11 @@ public class MedtronicHistoryData {
/**
* findDbEntry - finds Db entries in database, while theoretically this should have same dateTime they
- * don't. Entry on pump is few seconds before treatment in AAPS, and on manual boluses on pump there
- * is no treatment at all. For now we look fro tratment that was from 0s - 1m59s within pump entry.
+ * don't. Entry on pump is few seconds before treatment in AAPS, and on manual boluses on pump there
+ * is no treatment at all. For now we look fro tratment that was from 0s - 1m59s within pump entry.
*
- * @param treatment Pump Entry
+ * @param treatment Pump Entry
* @param entriesFromHistory entries from history
- *
* @return DbObject from AAPS (if found)
*/
private DbObjectBase findDbEntry(PumpHistoryEntry treatment, List extends DbObjectBase> entriesFromHistory) {
@@ -695,9 +785,30 @@ public class MedtronicHistoryData {
//proposedTime += (this.pumpTime.timeDifference * 1000);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}", treatment, gson.toJson(entriesFromHistory));
+
if (entriesFromHistory.size() == 0) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb=null", treatment);
return null;
} else if (entriesFromHistory.size() == 1) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=SingleEntry", treatment, entriesFromHistory.get(0));
+
+ // TODO: Fix db code
+ // if difference is bigger than 2 minutes we discard entry
+ long maxMillisAllowed = DateTimeUtil.getMillisFromATDWithAddedMinutes(treatment.atechDateTime, 2);
+
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry maxMillisAllowed={}, AtechDateTime={} (add 2 minutes). ", maxMillisAllowed, treatment.atechDateTime);
+
+ if (entriesFromHistory.get(0).getDate() > maxMillisAllowed) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry entry filtered out, returning null. ");
+ return null;
+ }
+
return entriesFromHistory.get(0);
}
@@ -720,10 +831,10 @@ public class MedtronicHistoryData {
}
}
-// LOG.debug("Entries: (timeDiff=[min={},sec={}],count={},list={})", min, sec, outList.size(),
-// gsonPretty.toJson(outList));
-
if (outList.size() == 1) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry Treatment={}, FromDb={}. Type=EntrySelected, AtTimeMin={}, AtTimeSec={}", treatment, entriesFromHistory.get(0), min, sec);
+
return outList.get(0);
}
@@ -731,6 +842,9 @@ public class MedtronicHistoryData {
if (isLogEnabled())
LOG.error("Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
min, sec, outList.size(), gson.toJson(outList));
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: findDbEntry Error - Too many entries (with too small diff): (timeDiff=[min={},sec={}],count={},list={})",
+ min, sec, outList.size(), gson.toJson(outList));
}
}
}
@@ -754,6 +868,7 @@ public class MedtronicHistoryData {
return;
List removeTreatmentsFromHistory = new ArrayList<>();
+ List removeTreatmentsFromPH = new ArrayList<>();
for (DbObjectBase treatment : treatmentsFromHistory) {
@@ -771,11 +886,17 @@ public class MedtronicHistoryData {
if (selectedBolus != null) {
entryList.remove(selectedBolus);
+ removeTreatmentsFromPH.add(selectedBolus);
removeTreatmentsFromHistory.add(treatment);
}
}
}
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: filterOutAlreadyAddedEntries: PumpHistory={}, Treatments={}",
+ gson.toJson(removeTreatmentsFromPH),
+ gsonCore.toJson(removeTreatmentsFromHistory));
+
treatmentsFromHistory.removeAll(removeTreatmentsFromHistory);
}
@@ -785,6 +906,8 @@ public class MedtronicHistoryData {
BolusDTO bolusDTO = (BolusDTO) bolus.getDecodedData().get("Object");
if (treatment == null) {
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addBolus(tretament==null): Bolus={}", bolusDTO);
switch (bolusDTO.getBolusType()) {
case Normal: {
@@ -797,6 +920,9 @@ public class MedtronicHistoryData {
addCarbsFromEstimate(detailedBolusInfo, bolus);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addBolus(tretament==null): DetailedBolusInfo={}", detailedBolusInfo);
+
boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
bolus.setLinkedObject(detailedBolusInfo);
@@ -819,6 +945,9 @@ public class MedtronicHistoryData {
bolus.setLinkedObject(extendedBolus);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus={}", extendedBolus);
+
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
if (isLogEnabled())
@@ -831,26 +960,23 @@ public class MedtronicHistoryData {
} else {
- DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.INSTANCE.findDetailedBolusInfo(treatment.date, bolusDTO.getDeliveredAmount());
- if (detailedBolusInfo == null) {
- detailedBolusInfo = new DetailedBolusInfo();
- }
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addBolus(OldTreatment={}): Bolus={}", treatment, bolusDTO);
- detailedBolusInfo.date = treatment.date;
- detailedBolusInfo.source = Source.PUMP;
- detailedBolusInfo.pumpId = bolus.getPumpId();
- detailedBolusInfo.insulin = bolusDTO.getDeliveredAmount();
- detailedBolusInfo.carbs = treatment.carbs;
+ treatment.source = Source.PUMP;
+ treatment.pumpId = bolus.getPumpId();
+ treatment.insulin = bolusDTO.getDeliveredAmount();
- addCarbsFromEstimate(detailedBolusInfo, bolus);
+ TreatmentService.UpdateReturn updateReturn = TreatmentsPlugin.getPlugin().getService().createOrUpdateMedtronic(treatment, false);
- boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
-
- bolus.setLinkedObject(detailedBolusInfo);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addBolus(tretament!=null): NewTreatment={}, UpdateReturn={}", treatment, updateReturn);
if (isLogEnabled())
- LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", detailedBolusInfo.date,
- detailedBolusInfo.pumpId, detailedBolusInfo.insulin, newRecord);
+ LOG.debug("editBolus - [date={},pumpId={}, insulin={}, newRecord={}]", treatment.date,
+ treatment.pumpId, treatment.insulin, updateReturn.toString());
+
+ bolus.setLinkedObject(treatment);
}
}
@@ -862,6 +988,9 @@ public class MedtronicHistoryData {
BolusWizardDTO bolusWizard = (BolusWizardDTO) bolus.getDecodedData().get("Estimate");
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: addCarbsFromEstimate: Bolus={}, BolusWizardDTO={}", bolus, bolusWizard);
+
detailedBolusInfo.carbs = bolusWizard.carbs;
}
}
@@ -1210,24 +1339,26 @@ public class MedtronicHistoryData {
}
}
- //LocalDateTime oldestEntryTime = null;
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: getOldestTimestamp. Oldest entry found: time={}, object={}", dt, currentTreatment);
try {
GregorianCalendar oldestEntryTime = DateTimeUtil.toGregorianCalendar(dt);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime: {}", DateTimeUtil.toString(oldestEntryTime));
oldestEntryTime.add(Calendar.MINUTE, -2);
+ if (doubleBolusDebug)
+ LOG.debug("DoubleBolusDebug: getOldestTimestamp. oldestEntryTime (-2m): {}, timeInMillis={}", DateTimeUtil.toString(oldestEntryTime), oldestEntryTime.getTimeInMillis());
+
return oldestEntryTime.getTimeInMillis();
-// if (this.pumpTime.timeDifference < 0) {
-// oldestEntryTime = oldestEntryTime.plusSeconds(this.pumpTime.timeDifference);
-// }
} catch (Exception ex) {
- LOG.error("Problem decoding date from last record: {}" + currentTreatment);
+ LOG.error("Problem decoding date from last record: {}", currentTreatment);
return 8; // default return of 6 minutes
}
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BatteryStatusDTO.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BatteryStatusDTO.java
index c8bd2347d0..93b5eb10cb 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BatteryStatusDTO.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BatteryStatusDTO.java
@@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto;
import com.google.gson.annotations.Expose;
+import java.util.Locale;
+
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType;
/**
@@ -38,10 +40,11 @@ public class BatteryStatusDTO {
public String toString() {
- return String.format("BatteryStatusDTO [voltage=%.2f, alkaline=%d, lithium=%d]",
+ return String.format(Locale.ENGLISH, "BatteryStatusDTO [voltage=%.2f, alkaline=%d, lithium=%d, niZn={}]",
voltage == null ? 0.0f : voltage,
getCalculatedPercent(BatteryType.Alkaline),
- getCalculatedPercent(BatteryType.Lithium));
+ getCalculatedPercent(BatteryType.Lithium),
+ getCalculatedPercent(BatteryType.NiZn));
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/BatteryType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/BatteryType.java
index 0d228d43ec..5c7bf245a2 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/BatteryType.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/BatteryType.java
@@ -14,7 +14,9 @@ public enum BatteryType {
None(R.string.key_medtronic_pump_battery_no, 0, 0),
Alkaline(R.string.key_medtronic_pump_battery_alkaline, 1.20d, 1.47d), //
- Lithium(R.string.key_medtronic_pump_battery_lithium, 1.22d, 1.64d);
+ Lithium(R.string.key_medtronic_pump_battery_lithium, 1.22d, 1.64d), //
+ NiZn(R.string.key_medtronic_pump_battery_nizn, 1.40d, 1.70d) //
+ ;
private final String description;
public double lowVoltage;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java
index 9f148ac02e..2d1a3a871e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.java
@@ -19,7 +19,6 @@ import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.activities.NoSplashActivity;
import info.nightscout.androidaps.logging.L;
@@ -82,7 +81,6 @@ public class MedtronicHistoryActivity extends NoSplashActivity {
@Override
protected void onResume() {
super.onResume();
- MainApp.bus().register(this);
filterHistory(selectedGroup);
setHistoryTypeSpinner();
}
@@ -106,7 +104,6 @@ public class MedtronicHistoryActivity extends NoSplashActivity {
@Override
protected void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java
index 29387b0724..fc1208a340 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.java
@@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError;
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState;
+import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType;
import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType;
@@ -281,6 +282,12 @@ public class MedtronicPumpStatus extends PumpStatus {
MedtronicUtil.setBatteryType(this.batteryType);
}
+ String bolusDebugEnabled = SP.getString(MedtronicConst.Prefs.BolusDebugEnabled, null);
+
+ boolean bolusDebug = bolusDebugEnabled != null && bolusDebugEnabled.equals(MainApp.gs(R.string.common_on));
+
+ MedtronicHistoryData.doubleBolusDebug = bolusDebug;
+
reconfigureService();
return true;
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicConst.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicConst.java
index b5bd2f1f64..fef95087de 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicConst.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicConst.java
@@ -11,17 +11,6 @@ public class MedtronicConst {
static final String Prefix = "AAPS.Medtronic.";
public class Prefs {
-
-// public static final String PrefPrefix = "pref_medtronic_";
-// public static final String PumpSerial = PrefPrefix + "serial";
-// public static final String PumpType = PrefPrefix + "pump_type";
-// public static final String PumpFrequency = PrefPrefix + "frequency";
-// public static final String MaxBolus = PrefPrefix + "max_bolus";
-// public static final String MaxBasal = PrefPrefix + "max_basal";
-// public static final String BolusDelay = PrefPrefix + "bolus_delay";
-// public static final String Encoding = PrefPrefix + "encoding";
-// public static final String BatteryType = PrefPrefix + "battery_type";
-
public static final int PumpSerial = R.string.key_medtronic_serial;
public static final int PumpType = R.string.key_medtronic_pump_type;
public static final int PumpFrequency = R.string.key_medtronic_frequency;
@@ -30,6 +19,7 @@ public class MedtronicConst {
public static final int BolusDelay = R.string.key_medtronic_bolus_delay;
public static final int Encoding = R.string.key_medtronic_encoding;
public static final int BatteryType = R.string.key_medtronic_battery_type;
+ public static final int BolusDebugEnabled = R.string.key_medtronic_bolus_debug;
}
public class Statistics {
@@ -42,6 +32,7 @@ public class MedtronicConst {
public static final String StandardBoluses = StatsPrefix + "std_boluses_delivered";
public static final String SMBBoluses = StatsPrefix + "smb_boluses_delivered";
public static final String LastPumpHistoryEntry = StatsPrefix + "pump_history_entry";
+ public static final String LastPrime = StatsPrefix + "last_sent_prime";
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java
index 96bf0a5d44..2c7ee69c2f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.java
@@ -61,8 +61,7 @@ public class MedtronicUtil extends RileyLinkUtil {
private static int doneBit = 1 << 7;
private static ClockDTO pumpTime;
public static Gson gsonInstance = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
- public static Gson gsonInstancePretty = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
- .setPrettyPrinting().create();
+ public static Gson gsonInstanceCore = new GsonBuilder().create();
private static BatteryType batteryType = BatteryType.None;
@@ -70,8 +69,9 @@ public class MedtronicUtil extends RileyLinkUtil {
return gsonInstance;
}
- public static Gson getGsonInstancePretty() {
- return gsonInstancePretty;
+
+ public static Gson getGsonInstanceCore() {
+ return gsonInstanceCore;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java
deleted file mode 100644
index be9bf17c85..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java
+++ /dev/null
@@ -1,125 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.virtual;
-
-
-import android.app.Activity;
-import android.os.Bundle;
-import android.os.Handler;
-import androidx.annotation.Nullable;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.TextView;
-
-import com.squareup.otto.Subscribe;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.ExtendedBolus;
-import info.nightscout.androidaps.db.TemporaryBasal;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
-import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
-import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
-import info.nightscout.androidaps.utils.FabricPrivacy;
-
-
-public class VirtualPumpFragment extends SubscriberFragment {
- private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class);
-
- TextView basaBasalRateView;
- TextView tempBasalView;
- TextView extendedBolusView;
- TextView batteryView;
- TextView reservoirView;
- TextView pumpTypeView;
- TextView pumpSettingsView;
-
-
- private static Handler sLoopHandler = new Handler();
- private static Runnable sRefreshLoop = null;
-
- @Override
- public void onCreate(@Nullable Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (sRefreshLoop == null) {
- sRefreshLoop = new Runnable() {
- @Override
- public void run() {
- updateGUI();
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- }
- };
- sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L);
- }
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.virtualpump_fragment, container, false);
- basaBasalRateView = (TextView) view.findViewById(R.id.virtualpump_basabasalrate);
- tempBasalView = (TextView) view.findViewById(R.id.virtualpump_tempbasal);
- extendedBolusView = (TextView) view.findViewById(R.id.virtualpump_extendedbolus);
- batteryView = (TextView) view.findViewById(R.id.virtualpump_battery);
- reservoirView = (TextView) view.findViewById(R.id.virtualpump_reservoir);
- pumpTypeView = (TextView) view.findViewById(R.id.virtualpump_type);
- pumpSettingsView = (TextView) view.findViewById(R.id.virtualpump_type_def);
-
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
-
- return null;
- }
-
- @Subscribe
- public void onStatusEvent(final EventVirtualPumpUpdateGui ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null && basaBasalRateView != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- VirtualPumpPlugin virtualPump = VirtualPumpPlugin.getPlugin();
- basaBasalRateView.setText(virtualPump.getBaseBasalRate() + "U");
- TemporaryBasal activeTemp = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis());
- if (activeTemp != null) {
- tempBasalView.setText(activeTemp.toStringFull());
- } else {
- tempBasalView.setText("");
- }
- ExtendedBolus activeExtendedBolus = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis());
- if (activeExtendedBolus != null) {
- extendedBolusView.setText(activeExtendedBolus.toString());
- } else {
- extendedBolusView.setText("");
- }
- batteryView.setText(virtualPump.batteryPercent + "%");
- reservoirView.setText(virtualPump.reservoirInUnits + "U");
-
- virtualPump.refreshConfiguration();
-
- PumpType pumpType = virtualPump.getPumpType();
-
- pumpTypeView.setText(pumpType.getDescription());
-
- String template = MainApp.gs(R.string.virtualpump_pump_def);
-
-
- pumpSettingsView.setText(pumpType.getFullDescription(template, pumpType.hasExtendedBasals()));
-
- }
- });
- }
-
-
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt
new file mode 100644
index 0000000000..08402520c2
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt
@@ -0,0 +1,85 @@
+package info.nightscout.androidaps.plugins.pump.virtual
+
+import android.os.Bundle
+import android.os.Handler
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import androidx.fragment.app.Fragment
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.events.EventExtendedBolusChange
+import info.nightscout.androidaps.events.EventTempBasalChange
+import info.nightscout.androidaps.plugins.bus.RxBus
+import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
+import info.nightscout.androidaps.utils.FabricPrivacy
+import info.nightscout.androidaps.utils.T
+import io.reactivex.android.schedulers.AndroidSchedulers
+import io.reactivex.disposables.CompositeDisposable
+import kotlinx.android.synthetic.main.virtualpump_fragment.*
+import org.slf4j.LoggerFactory
+
+class VirtualPumpFragment : Fragment() {
+ private val disposable = CompositeDisposable()
+
+ private val loopHandler = Handler()
+ private lateinit var refreshLoop: Runnable
+
+ init {
+ refreshLoop = Runnable {
+ activity?.runOnUiThread { updateGui() }
+ loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
+ }
+ }
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
+ return inflater.inflate(R.layout.virtualpump_fragment, container, false)
+ }
+
+ @Synchronized
+ override fun onResume() {
+ super.onResume()
+ disposable.add(RxBus
+ .toObservable(EventVirtualPumpUpdateGui::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
+ )
+ disposable.add(RxBus
+ .toObservable(EventTempBasalChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
+ )
+ disposable.add(RxBus
+ .toObservable(EventExtendedBolusChange::class.java)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe({ updateGui() }, { FabricPrivacy.logException(it) })
+ )
+ loopHandler.postDelayed(refreshLoop, T.mins(1).msecs())
+ updateGui()
+ }
+
+ @Synchronized
+ override fun onPause() {
+ super.onPause()
+ disposable.clear()
+ loopHandler.removeCallbacks(refreshLoop)
+ }
+
+ @Synchronized
+ private fun updateGui() {
+ val virtualPump = VirtualPumpPlugin.getPlugin()
+ virtualpump_basabasalrate?.text = MainApp.gs(R.string.pump_basebasalrate, virtualPump.baseBasalRate)
+ virtualpump_tempbasal?.text = TreatmentsPlugin.getPlugin().getTempBasalFromHistory(System.currentTimeMillis())?.toStringFull()
+ ?: ""
+ virtualpump_extendedbolus?.text = TreatmentsPlugin.getPlugin().getExtendedBolusFromHistory(System.currentTimeMillis())?.toString() ?: ""
+ virtualpump_battery?.text = MainApp.gs(R.string.format_percent, virtualPump.batteryPercent)
+ virtualpump_reservoir?.text = MainApp.gs(R.string.formatinsulinunits, virtualPump.reservoirInUnits.toDouble())
+
+ virtualPump.refreshConfiguration()
+ val pumpType = virtualPump.pumpType
+
+ virtualpump_type?.text = pumpType.description
+ virtualpump_type_def?.text = pumpType.getFullDescription(MainApp.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals())
+ }
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java
index 514ee912ad..447367c510 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.java
@@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.pump.virtual;
import android.os.SystemClock;
-import com.squareup.otto.Subscribe;
-
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
@@ -41,8 +39,11 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType;
import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.InstanceId;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
@@ -50,6 +51,7 @@ import info.nightscout.androidaps.utils.SP;
*/
public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
private Logger log = LoggerFactory.getLogger(L.PUMP);
+ private CompositeDisposable disposable = new CompositeDisposable();
Integer batteryPercent = 50;
Integer reservoirInUnits = 50;
@@ -122,22 +124,23 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
@Override
protected void onStart() {
super.onStart();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPreferenceChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (event.isChanged(R.string.key_virtualpump_type))
+ refreshConfiguration();
+ }, FabricPrivacy::logException)
+ );
refreshConfiguration();
}
@Override
protected void onStop() {
- MainApp.bus().unregister(this);
+ disposable.clear();
super.onStop();
}
- @Subscribe
- public void onStatusEvent(final EventPreferenceChange s) {
- if (s.isChanged(R.string.key_virtualpump_type))
- refreshConfiguration();
- }
-
@Override
public boolean isFakingTempsByExtendedBoluses() {
return (Config.NSCLIENT) && fromNSAreCommingFakedExtendedBoluses;
@@ -268,21 +271,21 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
while (delivering < detailedBolusInfo.insulin) {
SystemClock.sleep(200);
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivering), delivering);
- bolusingEvent.percent = Math.min((int) (delivering / detailedBolusInfo.insulin * 100), 100);
- MainApp.bus().post(bolusingEvent);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivering), delivering));
+ bolusingEvent.setPercent(Math.min((int) (delivering / detailedBolusInfo.insulin * 100), 100));
+ RxBus.INSTANCE.send(bolusingEvent);
delivering += 0.1d;
}
SystemClock.sleep(200);
- EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.getInstance();
- bolusingEvent.status = String.format(MainApp.gs(R.string.bolusdelivered), detailedBolusInfo.insulin);
- bolusingEvent.percent = 100;
- MainApp.bus().post(bolusingEvent);
+ EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE;
+ bolusingEvent.setStatus(String.format(MainApp.gs(R.string.bolusdelivered), detailedBolusInfo.insulin));
+ bolusingEvent.setPercent(100);
+ RxBus.INSTANCE.send(bolusingEvent);
SystemClock.sleep(1000);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Delivering treatment insulin: " + detailedBolusInfo.insulin + "U carbs: " + detailedBolusInfo.carbs + "g " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false);
return result;
@@ -310,7 +313,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Setting temp basal absolute: " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
return result;
}
@@ -333,7 +336,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
TreatmentsPlugin.getPlugin().addToHistoryTempBasal(tempBasal);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Settings temp basal percent: " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
return result;
}
@@ -358,7 +361,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Setting extended bolus: " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
return result;
}
@@ -376,7 +379,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
//tempBasal = null;
if (L.isEnabled(L.PUMPCOMM))
log.debug("Canceling temp basal: " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
}
lastDataTime = System.currentTimeMillis();
return result;
@@ -396,7 +399,7 @@ public class VirtualPumpPlugin extends PluginBase implements PumpInterface {
result.comment = MainApp.gs(R.string.virtualpump_resultok);
if (L.isEnabled(L.PUMPCOMM))
log.debug("Canceling extended bolus: " + result);
- MainApp.bus().post(new EventVirtualPumpUpdateGui());
+ RxBus.INSTANCE.send(new EventVirtualPumpUpdateGui());
lastDataTime = System.currentTimeMillis();
return result;
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java
deleted file mode 100644
index 795134997a..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.java
+++ /dev/null
@@ -1,9 +0,0 @@
-package info.nightscout.androidaps.plugins.pump.virtual.events;
-
-import info.nightscout.androidaps.events.EventUpdateGui;
-
-/**
- * Created by mike on 05.08.2016.
- */
-public class EventVirtualPumpUpdateGui extends EventUpdateGui {
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt
new file mode 100644
index 0000000000..a0498aa14d
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/events/EventVirtualPumpUpdateGui.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.plugins.pump.virtual.events
+
+import info.nightscout.androidaps.events.EventUpdateGui
+
+class EventVirtualPumpUpdateGui : EventUpdateGui()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java
index 269ee2b3f5..6023d70d12 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.java
@@ -1,19 +1,18 @@
package info.nightscout.androidaps.plugins.source;
-import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
-import androidx.annotation.NonNull;
-import androidx.appcompat.app.AlertDialog;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
+import androidx.appcompat.app.AlertDialog;
+import androidx.fragment.app.Fragment;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
@@ -21,19 +20,22 @@ import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.BgReading;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by mike on 16.10.2017.
*/
-public class BGSourceFragment extends SubscriberFragment {
+public class BGSourceFragment extends Fragment {
+ private CompositeDisposable disposable = new CompositeDisposable();
RecyclerView recyclerView;
String units = Constants.MGDL;
@@ -66,19 +68,25 @@ public class BGSourceFragment extends SubscriberFragment {
return null;
}
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished unused) {
- updateGUI();
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
}
@Override
+ public synchronized void onPause() {
+ disposable.clear();
+ super.onPause();
+ }
+
protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- long now = System.currentTimeMillis();
- recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true);
- });
+ long now = System.currentTimeMillis();
+ recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getAllBgreadingsDataFromTime(now - MILLS_TO_THE_PAST, false)), true);
}
public class RecyclerViewAdapter extends RecyclerView.Adapter {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt
index 1cf438b14d..633f16cf10 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/SourceDexcomPlugin.kt
@@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.source
import android.content.Intent
import android.content.pm.PackageManager
-import android.os.Build
import androidx.core.content.ContextCompat
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
@@ -18,6 +17,7 @@ import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.SP
+import info.nightscout.androidaps.utils.T
import org.json.JSONObject
import org.slf4j.LoggerFactory
@@ -52,7 +52,7 @@ object SourceDexcomPlugin : PluginBase(PluginDescription()
}
fun findDexcomPackageName(): String? {
- val packageManager = MainApp.instance().packageManager;
+ val packageManager = MainApp.instance().packageManager
for (packageInfo in packageManager.getInstalledPackages(0)) {
if (PACKAGE_NAMES.contains(packageInfo.packageName)) return packageInfo.packageName
}
@@ -62,45 +62,56 @@ object SourceDexcomPlugin : PluginBase(PluginDescription()
override fun handleNewData(intent: Intent) {
if (!isEnabled(PluginType.BGSOURCE)) return
try {
+ val sensorType = intent.getStringExtra("sensorType") ?: ""
val glucoseValues = intent.getBundleExtra("glucoseValues")
for (i in 0 until glucoseValues.size()) {
- val glucoseValue = glucoseValues.getBundle(i.toString())
- val bgReading = BgReading()
- bgReading.value = glucoseValue!!.getInt("glucoseValue").toDouble()
- bgReading.direction = glucoseValue.getString("trendArrow")
- bgReading.date = glucoseValue.getLong("timestamp") * 1000
- bgReading.raw = 0.0
- if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom")) {
- if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
- NSUpload.uploadBg(bgReading, "AndroidAPS-DexcomG6")
- }
- if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
- NSUpload.sendToXdrip(bgReading)
+ glucoseValues.getBundle(i.toString())?.let { glucoseValue ->
+ val bgReading = BgReading()
+ bgReading.value = glucoseValue.getInt("glucoseValue").toDouble()
+ bgReading.direction = glucoseValue.getString("trendArrow")
+ bgReading.date = glucoseValue.getLong("timestamp") * 1000
+ bgReading.raw = 0.0
+ if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) {
+ if (SP.getBoolean(R.string.key_dexcomg5_nsupload, false)) {
+ NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType")
+ }
+ if (SP.getBoolean(R.string.key_dexcomg5_xdripupload, false)) {
+ NSUpload.sendToXdrip(bgReading)
+ }
}
}
}
val meters = intent.getBundleExtra("meters")
for (i in 0 until meters.size()) {
val meter = meters.getBundle(i.toString())
- val timestamp = meter!!.getLong("timestamp") * 1000
- if (MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp) != null) continue
- val jsonObject = JSONObject()
- jsonObject.put("enteredBy", "AndroidAPS-Dexcom")
- jsonObject.put("created_at", DateUtil.toISOString(timestamp))
- jsonObject.put("eventType", CareportalEvent.BGCHECK)
- jsonObject.put("glucoseType", "Finger")
- jsonObject.put("glucose", meter.getInt("meterValue"))
- jsonObject.put("units", Constants.MGDL)
- NSUpload.uploadCareportalEntryToNS(jsonObject)
+ meter?.let {
+ val timestamp = it.getLong("timestamp") * 1000
+ val now = DateUtil.now()
+ if (timestamp > now - T.months(1).msecs() && timestamp < now)
+ if (MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp) == null) {
+ val jsonObject = JSONObject()
+ jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
+ jsonObject.put("created_at", DateUtil.toISOString(timestamp))
+ jsonObject.put("eventType", CareportalEvent.BGCHECK)
+ jsonObject.put("glucoseType", "Finger")
+ jsonObject.put("glucose", meter.getInt("meterValue"))
+ jsonObject.put("units", Constants.MGDL)
+ NSUpload.uploadCareportalEntryToNS(jsonObject)
+ }
+ }
}
if (SP.getBoolean(R.string.key_dexcom_lognssensorchange, false) && intent.hasExtra("sensorInsertionTime")) {
- val sensorInsertionTime = intent.extras!!.getLong("sensorInsertionTime") * 1000
- if (MainApp.getDbHelper().getCareportalEventFromTimestamp(sensorInsertionTime) == null) {
- val jsonObject = JSONObject()
- jsonObject.put("enteredBy", "AndroidAPS-Dexcom")
- jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
- jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
- NSUpload.uploadCareportalEntryToNS(jsonObject)
+ intent.extras?.let {
+ val sensorInsertionTime = it.getLong("sensorInsertionTime") * 1000
+ val now = DateUtil.now()
+ if (sensorInsertionTime > now - T.months(1).msecs() && sensorInsertionTime < now)
+ if (MainApp.getDbHelper().getCareportalEventFromTimestamp(sensorInsertionTime) == null) {
+ val jsonObject = JSONObject()
+ jsonObject.put("enteredBy", "AndroidAPS-Dexcom$sensorType")
+ jsonObject.put("created_at", DateUtil.toISOString(sensorInsertionTime))
+ jsonObject.put("eventType", CareportalEvent.SENSORCHANGE)
+ NSUpload.uploadCareportalEntryToNS(jsonObject)
+ }
}
}
} catch (e: Exception) {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java
index 309191fdc0..1331c8eedf 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java
@@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.treatments;
import android.content.Intent;
import android.os.IBinder;
+
import androidx.annotation.Nullable;
import com.j256.ormlite.android.apptools.OpenHelperManager;
@@ -13,7 +14,6 @@ import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
-import com.squareup.otto.Subscribe;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
@@ -29,7 +29,6 @@ import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.db.DatabaseHelper;
import info.nightscout.androidaps.db.ICallback;
import info.nightscout.androidaps.db.Source;
@@ -38,9 +37,14 @@ import info.nightscout.androidaps.events.EventNsTreatment;
import info.nightscout.androidaps.events.EventReloadTreatmentData;
import info.nightscout.androidaps.events.EventTreatmentChange;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData;
+import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.JsonHelper;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
@@ -49,6 +53,7 @@ import info.nightscout.androidaps.utils.JsonHelper;
public class TreatmentService extends OrmLiteBaseService {
private static Logger log = LoggerFactory.getLogger(L.DATATREATMENTS);
+ private CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture> scheduledTreatmentEventPost = null;
@@ -56,7 +61,20 @@ public class TreatmentService extends OrmLiteBaseService {
public TreatmentService() {
onCreate();
dbInitialize();
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNsTreatment.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ int mode = event.getMode();
+ JSONObject payload = event.getPayload();
+
+ if (mode == EventNsTreatment.Companion.getADD() || mode == EventNsTreatment.Companion.getUPDATE()) {
+ this.createTreatmentFromJsonIfNotExists(payload);
+ } else { // EventNsTreatment.REMOVE
+ this.deleteNS(payload);
+ }
+ }, FabricPrivacy::logException)
+ );
}
/**
@@ -87,19 +105,6 @@ public class TreatmentService extends OrmLiteBaseService {
return null;
}
- @Subscribe
- @SuppressWarnings("unused")
- public void handleNsEvent(EventNsTreatment event) {
- int mode = event.getMode();
- JSONObject payload = event.getPayload();
-
- if (mode == EventNsTreatment.ADD || mode == EventNsTreatment.UPDATE) {
- this.createTreatmentFromJsonIfNotExists(payload);
- } else { // EventNsTreatment.REMOVE
- this.deleteNS(payload);
- }
- }
-
@Override
public void onCreate() {
super.onCreate();
@@ -128,7 +133,7 @@ public class TreatmentService extends OrmLiteBaseService {
try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` ADD COLUMN boluscalc STRING;");
} catch (SQLException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
} else {
if (L.isEnabled(L.DATATREATMENTS))
@@ -142,7 +147,7 @@ public class TreatmentService extends OrmLiteBaseService {
try {
getDao().executeRaw("ALTER TABLE `" + Treatment.TABLE_TREATMENTS + "` DROP COLUMN boluscalc STRING;");
} catch (SQLException e) {
- e.printStackTrace();
+ log.error("Unhandled exception", e);
}
}
}
@@ -180,11 +185,11 @@ public class TreatmentService extends OrmLiteBaseService {
public void run() {
if (L.isEnabled(L.DATATREATMENTS))
log.debug("Firing EventReloadTreatmentData");
- MainApp.bus().post(event);
+ RxBus.INSTANCE.send(event);
if (DatabaseHelper.earliestDataChange != null) {
if (L.isEnabled(L.DATATREATMENTS))
log.debug("Firing EventNewHistoryData");
- MainApp.bus().post(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
+ RxBus.INSTANCE.send(new EventNewHistoryData(DatabaseHelper.earliestDataChange));
}
DatabaseHelper.earliestDataChange = null;
callback.setPost(null);
@@ -192,7 +197,7 @@ public class TreatmentService extends OrmLiteBaseService {
}
// prepare task for execution in 1 sec
// cancel waiting task to prevent sending multiple posts
- ScheduledFuture> scheduledFuture = callback.getPost();
+ ScheduledFuture> scheduledFuture = callback.getPost();
if (scheduledFuture != null)
scheduledFuture.cancel(false);
Runnable task = new PostRunnable();
@@ -245,12 +250,15 @@ public class TreatmentService extends OrmLiteBaseService {
try {
Treatment treatment = Treatment.createFromJson(json);
if (treatment != null) {
+
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: createTreatmentFromJsonIfNotExists:: medtronicPump={}", MedtronicUtil.isMedtronicPump());
+
if (!MedtronicUtil.isMedtronicPump())
createOrUpdate(treatment);
else
- createOrUpdateMedtronic(treatment, false);
- }
- else
+ createOrUpdateMedtronic(treatment, true);
+ } else
log.error("Date is null: " + treatment.toString());
} catch (JSONException e) {
log.error("Unhandled exception", e);
@@ -389,12 +397,19 @@ public class TreatmentService extends OrmLiteBaseService {
public UpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) {
+
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout);
+
try {
treatment.date = DatabaseHelper.roundDateToSec(treatment.date);
Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date);
- if (existingTreatment==null) {
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment);
+
+ if (existingTreatment == null) {
getDao().create(treatment);
if (L.isEnabled(L.DATATREATMENTS))
log.debug("New record from: " + Source.getString(treatment.source) + " " + treatment.toString());
@@ -403,7 +418,10 @@ public class TreatmentService extends OrmLiteBaseService {
return new UpdateReturn(true, true);
} else {
- if (existingTreatment.date==treatment.date) {
+ if (existingTreatment.date == treatment.date) {
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date==treatment.date)");
+
// we will do update only, if entry changed
if (!optionalTreatmentCopy(existingTreatment, treatment, fromNightScout)) {
return new UpdateReturn(true, false);
@@ -413,6 +431,9 @@ public class TreatmentService extends OrmLiteBaseService {
scheduleTreatmentChange(treatment);
return new UpdateReturn(true, false);
} else {
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: createOrUpdateMedtronic::(existingTreatment.date != treatment.date)");
+
// date is different, we need to remove entry
getDao().delete(existingTreatment);
optionalTreatmentCopy(existingTreatment, treatment, fromNightScout);
@@ -476,15 +497,15 @@ public class TreatmentService extends OrmLiteBaseService {
int source = Source.NONE;
- if (oldTreatment.pumpId==0) {
+ if (oldTreatment.pumpId == 0) {
if (newTreatment.pumpId > 0) {
- oldTreatment.pumpId=newTreatment.pumpId;
+ oldTreatment.pumpId = newTreatment.pumpId;
source = Source.PUMP;
changed = true;
}
}
- if (source==Source.NONE) {
+ if (source == Source.NONE) {
if (oldTreatment.source == newTreatment.source) {
source = oldTreatment.source;
@@ -515,7 +536,6 @@ public class TreatmentService extends OrmLiteBaseService {
log.debug("treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString());
-
if (fromNightScout) {
long pumpId_old = oldTreatment.pumpId;
boolean isSMB = (oldTreatment.isSMB || newTreatment.isSMB);
@@ -545,7 +565,7 @@ public class TreatmentService extends OrmLiteBaseService {
Treatment record = null;
- if (pumpId>0) {
+ if (pumpId > 0) {
record = getPumpRecordById(pumpId);
@@ -565,7 +585,6 @@ public class TreatmentService extends OrmLiteBaseService {
}
-
/**
* Returns the record for the given id, null if none, throws RuntimeException
* if multiple records with the same pump id exist.
@@ -686,7 +705,7 @@ public class TreatmentService extends OrmLiteBaseService {
return new ArrayList<>();
}
- public List getTreatmentDataFromTime(long from, long to, boolean ascending) {
+ public List getTreatmentDataFromTime(long from, long to, boolean ascending) {
try {
Dao daoTreatments = getDao();
List treatments;
@@ -717,6 +736,14 @@ public class TreatmentService extends OrmLiteBaseService {
boolean newRecord;
boolean success;
+
+ @Override
+ public String toString() {
+ return "UpdateReturn [" +
+ "newRecord=" + newRecord +
+ ", success=" + success +
+ ']';
+ }
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java
index 192952057d..731042c237 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsFragment.java
@@ -1,19 +1,18 @@
package info.nightscout.androidaps.plugins.treatments;
import android.os.Bundle;
-import androidx.fragment.app.Fragment;
-import androidx.fragment.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.fragment.app.Fragment;
+import androidx.fragment.app.FragmentTransaction;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment;
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsCareportalFragment;
@@ -22,8 +21,12 @@ import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfile
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTempTargetFragment;
import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsTemporaryBasalsFragment;
import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
+
+public class TreatmentsFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
-public class TreatmentsFragment extends SubscriberFragment implements View.OnClickListener {
TextView treatmentsTab;
TextView extendedBolusesTab;
TextView tempBasalsTab;
@@ -34,32 +37,42 @@ public class TreatmentsFragment extends SubscriberFragment implements View.OnCli
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
- try {
- View view = inflater.inflate(R.layout.treatments_fragment, container, false);
+ View view = inflater.inflate(R.layout.treatments_fragment, container, false);
- treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments);
- extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses);
- tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals);
- tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets);
- profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches);
- careportalTab = (TextView) view.findViewById(R.id.treatments_careportal);
- treatmentsTab.setOnClickListener(this);
- extendedBolusesTab.setOnClickListener(this);
- tempBasalsTab.setOnClickListener(this);
- tempTargetTab.setOnClickListener(this);
- profileSwitchTab.setOnClickListener(this);
- careportalTab.setOnClickListener(this);
+ treatmentsTab = (TextView) view.findViewById(R.id.treatments_treatments);
+ extendedBolusesTab = (TextView) view.findViewById(R.id.treatments_extendedboluses);
+ tempBasalsTab = (TextView) view.findViewById(R.id.treatments_tempbasals);
+ tempTargetTab = (TextView) view.findViewById(R.id.treatments_temptargets);
+ profileSwitchTab = (TextView) view.findViewById(R.id.treatments_profileswitches);
+ careportalTab = (TextView) view.findViewById(R.id.treatments_careportal);
+ treatmentsTab.setOnClickListener(this);
+ extendedBolusesTab.setOnClickListener(this);
+ tempBasalsTab.setOnClickListener(this);
+ tempTargetTab.setOnClickListener(this);
+ profileSwitchTab.setOnClickListener(this);
+ careportalTab.setOnClickListener(this);
- setFragment(new TreatmentsBolusFragment());
- setBackgroundColorOnSelected(treatmentsTab);
+ setFragment(new TreatmentsBolusFragment());
+ setBackgroundColorOnSelected(treatmentsTab);
- return view;
- } catch (Exception e) {
- FabricPrivacy.logException(e);
- }
+ return view;
+ }
- return null;
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
}
@Override
@@ -111,13 +124,7 @@ public class TreatmentsFragment extends SubscriberFragment implements View.OnCli
selected.setBackgroundColor(MainApp.gc(R.color.tabBgColorSelected));
}
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
+ private void updateGui() {
if (ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().isExtendedBolusCapable
|| TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory().size() > 0) {
extendedBolusesTab.setVisibility(View.VISIBLE);
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java
index 195005e87a..004f44858d 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java
@@ -6,7 +6,6 @@ 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;
@@ -52,6 +51,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
+import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData;
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin;
import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin;
@@ -59,6 +59,8 @@ 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.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
/**
* Created by mike on 05.08.2016.
@@ -66,6 +68,8 @@ import info.nightscout.androidaps.utils.T;
public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface {
private Logger log = LoggerFactory.getLogger(L.DATATREATMENTS);
+ private CompositeDisposable disposable = new CompositeDisposable();
+
private static TreatmentsPlugin treatmentsPlugin;
public static TreatmentsPlugin getPlugin() {
@@ -99,18 +103,53 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
@Override
protected void onStart() {
- MainApp.bus().register(this);
initializeTempBasalData();
initializeTreatmentData();
initializeExtendedBolusData();
initializeTempTargetData();
initializeProfileSwitchData();
super.onStart();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventReloadTreatmentData.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.DATATREATMENTS))
+ log.debug("EventReloadTreatmentData");
+ initializeTreatmentData();
+ initializeExtendedBolusData();
+ updateTotalIOBTreatments();
+ RxBus.INSTANCE.send(event.getNext());
+ },
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventReloadProfileSwitchData.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> initializeProfileSwitchData(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempTargetChange.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> initializeTempTargetData(),
+ FabricPrivacy::logException
+ ));
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventReloadTempBasalData.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.DATATREATMENTS))
+ log.debug("EventReloadTempBasalData");
+ initializeTempBasalData();
+ updateTotalIOBTempBasals();
+ },
+ FabricPrivacy::logException
+ ));
}
@Override
protected void onStop() {
- MainApp.bus().register(this);
+ disposable.clear();
super.onStop();
}
@@ -306,12 +345,20 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
@Override
public List getTreatmentsFromHistoryAfterTimestamp(long fromTimestamp) {
List in5minback = new ArrayList<>();
+
long time = System.currentTimeMillis();
synchronized (treatments) {
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: AllTreatmentsInDb: {}", MedtronicUtil.getGsonInstanceCore().toJson(treatments));
+
for (Treatment t : treatments) {
if (t.date <= time && t.date >= fromTimestamp)
in5minback.add(t);
}
+
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={}", fromTimestamp, MedtronicUtil.getGsonInstanceCore().toJson(in5minback));
+
return in5minback;
}
}
@@ -387,25 +434,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
return getExtendedBolusFromHistory(System.currentTimeMillis()) != null; //TODO: crosscheck here
}
- @Subscribe
- public void onStatusEvent(final EventReloadTreatmentData ev) {
- if (L.isEnabled(L.DATATREATMENTS))
- log.debug("EventReloadTreatmentData");
- initializeTreatmentData();
- initializeExtendedBolusData();
- updateTotalIOBTreatments();
- MainApp.bus().post(ev.next);
- }
-
- @Subscribe
- @SuppressWarnings("unused")
- public void onStatusEvent(final EventReloadTempBasalData ev) {
- if (L.isEnabled(L.DATATREATMENTS))
- log.debug("EventReloadTempBasalData");
- initializeTempBasalData();
- updateTotalIOBTempBasals();
- }
-
@Override
public IobTotal getLastCalculationTempBasals() {
return lastTempBasalsCalculation;
@@ -604,6 +632,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) {
boolean medtronicPump = MedtronicUtil.isMedtronicPump();
+ if (MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: addToHistoryTreatment::isMedtronicPump={}", medtronicPump);
+
Treatment treatment = new Treatment();
treatment.date = detailedBolusInfo.date;
treatment.source = detailedBolusInfo.source;
@@ -618,6 +649,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
treatment.boluscalc = detailedBolusInfo.boluscalc != null ? detailedBolusInfo.boluscalc.toString() : null;
TreatmentService.UpdateReturn creatOrUpdateResult;
+ if (medtronicPump && MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: addToHistoryTreatment::treatment={}", treatment);
+
if (!medtronicPump)
creatOrUpdateResult = getService().createOrUpdate(treatment);
else
@@ -626,12 +660,17 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
boolean newRecordCreated = creatOrUpdateResult.newRecord;
//log.debug("Adding new Treatment record" + treatment.toString());
if (detailedBolusInfo.carbTime != 0) {
+
Treatment carbsTreatment = new Treatment();
carbsTreatment.source = detailedBolusInfo.source;
carbsTreatment.pumpId = detailedBolusInfo.pumpId; // but this should never happen
carbsTreatment.date = detailedBolusInfo.date + detailedBolusInfo.carbTime * 60 * 1000L + 1000L; // add 1 sec to make them different records
carbsTreatment.carbs = detailedBolusInfo.carbs;
carbsTreatment.source = detailedBolusInfo.source;
+
+ if (medtronicPump && MedtronicHistoryData.doubleBolusDebug)
+ log.debug("DoubleBolusDebug: carbTime!=0, creating second treatment. CarbsTreatment={}", carbsTreatment);
+
if (!medtronicPump)
getService().createOrUpdate(carbsTreatment);
else
@@ -681,13 +720,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
return oldestTime;
}
- // TempTargets
- @Subscribe
- @SuppressWarnings("unused")
- public void onStatusEvent(final EventTempTargetChange ev) {
- initializeTempTargetData();
- }
-
@Nullable
@Override
public TempTarget getTempTargetFromHistory() {
@@ -718,13 +750,6 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
NSUpload.uploadTempTarget(tempTarget);
}
- // Profile Switch
- @Subscribe
- @SuppressWarnings("unused")
- public void onStatusEvent(final EventReloadProfileSwitchData ev) {
- initializeProfileSwitchData();
- }
-
@Override
@Nullable
public ProfileSwitch getProfileSwitchFromHistory(long time) {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java
index 556d80f321..ee78c6748b 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.java
@@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.treatments.fragments;
-import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
@@ -14,12 +13,11 @@ import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
+import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.squareup.otto.Subscribe;
-
import java.util.List;
import info.nightscout.androidaps.MainApp;
@@ -28,7 +26,7 @@ import info.nightscout.androidaps.data.Iob;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventTreatmentChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
@@ -39,11 +37,16 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.treatments.dialogs.WizardInfoDialog;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
import static info.nightscout.androidaps.utils.DateUtil.now;
-public class TreatmentsBolusFragment extends SubscriberFragment implements View.OnClickListener {
+public class TreatmentsBolusFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -162,7 +165,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
}
TreatmentsPlugin.getPlugin().getService().delete(treatment);
}
- updateGUI();
+ updateGui();
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
@@ -213,7 +216,6 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
context = getContext();
- updateGUI();
return view;
}
@@ -227,7 +229,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
builder.setMessage(MainApp.gs(R.string.refresheventsfromnightscout) + "?");
builder.setPositiveButton(MainApp.gs(R.string.ok), (dialog, id) -> {
TreatmentsPlugin.getPlugin().getService().resetTreatments();
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
@@ -248,7 +250,7 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
}
TreatmentsPlugin.getPlugin().getService().delete(treatment);
}
- updateGUI();
+ updateGui();
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
builder.show();
@@ -256,32 +258,39 @@ public class TreatmentsBolusFragment extends SubscriberFragment implements View.
}
}
- @Subscribe
- public void onStatusEvent(final EventTreatmentChange ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- updateGUI();
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTreatmentChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
}
@Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTreatmentsFromHistory()), false);
- if (TreatmentsPlugin.getPlugin().getLastCalculationTreatments() != null) {
- iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().iob) + " " + MainApp.gs(R.string.insulin_unit_shortname));
- activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().activity) + " " + MainApp.gs(R.string.insulin_unit_shortname));
- }
- if (!TreatmentsPlugin.getPlugin().getService().getTreatmentDataFromTime(now() + 1000, true).isEmpty()) {
- deleteFutureTreatments.setVisibility(View.VISIBLE);
- } else {
- deleteFutureTreatments.setVisibility(View.GONE);
- }
- });
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
+ private void updateGui() {
+ recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTreatmentsFromHistory()), false);
+ if (TreatmentsPlugin.getPlugin().getLastCalculationTreatments() != null) {
+ iobTotal.setText(DecimalFormatter.to2Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().iob) + " " + MainApp.gs(R.string.insulin_unit_shortname));
+ activityTotal.setText(DecimalFormatter.to3Decimal(TreatmentsPlugin.getPlugin().getLastCalculationTreatments().activity) + " " + MainApp.gs(R.string.insulin_unit_shortname));
+ }
+ if (!TreatmentsPlugin.getPlugin().getService().getTreatmentDataFromTime(now() + 1000, true).isEmpty()) {
+ deleteFutureTreatments.setVisibility(View.VISIBLE);
+ } else {
+ deleteFutureTreatments.setVisibility(View.GONE);
+ }
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java
index 4a0e767cbb..4810a1ed8c 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.java
@@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.treatments.fragments;
-import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
@@ -13,30 +12,33 @@ import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
+import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.squareup.otto.Subscribe;
-
import java.util.List;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.db.CareportalEvent;
import info.nightscout.androidaps.events.EventCareportalEventChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import info.nightscout.androidaps.utils.DateUtil;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.Translator;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by mike on 13/01/17.
*/
-public class TreatmentsCareportalFragment extends SubscriberFragment implements View.OnClickListener {
+public class TreatmentsCareportalFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -148,10 +150,26 @@ public class TreatmentsCareportalFragment extends SubscriberFragment implements
if (nsUploadOnly)
refreshFromNS.setVisibility(View.GONE);
- updateGUI();
return view;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventCareportalEventChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
@Override
public void onClick(View view) {
switch (view.getId()) {
@@ -162,7 +180,7 @@ public class TreatmentsCareportalFragment extends SubscriberFragment implements
builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetCareportalEvents();
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
@@ -182,21 +200,8 @@ public class TreatmentsCareportalFragment extends SubscriberFragment implements
}
- @Subscribe
- public void onStatusEvent(final EventCareportalEventChange ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)), false);
- }
- });
+ private void updateGui() {
+ recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getCareportalEvents(false)), false);
}
private void removeAndroidAPSStatedEvents() {
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java
index 24a5185ef0..5ce7b57564 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.java
@@ -1,21 +1,20 @@
package info.nightscout.androidaps.plugins.treatments.fragments;
-import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
import android.os.Bundle;
-import androidx.core.content.ContextCompat;
-import androidx.appcompat.app.AlertDialog;
-import androidx.cardview.widget.CardView;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.appcompat.app.AlertDialog;
+import androidx.cardview.widget.CardView;
+import androidx.core.content.ContextCompat;
+import androidx.fragment.app.Fragment;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -24,16 +23,21 @@ import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.db.ExtendedBolus;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventExtendedBolusChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class TreatmentsExtendedBolusesFragment extends SubscriberFragment {
+public class TreatmentsExtendedBolusesFragment extends Fragment {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -173,30 +177,33 @@ public class TreatmentsExtendedBolusesFragment extends SubscriberFragment {
context = getContext();
- updateGUI();
return view;
}
- @Subscribe
- public void onStatusEvent(final EventExtendedBolusChange ev) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ev) {
- updateGUI();
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventExtendedBolusChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
}
@Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null && recyclerView != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false);
- }
- });
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
+ private void updateGui() {
+ recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getExtendedBolusesFromHistory()), false);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java
index 71d8eb2b18..2d06b2824f 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.java
@@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.treatments.fragments;
-import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Paint;
@@ -14,12 +13,11 @@ import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
+import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,21 +30,25 @@ import info.nightscout.androidaps.db.ProfileSwitch;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.logging.L;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by mike on 13/01/17.
*/
-public class TreatmentsProfileSwitchFragment extends SubscriberFragment implements View.OnClickListener {
+public class TreatmentsProfileSwitchFragment extends Fragment implements View.OnClickListener {
private Logger log = LoggerFactory.getLogger(L.UI);
+ private CompositeDisposable disposable = new CompositeDisposable();
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -195,10 +197,26 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen
if (nsUploadOnly)
refreshFromNS.setVisibility(View.GONE);
- updateGUI();
return view;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventProfileNeedsUpdate.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGUI(), FabricPrivacy::logException)
+ );
+ updateGUI();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
@Override
public void onClick(View view) {
switch (view.getId()) {
@@ -209,7 +227,7 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen
builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetProfileSwitch();
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
@@ -218,20 +236,7 @@ public class TreatmentsProfileSwitchFragment extends SubscriberFragment implemen
}
}
- @Subscribe
- public void onStatusEvent(final EventProfileNeedsUpdate ev) {
- updateGUI();
- }
-
- @Override
protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getProfileSwitchData(false)), false);
- }
- });
+ recyclerView.swapAdapter(new RecyclerViewAdapter(MainApp.getDbHelper().getProfileSwitchData(false)), false);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java
index 3c17e7b762..ccd1b327c9 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java
@@ -14,18 +14,17 @@ import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
+import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
-import com.squareup.otto.Subscribe;
-
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.Intervals;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TempTarget;
import info.nightscout.androidaps.events.EventTempTargetChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
@@ -33,13 +32,17 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
/**
* Created by mike on 13/01/17.
*/
-public class TreatmentsTempTargetFragment extends SubscriberFragment implements View.OnClickListener {
+public class TreatmentsTempTargetFragment extends Fragment implements View.OnClickListener {
+ private CompositeDisposable disposable = new CompositeDisposable();
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -184,10 +187,26 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements
if (nsUploadOnly)
refreshFromNS.setVisibility(View.GONE);
- updateGUI();
return view;
}
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempTargetChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
+ }
+
+ @Override
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
@Override
public void onClick(View view) {
switch (view.getId()) {
@@ -198,7 +217,7 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements
builder.setPositiveButton(MainApp.gs(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainApp.getDbHelper().resetTempTargets();
- MainApp.bus().post(new EventNSClientRestart());
+ RxBus.INSTANCE.send(new EventNSClientRestart());
}
});
builder.setNegativeButton(MainApp.gs(R.string.cancel), null);
@@ -208,20 +227,7 @@ public class TreatmentsTempTargetFragment extends SubscriberFragment implements
}
- @Subscribe
- public void onStatusEvent(final EventTempTargetChange ev) {
- updateGUI();
- }
-
- @Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()), false);
- }
- });
+ private void updateGui() {
+ recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTempTargetsFromHistory()), false);
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java
index 6aed7aea43..45f930410e 100644
--- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java
+++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.java
@@ -1,21 +1,20 @@
package info.nightscout.androidaps.plugins.treatments.fragments;
-import android.app.Activity;
import android.content.Context;
import android.graphics.Paint;
import android.os.Bundle;
-import androidx.annotation.NonNull;
-import androidx.core.content.ContextCompat;
-import androidx.appcompat.app.AlertDialog;
-import androidx.cardview.widget.CardView;
-import androidx.recyclerview.widget.LinearLayoutManager;
-import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
+import androidx.annotation.NonNull;
+import androidx.appcompat.app.AlertDialog;
+import androidx.cardview.widget.CardView;
+import androidx.core.content.ContextCompat;
+import androidx.fragment.app.Fragment;
+import androidx.recyclerview.widget.LinearLayoutManager;
+import androidx.recyclerview.widget.RecyclerView;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
@@ -25,7 +24,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.Source;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.events.EventTempBasalChange;
-import info.nightscout.androidaps.plugins.common.SubscriberFragment;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue;
@@ -33,9 +32,14 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutos
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.DecimalFormatter;
+import info.nightscout.androidaps.utils.FabricPrivacy;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
-public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment {
+public class TreatmentsTemporaryBasalsFragment extends Fragment {
+ private CompositeDisposable disposable = new CompositeDisposable();
+
RecyclerView recyclerView;
LinearLayoutManager llm;
@@ -199,30 +203,36 @@ public class TreatmentsTemporaryBasalsFragment extends SubscriberFragment {
context = getContext();
- updateGUI();
return view;
}
- @Subscribe
- public void onStatusEvent(final EventTempBasalChange ignored) {
- updateGUI();
- }
-
- @Subscribe
- public void onStatusEvent(final EventAutosensCalculationFinished ignored) {
- updateGUI();
+ @Override
+ public synchronized void onResume() {
+ super.onResume();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventTempBasalChange.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAutosensCalculationFinished.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateGui(), FabricPrivacy::logException)
+ );
+ updateGui();
}
@Override
- protected void updateGUI() {
- Activity activity = getActivity();
- if (activity != null)
- activity.runOnUiThread(() -> {
- recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTemporaryBasalsFromHistory()), false);
- IobTotal tempBasalsCalculation = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals();
- if (tempBasalsCalculation != null)
- tempBasalTotalView.setText(DecimalFormatter.to2Decimal(tempBasalsCalculation.basaliob, " U"));
- });
+ public synchronized void onPause() {
+ super.onPause();
+ disposable.clear();
+ }
+
+ private void updateGui() {
+ recyclerView.swapAdapter(new RecyclerViewAdapter(TreatmentsPlugin.getPlugin().getTemporaryBasalsFromHistory()), false);
+ IobTotal tempBasalsCalculation = TreatmentsPlugin.getPlugin().getLastCalculationTempBasals();
+ if (tempBasalsCalculation != null)
+ tempBasalTotalView.setText(DecimalFormatter.to2Decimal(tempBasalsCalculation.basaliob, " U"));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java
index 3130cb0df3..f24b02171f 100644
--- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java
+++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.java
@@ -27,7 +27,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressHelperActivity;
-import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
+import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
@@ -101,16 +101,20 @@ public class CommandQueue {
}
private synchronized void removeAll(Command.CommandType type) {
- for (int i = queue.size() - 1; i >= 0; i--) {
- if (queue.get(i).commandType == type) {
- queue.remove(i);
+ synchronized (queue) {
+ for (int i = queue.size() - 1; i >= 0; i--) {
+ if (queue.get(i).commandType == type) {
+ queue.remove(i);
+ }
}
}
}
private synchronized boolean isLastScheduled(Command.CommandType type) {
- if (queue.size() > 0 && queue.get(queue.size() - 1).commandType == type) {
- return true;
+ synchronized (queue) {
+ if (queue.size() > 0 && queue.get(queue.size() - 1).commandType == type) {
+ return true;
+ }
}
return false;
}
@@ -119,26 +123,33 @@ public class CommandQueue {
// inject as a first command
if (L.isEnabled(L.PUMPQUEUE))
log.debug("Adding as first: " + command.getClass().getSimpleName() + " - " + command.status());
- queue.addFirst(command);
+ synchronized (queue) {
+ queue.addFirst(command);
+ }
}
private synchronized void add(Command command) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("Adding: " + command.getClass().getSimpleName() + " - " + command.status());
- queue.add(command);
+ synchronized (queue) {
+ queue.add(command);
+ }
}
synchronized void pickup() {
- performing = queue.poll();
+ synchronized (queue) {
+ performing = queue.poll();
+ }
}
synchronized void clear() {
performing = null;
- for (int i = 0; i < queue.size(); i++) {
- queue.get(i).cancel();
+ synchronized (queue) {
+ for (int i = 0; i < queue.size(); i++) {
+ queue.get(i).cancel();
+ }
+ queue.clear();
}
-
- queue.clear();
}
public int size() {
@@ -181,9 +192,11 @@ public class CommandQueue {
public synchronized boolean bolusInQueue() {
if (isRunning(Command.CommandType.BOLUS)) return true;
- for (int i = 0; i < queue.size(); i++) {
- if (queue.get(i).commandType == Command.CommandType.BOLUS) {
- return true;
+ synchronized (queue) {
+ for (int i = 0; i < queue.size(); i++) {
+ if (queue.get(i).commandType == Command.CommandType.BOLUS) {
+ return true;
+ }
}
}
return false;
@@ -236,7 +249,7 @@ public class CommandQueue {
// not when the Bolus command is starting. The command closes the dialog upon completion).
showBolusProgressDialog(detailedBolusInfo.insulin, detailedBolusInfo.context);
// Notify Wear about upcoming bolus
- MainApp.bus().post(new EventBolusRequested(detailedBolusInfo.insulin));
+ RxBus.INSTANCE.send(new EventBolusRequested(detailedBolusInfo.insulin));
}
}
@@ -262,7 +275,7 @@ public class CommandQueue {
public synchronized void cancelAllBoluses() {
if (!isRunning(Command.CommandType.BOLUS)) {
- MainApp.bus().post(new EventDismissBolusprogressIfRunning(new PumpEnactResult().success(true).enacted(false)));
+ RxBus.INSTANCE.send(new EventDismissBolusProgressIfRunning(new PumpEnactResult().success(true).enacted(false)));
}
removeAll(Command.CommandType.BOLUS);
removeAll(Command.CommandType.SMB_BOLUS);
@@ -440,9 +453,11 @@ public class CommandQueue {
public synchronized boolean statusInQueue() {
if (isRunning(Command.CommandType.READSTATUS))
return true;
- for (int i = 0; i < queue.size(); i++) {
- if (queue.get(i).commandType == Command.CommandType.READSTATUS) {
- return true;
+ synchronized (queue) {
+ for (int i = 0; i < queue.size(); i++) {
+ if (queue.get(i).commandType == Command.CommandType.READSTATUS) {
+ return true;
+ }
}
}
return false;
@@ -528,15 +543,18 @@ public class CommandQueue {
public Spanned spannedStatus() {
String s = "";
int line = 0;
- if (performing != null) {
- s += "" + performing.status() + "";
+ Command perf = performing;
+ if (perf != null) {
+ s += "" + perf.status() + "";
line++;
}
- for (int i = 0; i < queue.size(); i++) {
- if (line != 0)
- s += " ";
- s += queue.get(i).status();
- line++;
+ synchronized (queue) {
+ for (int i = 0; i < queue.size(); i++) {
+ if (line != 0)
+ s += " ";
+ s += queue.get(i).status();
+ line++;
+ }
}
return Html.fromHtml(s);
}
diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java
index 59eaf6471e..85823c2c30 100644
--- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java
+++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java
@@ -14,8 +14,9 @@ import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
+import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning;
import info.nightscout.androidaps.queue.events.EventQueueChanged;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
@@ -50,7 +51,7 @@ public class QueueThread extends Thread {
public final void run() {
if (mWakeLock != null)
mWakeLock.acquire(T.mins(10).msecs());
- MainApp.bus().post(new EventQueueChanged());
+ RxBus.INSTANCE.send(new EventQueueChanged());
long lastCommandTime;
long connectionStartTime = lastCommandTime = System.currentTimeMillis();
@@ -60,15 +61,15 @@ public class QueueThread extends Thread {
if (pump == null) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("pump == null");
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized)));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.pumpNotInitialized)));
SystemClock.sleep(1000);
continue;
}
long secondsElapsed = (System.currentTimeMillis() - connectionStartTime) / 1000;
if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) {
- MainApp.bus().post(new EventDismissBolusprogressIfRunning(null));
- MainApp.bus().post(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout)));
+ RxBus.INSTANCE.send(new EventDismissBolusProgressIfRunning(null));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(MainApp.gs(R.string.connectiontimedout)));
if (L.isEnabled(L.PUMPQUEUE))
log.debug("timed out");
pump.stopConnecting();
@@ -100,9 +101,9 @@ public class QueueThread extends Thread {
queue.clear();
if (L.isEnabled(L.PUMPQUEUE))
log.debug("no connection possible");
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
pump.disconnect("Queue empty");
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
return;
}
}
@@ -110,7 +111,7 @@ public class QueueThread extends Thread {
if (pump.isHandshakeInProgress()) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("handshaking " + secondsElapsed);
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.HANDSHAKING, (int) secondsElapsed));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.HANDSHAKING, (int) secondsElapsed));
SystemClock.sleep(100);
continue;
}
@@ -118,7 +119,7 @@ public class QueueThread extends Thread {
if (pump.isConnecting()) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("connecting " + secondsElapsed);
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTING, (int) secondsElapsed));
SystemClock.sleep(1000);
continue;
}
@@ -126,7 +127,7 @@ public class QueueThread extends Thread {
if (!pump.isConnected()) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("connect");
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.CONNECTING, (int) secondsElapsed));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTING, (int) secondsElapsed));
pump.connect("Connection needed");
SystemClock.sleep(1000);
continue;
@@ -144,10 +145,10 @@ public class QueueThread extends Thread {
if (queue.performing() != null) {
if (L.isEnabled(L.PUMPQUEUE))
log.debug("performing " + queue.performing().status());
- MainApp.bus().post(new EventQueueChanged());
+ RxBus.INSTANCE.send(new EventQueueChanged());
queue.performing().execute();
queue.resetPerforming();
- MainApp.bus().post(new EventQueueChanged());
+ RxBus.INSTANCE.send(new EventQueueChanged());
lastCommandTime = System.currentTimeMillis();
SystemClock.sleep(100);
continue;
@@ -161,9 +162,9 @@ public class QueueThread extends Thread {
waitingForDisconnect = true;
if (L.isEnabled(L.PUMPQUEUE))
log.debug("queue empty. disconnect");
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTING));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING));
pump.disconnect("Queue empty");
- MainApp.bus().post(new EventPumpStatusChanged(EventPumpStatusChanged.DISCONNECTED));
+ RxBus.INSTANCE.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED));
if (L.isEnabled(L.PUMPQUEUE))
log.debug("disconnected");
return;
diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java
index 4dc132e128..6348ea31b9 100644
--- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java
+++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandBolus.java
@@ -3,13 +3,13 @@ package info.nightscout.androidaps.queue.commands;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.data.DetailedBolusInfo;
import info.nightscout.androidaps.data.PumpEnactResult;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.general.overview.dialogs.BolusProgressDialog;
-import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusprogressIfRunning;
+import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.DecimalFormatter;
@@ -33,7 +33,7 @@ public class CommandBolus extends Command {
PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().deliverTreatment(detailedBolusInfo);
BolusProgressDialog.bolusEnded = true;
- MainApp.bus().post(new EventDismissBolusprogressIfRunning(r));
+ RxBus.INSTANCE.send(new EventDismissBolusProgressIfRunning(r));
if (L.isEnabled(L.PUMPQUEUE))
log.debug("Result success: " + r.success + " enacted: " + r.enacted);
diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java
index 6b8a610fa6..b69f3f4dc7 100644
--- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java
+++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSetProfile.java
@@ -50,8 +50,8 @@ public class CommandSetProfile extends Command {
// Send SMS notification if ProfileSwitch is comming from NS
ProfileSwitch profileSwitch = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(System.currentTimeMillis());
if (profileSwitch != null && r.enacted && profileSwitch.source == Source.NIGHTSCOUT) {
- SmsCommunicatorPlugin smsCommunicatorPlugin = MainApp.getSpecificPlugin(SmsCommunicatorPlugin.class);
- if (smsCommunicatorPlugin != null && smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) {
+ SmsCommunicatorPlugin smsCommunicatorPlugin = SmsCommunicatorPlugin.INSTANCE;
+ if (smsCommunicatorPlugin.isEnabled(PluginType.GENERAL)) {
smsCommunicatorPlugin.sendNotificationToAllNumbers(MainApp.gs(R.string.profile_set_ok));
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java
index d325ee9506..cb49d8cf4e 100644
--- a/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java
+++ b/app/src/main/java/info/nightscout/androidaps/receivers/ChargingStateReceiver.java
@@ -5,8 +5,8 @@ import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventChargingState;
+import info.nightscout.androidaps.plugins.bus.RxBus;
public class ChargingStateReceiver extends BroadcastReceiver {
@@ -17,11 +17,11 @@ public class ChargingStateReceiver extends BroadcastReceiver {
EventChargingState event = grabChargingState(context);
if (event != null)
- MainApp.bus().post(event);
+ RxBus.INSTANCE.send(event);
lastEvent = event;
}
- public EventChargingState grabChargingState(Context context) {
+ public static EventChargingState grabChargingState(Context context) {
BatteryManager bm = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
if (bm == null)
diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java
index 7a9aa31c46..4c8a3f660e 100644
--- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java
+++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.java
@@ -16,6 +16,7 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.logging.L;
+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.queue.commands.Command;
@@ -73,7 +74,7 @@ public class KeepAliveReceiver extends BroadcastReceiver {
}
if (!pump.isThisProfileSet(profile) && !ConfigBuilderPlugin.getPlugin().getCommandQueue().isRunning(Command.CommandType.BASALPROFILE)) {
- MainApp.bus().post(new EventProfileNeedsUpdate());
+ RxBus.INSTANCE.send(new EventProfileNeedsUpdate());
} else if (isStatusOutdated && !pump.isBusy()) {
lastReadStatus = System.currentTimeMillis();
ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("KeepAlive. Status outdated.", null);
diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java
index 2695ad64f2..19cf12bc8a 100644
--- a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java
+++ b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java
@@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventNetworkChange;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
public class NetworkChangeReceiver extends BroadcastReceiver {
@@ -23,15 +24,17 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
private static EventNetworkChange lastEvent = null;
+ public static final NetworkChangeReceiver instance = new NetworkChangeReceiver();
+
@Override
public void onReceive(final Context context, final Intent intent) {
EventNetworkChange event = grabNetworkStatus(context);
if (event != null)
- MainApp.bus().post(event);
+ RxBus.INSTANCE.send(event);
}
@Nullable
- public EventNetworkChange grabNetworkStatus(final Context context) {
+ public static EventNetworkChange grabNetworkStatus(final Context context) {
EventNetworkChange event = new EventNetworkChange();
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
@@ -40,23 +43,23 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
if (activeNetwork != null) {
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI && activeNetwork.isConnected()) {
- event.wifiConnected = true;
+ event.setWifiConnected(true);
WifiManager wifiManager = (WifiManager) MainApp.instance().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
- event.ssid = wifiInfo.getSSID();
+ event.setSsid(wifiInfo.getSSID());
}
if (L.isEnabled(L.CORE))
- log.debug("NETCHANGE: Wifi connected. SSID: " + event.ssid);
+ log.debug("NETCHANGE: Wifi connected. SSID: " + event.connectedSsid());
}
}
if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
- event.mobileConnected = true;
- event.roaming = activeNetwork.isRoaming();
+ event.setMobileConnected(true);
+ event.setRoaming(activeNetwork.isRoaming());
if (L.isEnabled(L.CORE))
- log.debug("NETCHANGE: Mobile connected. Roaming: " + event.roaming);
+ log.debug("NETCHANGE: Mobile connected. Roaming: " + event.getRoaming());
}
} else {
if (L.isEnabled(L.CORE))
@@ -68,14 +71,14 @@ public class NetworkChangeReceiver extends BroadcastReceiver {
}
public static boolean isWifiConnected() {
- return lastEvent != null && lastEvent.wifiConnected;
+ return lastEvent != null && lastEvent.getWifiConnected();
}
- public static boolean isConnected() {
- return lastEvent != null && (lastEvent.wifiConnected || lastEvent.mobileConnected);
+ public static boolean isConnected() {
+ return lastEvent != null && (lastEvent.getWifiConnected() || lastEvent.getMobileConnected());
}
public static EventNetworkChange getLastEvent() {
return lastEvent;
}
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java
index 29b9c5fd01..44050ece35 100644
--- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java
+++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java
@@ -45,7 +45,6 @@ public class DataService extends IntentService {
public DataService() {
super("DataService");
- registerBus();
}
@Override
@@ -87,14 +86,14 @@ public class DataService extends IntentService {
} else if (Intents.ACTION_NEW_STATUS.equals(action)) {
NSSettingsStatus.getInstance().handleNewData(intent);
} else if (Intents.ACTION_NEW_FOOD.equals(action)) {
- EventNsFood evt = new EventNsFood(EventNsFood.ADD, bundles);
- MainApp.bus().post(evt);
+ EventNsFood evt = new EventNsFood(EventNsFood.Companion.getADD(), bundles);
+ RxBus.INSTANCE.send(evt);
} else if (Intents.ACTION_CHANGED_FOOD.equals(action)) {
- EventNsFood evt = new EventNsFood(EventNsFood.UPDATE, bundles);
- MainApp.bus().post(evt);
+ EventNsFood evt = new EventNsFood(EventNsFood.Companion.getUPDATE(), bundles);
+ RxBus.INSTANCE.send(evt);
} else if (Intents.ACTION_REMOVED_FOOD.equals(action)) {
- EventNsFood evt = new EventNsFood(EventNsFood.REMOVE, bundles);
- MainApp.bus().post(evt);
+ EventNsFood evt = new EventNsFood(EventNsFood.Companion.getREMOVE(), bundles);
+ RxBus.INSTANCE.send(evt);
} else if (acceptNSData &&
(Intents.ACTION_NEW_TREATMENT.equals(action) ||
Intents.ACTION_CHANGED_TREATMENT.equals(action) ||
@@ -104,7 +103,7 @@ public class DataService extends IntentService {
) {
handleNewDataFromNSClient(intent);
} else if (Telephony.Sms.Intents.SMS_RECEIVED_ACTION.equals(action)) {
- SmsCommunicatorPlugin.getPlugin().handleNewData(intent);
+ SmsCommunicatorPlugin.INSTANCE.handleNewData(intent);
}
if (L.isEnabled(L.DATASERVICE))
@@ -115,16 +114,6 @@ public class DataService extends IntentService {
@Override
public void onDestroy() {
super.onDestroy();
- MainApp.bus().unregister(this);
- }
-
- private void registerBus() {
- try {
- MainApp.bus().unregister(this);
- } catch (RuntimeException x) {
- // Ignore
- }
- MainApp.bus().register(this);
}
private void handleNewDataFromNSClient(Intent intent) {
@@ -198,8 +187,8 @@ public class DataService extends IntentService {
private void handleRemovedTreatmentFromNS(JSONObject json) {
// new DB model
- EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.REMOVE, json);
- MainApp.bus().post(evtTreatment);
+ EventNsTreatment evtTreatment = new EventNsTreatment(EventNsTreatment.Companion.getREMOVE(), json);
+ RxBus.INSTANCE.send(evtTreatment);
// old DB model
String _id = JsonHelper.safeGetString(json, "_id");
MainApp.getDbHelper().deleteTempTargetById(_id);
@@ -211,7 +200,7 @@ public class DataService extends IntentService {
private void handleTreatmentFromNS(JSONObject json, Intent intent) {
// new DB model
- int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.ADD : EventNsTreatment.UPDATE;
+ int mode = Intents.ACTION_NEW_TREATMENT.equals(intent.getAction()) ? EventNsTreatment.Companion.getADD() : EventNsTreatment.Companion.getUPDATE();
double insulin = JsonHelper.safeGetDouble(json, "insulin");
double carbs = JsonHelper.safeGetDouble(json, "carbs");
String eventType = JsonHelper.safeGetString(json, "eventType");
@@ -221,7 +210,7 @@ public class DataService extends IntentService {
}
if (insulin > 0 || carbs > 0) {
EventNsTreatment evtTreatment = new EventNsTreatment(mode, json);
- MainApp.bus().post(evtTreatment);
+ RxBus.INSTANCE.send(evtTreatment);
} else if (json.has(DanaRNSHistorySync.DANARSIGNATURE)) {
// old DB model
MainApp.getDbHelper().updateDanaRHistoryRecordId(json);
diff --git a/app/src/main/java/info/nightscout/androidaps/services/LocationService.java b/app/src/main/java/info/nightscout/androidaps/services/LocationService.java
index 33f92d770a..9600515d6f 100644
--- a/app/src/main/java/info/nightscout/androidaps/services/LocationService.java
+++ b/app/src/main/java/info/nightscout/androidaps/services/LocationService.java
@@ -11,23 +11,24 @@ import android.os.IBinder;
import androidx.core.app.ActivityCompat;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.events.EventAppExit;
import info.nightscout.androidaps.events.EventLocationChange;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.persistentNotification.PersistentNotificationPlugin;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.SP;
import info.nightscout.androidaps.utils.T;
+import io.reactivex.disposables.CompositeDisposable;
+import io.reactivex.schedulers.Schedulers;
public class LocationService extends Service {
private static Logger log = LoggerFactory.getLogger(L.LOCATION);
+ private CompositeDisposable disposable = new CompositeDisposable();
private LocationManager mLocationManager = null;
private static final float LOCATION_DISTANCE = 10f;
@@ -125,7 +126,14 @@ public class LocationService extends Service {
} catch (IllegalArgumentException ex) {
log.error("network provider does not exist, " + ex.getMessage());
}
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventAppExit.class)
+ .observeOn(Schedulers.io())
+ .subscribe(event -> {
+ if (L.isEnabled(L.CORE)) log.debug("EventAppExit received");
+ stopSelf();
+ }, FabricPrivacy::logException)
+ );
}
@Override
@@ -143,15 +151,7 @@ public class LocationService extends Service {
log.error("fail to remove location listener, ignore", ex);
}
}
- MainApp.bus().unregister(this);
- }
-
- @Subscribe
- public void onStatusEvent(EventAppExit event) {
- if (L.isEnabled(L.CORE))
- log.debug("EventAppExit received");
-
- stopSelf();
+ disposable.clear();
}
private void initializeLocationManager() {
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java
index 2c6902cb01..2c9e1ea51b 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java
@@ -5,8 +5,6 @@ import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
-import com.squareup.otto.Subscribe;
-
import java.util.ArrayList;
import java.util.List;
@@ -19,6 +17,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
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.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment;
@@ -45,7 +44,6 @@ import info.nightscout.androidaps.setupwizard.elements.SWHtmlLink;
import info.nightscout.androidaps.setupwizard.elements.SWInfotext;
import info.nightscout.androidaps.setupwizard.elements.SWPlugin;
import info.nightscout.androidaps.setupwizard.elements.SWRadioButton;
-import info.nightscout.androidaps.setupwizard.events.EventSWLabel;
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate;
import info.nightscout.androidaps.utils.AndroidPermission;
import info.nightscout.androidaps.utils.LocaleHelper;
@@ -93,8 +91,7 @@ public class SWDefinition {
.preferenceId(R.string.key_language).label(R.string.language)
.comment(R.string.setupwizard_language_prompt))
.validator(() -> {
- String lang = SP.getString("language", "en");
- LocaleHelper.setLocale(MainApp.instance().getApplicationContext(), lang);
+ LocaleHelper.INSTANCE.update(MainApp.instance().getApplicationContext());
return SP.contains(R.string.key_language);
});
@@ -108,7 +105,7 @@ public class SWDefinition {
.visibility(() -> !SP.getBoolean(R.string.key_i_understand, false))
.action(() -> {
SP.putBoolean(R.string.key_i_understand, true);
- MainApp.bus().post(new EventSWUpdate(false));
+ RxBus.INSTANCE.send(new EventSWUpdate(false));
}))
.visibility(() -> !SP.getBoolean(R.string.key_i_understand, false))
.validator(() -> SP.getBoolean(R.string.key_i_understand, false));
@@ -170,8 +167,8 @@ public class SWDefinition {
NSClientPlugin.getPlugin().setFragmentVisible(PluginType.GENERAL, true);
ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(NSClientPlugin.getPlugin(), PluginType.GENERAL);
ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard");
- MainApp.bus().post(new EventConfigBuilderChange());
- MainApp.bus().post(new EventSWUpdate(true));
+ RxBus.INSTANCE.send(new EventConfigBuilderChange());
+ RxBus.INSTANCE.send(new EventSWUpdate(true));
})
.visibility(() -> !NSClientPlugin.getPlugin().isEnabled(PluginType.GENERAL)))
.add(new SWEditUrl()
@@ -186,15 +183,9 @@ public class SWDefinition {
.label(R.string.nsclientinternal_secret_dialogtitle)
.comment(R.string.nsclientinternal_secret_dialogmessage))
.add(new SWBreak())
- .add(new SWEventListener(this)
+ .add(new SWEventListener(this, EventNSClientStatus.class)
.label(R.string.status)
.initialStatus(NSClientPlugin.getPlugin().status)
- .listener(new Object() {
- @Subscribe
- public void onEventNSClientStatus(EventNSClientStatus event) {
- MainApp.bus().post(new EventSWLabel(event.status));
- }
- })
)
.add(new SWBreak())
.validator(() -> NSClientPlugin.getPlugin().nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth)
@@ -328,14 +319,7 @@ public class SWDefinition {
.text(R.string.readstatus)
.action(() -> ConfigBuilderPlugin.getPlugin().getCommandQueue().readStatus("Clicked connect to pump", null))
.visibility(() -> ConfigBuilderPlugin.getPlugin().getActivePump() != null))
- .add(new SWEventListener(this)
- .listener(new Object() {
- @Subscribe
- public void onEventPumpStatusChanged(EventPumpStatusChanged event) {
- MainApp.bus().post(new EventSWLabel(event.textStatus()));
- }
- })
- )
+ .add(new SWEventListener(this, EventPumpStatusChanged.class))
.validator(() -> ConfigBuilderPlugin.getPlugin().getActivePump() != null && ConfigBuilderPlugin.getPlugin().getActivePump().isInitialized());
private SWScreen screenAps = new SWScreen(R.string.configbuilder_aps)
@@ -385,8 +369,8 @@ public class SWDefinition {
LoopPlugin.getPlugin().setFragmentVisible(PluginType.LOOP, true);
ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(LoopPlugin.getPlugin(), PluginType.LOOP);
ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard");
- MainApp.bus().post(new EventConfigBuilderChange());
- MainApp.bus().post(new EventSWUpdate(true));
+ RxBus.INSTANCE.send(new EventConfigBuilderChange());
+ RxBus.INSTANCE.send(new EventSWUpdate(true));
})
.visibility(() -> !LoopPlugin.getPlugin().isEnabled(PluginType.LOOP)))
.validator(() -> LoopPlugin.getPlugin().isEnabled(PluginType.LOOP))
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java
index 487a80d91c..26944effbf 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWEventListener.java
@@ -1,33 +1,42 @@
package info.nightscout.androidaps.setupwizard;
import android.content.Context;
-import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.events.EventStatus;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.setupwizard.elements.SWItem;
-import info.nightscout.androidaps.setupwizard.events.EventSWLabel;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
public class SWEventListener extends SWItem {
private static Logger log = LoggerFactory.getLogger(SWEventListener.class);
+ private CompositeDisposable disposable = new CompositeDisposable();
private int textLabel = 0;
private String status = "";
TextView textView;
- Object listener;
SWDefinition definition;
- SWEventListener(SWDefinition definition) {
+ SWEventListener(SWDefinition definition, Class clazz) {
super(Type.LISTENER);
this.definition = definition;
- MainApp.bus().register(this);
+ disposable.add(RxBus.INSTANCE
+ .toObservable(clazz)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ status = ((EventStatus) event).getStatus();
+ if (textView != null)
+ textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status);
+ })
+ );
+
}
public SWEventListener label(int newLabel) {
@@ -35,16 +44,11 @@ public class SWEventListener extends SWItem {
return this;
}
- public SWEventListener initialStatus(String status) {
+ SWEventListener initialStatus(String status) {
this.status = status;
return this;
}
- public SWEventListener listener(Object listener) {
- this.listener = listener;
- return this;
- }
-
@Override
public void generateDialog(LinearLayout layout) {
Context context = layout.getContext();
@@ -53,20 +57,5 @@ public class SWEventListener extends SWItem {
textView.setId(layout.generateViewId());
textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status);
layout.addView(textView);
- if (listener != null)
- try {
- MainApp.bus().register(listener);
- } catch (Exception ignored) {}
}
-
- @Subscribe
- public void onEventSWLabel(final EventSWLabel l) {
- status = l.label;
- if (definition != null && definition.getActivity() != null)
- definition.getActivity().runOnUiThread(() -> {
- if (textView != null)
- textView.setText((textLabel != 0 ? MainApp.gs(textLabel) : "") + " " + status);
- });
- }
-
}
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java
index 1d3b867a6d..e6a4831693 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java
@@ -12,8 +12,6 @@ import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
-import com.squareup.otto.Subscribe;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -26,17 +24,22 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity;
import info.nightscout.androidaps.events.EventProfileNeedsUpdate;
import info.nightscout.androidaps.events.EventProfileStoreChanged;
import info.nightscout.androidaps.events.EventPumpStatusChanged;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientStatus;
import info.nightscout.androidaps.setupwizard.elements.SWItem;
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate;
import info.nightscout.androidaps.utils.AndroidPermission;
+import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.LocaleHelper;
import info.nightscout.androidaps.utils.OKDialog;
import info.nightscout.androidaps.utils.SP;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.disposables.CompositeDisposable;
public class SetupWizardActivity extends NoSplashAppCompatActivity {
//logging
private static Logger log = LoggerFactory.getLogger(SetupWizardActivity.class);
+ private CompositeDisposable disposable = new CompositeDisposable();
ScrollView scrollView;
@@ -48,7 +51,7 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
- LocaleHelper.onCreate(this, "en");
+ LocaleHelper.INSTANCE.update(getApplicationContext());
setContentView(R.layout.activity_setupwizard);
scrollView = (ScrollView) findViewById(R.id.sw_scrollview);
@@ -71,7 +74,8 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity {
@Override
public void onBackPressed() {
- if (currentWizardPage == 0) OKDialog.showConfirmation(this, MainApp.gs(R.string.exitwizard), this::finish);
+ if (currentWizardPage == 0)
+ OKDialog.showConfirmation(this, MainApp.gs(R.string.exitwizard), this::finish);
else showPreviousPage(null);
}
@@ -83,41 +87,41 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity {
@Override
public void onPause() {
super.onPause();
- MainApp.bus().unregister(this);
+ disposable.clear();
}
@Override
protected void onResume() {
super.onResume();
- MainApp.bus().register(this);
swDefinition.setActivity(this);
- }
-
- @Subscribe
- public void onContentUpdate(EventSWUpdate ev) {
- if (ev.redraw)
- generateLayout();
- updateButtons();
- }
-
- @Subscribe
- public void onEventNSClientStatus(EventNSClientStatus ignored) {
- updateButtons();
- }
-
- @Subscribe
- public void onEventPumpStatusChanged(EventPumpStatusChanged ignored) {
- updateButtons();
- }
-
- @Subscribe
- public void onEventProfileStoreChanged(EventProfileStoreChanged ignored) {
- updateButtons();
- }
-
- @Subscribe
- public void onEventProfileSwitchChange(EventProfileNeedsUpdate ignored) {
- updateButtons();
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventPumpStatusChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateButtons(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventNSClientStatus.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateButtons(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventProfileNeedsUpdate.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateButtons(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventProfileStoreChanged.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> updateButtons(), FabricPrivacy::logException)
+ );
+ disposable.add(RxBus.INSTANCE
+ .toObservable(EventSWUpdate.class)
+ .observeOn(AndroidSchedulers.mainThread())
+ .subscribe(event -> {
+ if (event.getRedraw()) generateLayout();
+ updateButtons();
+ }, FabricPrivacy::logException)
+ );
}
private void generateLayout() {
@@ -127,7 +131,7 @@ public class SetupWizardActivity extends NoSplashAppCompatActivity {
SWItem currentItem = currentScreen.items.get(i);
currentItem.generateDialog(layout);
}
- scrollView.smoothScrollTo(0,0);
+ scrollView.smoothScrollTo(0, 0);
}
private void updateButtons() {
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java
index 7e6ead7d72..f35decbf53 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditUrl.java
@@ -16,6 +16,7 @@ import org.slf4j.LoggerFactory;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.setupwizard.events.EventSWLabel;
import info.nightscout.androidaps.utils.SP;
@@ -62,7 +63,7 @@ public class SWEditUrl extends SWItem {
if (Patterns.WEB_URL.matcher(s).matches())
save(s.toString(), updateDelay);
else
- MainApp.bus().post(new EventSWLabel(MainApp.gs(R.string.error_url_not_valid)));
+ RxBus.INSTANCE.send(new EventSWLabel(MainApp.gs(R.string.error_url_not_valid)));
}
@Override
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java
index 6206cb0d9a..6931344acf 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.java
@@ -12,9 +12,9 @@ import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.logging.L;
+import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate;
import info.nightscout.androidaps.utils.SP;
@@ -98,9 +98,8 @@ public class SWItem {
public void run() {
if (L.isEnabled(L.CORE))
log.debug("Firing EventPreferenceChange");
- MainApp.bus().post(new EventPreferenceChange(preferenceId));
RxBus.INSTANCE.send(new EventPreferenceChange(preferenceId));
- MainApp.bus().post(new EventSWUpdate());
+ RxBus.INSTANCE.send(new EventSWUpdate(false));
scheduledEventPost = null;
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java
index 8c0be61598..e5dde501bc 100644
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWPlugin.java
@@ -17,7 +17,7 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.interfaces.PluginType;
-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.setupwizard.events.EventSWUpdate;
@@ -88,8 +88,8 @@ public class SWPlugin extends SWItem {
plugin.setFragmentVisible(pType, rb.isChecked() && makeVisible);
ConfigBuilderPlugin.getPlugin().processOnEnabledCategoryChanged(plugin, pType);
ConfigBuilderPlugin.getPlugin().storeSettings("SetupWizard");
- MainApp.bus().post(new EventConfigBuilderChange());
- MainApp.bus().post(new EventSWUpdate());
+ RxBus.INSTANCE.send(new EventConfigBuilderChange());
+ RxBus.INSTANCE.send(new EventSWUpdate(false));
});
layout.addView(radioGroup);
super.generateDialog(layout);
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java
deleted file mode 100644
index 181960ac40..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package info.nightscout.androidaps.setupwizard.events;
-
-import info.nightscout.androidaps.events.Event;
-
-public class EventSWUpdate extends Event {
- public boolean redraw = false;
-
- public EventSWUpdate() {
- }
-
- public EventSWUpdate(boolean redraw) {
- this.redraw = redraw;
- }
-}
diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt
new file mode 100644
index 0000000000..3c700cda41
--- /dev/null
+++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/events/EventSWUpdate.kt
@@ -0,0 +1,5 @@
+package info.nightscout.androidaps.setupwizard.events
+
+import info.nightscout.androidaps.events.Event
+
+class EventSWUpdate(var redraw: Boolean) : Event()
\ No newline at end of file
diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt
index 11e8f7a5a9..ef4cae3f83 100644
--- a/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt
+++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusWizard.kt
@@ -17,6 +17,7 @@ import info.nightscout.androidaps.interfaces.PumpDescription
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.configBuilder.ProfileFunctions
import info.nightscout.androidaps.plugins.general.overview.dialogs.ErrorHelperActivity
@@ -28,6 +29,7 @@ import org.json.JSONException
import org.json.JSONObject
import org.slf4j.LoggerFactory
import java.util.*
+import kotlin.math.abs
class BolusWizard @JvmOverloads constructor(val profile: Profile,
val profileName: String,
@@ -60,14 +62,11 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
var glucoseStatus: GlucoseStatus? = null
private set
- var targetBGLow = 0.0
- private set
+ private var targetBGLow = 0.0
- var targetBGHigh = 0.0
- private set
+ private var targetBGHigh = 0.0
- var bgDiff = 0.0
- private set
+ private var bgDiff = 0.0
var insulinFromBG = 0.0
private set
@@ -96,8 +95,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
var trend = 0.0
private set
- var accepted = false
- private set
+ private var accepted = false
// Result
var calculatedTotalInsulin: Double = 0.0
@@ -127,12 +125,10 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
targetBGHigh = Profile.fromMgdlToUnits(tempTarget.high, profile.units)
}
if (useBg && bg > 0) {
- if (bg >= targetBGLow && bg <= targetBGHigh) {
- bgDiff = 0.0
- } else if (bg <= targetBGLow) {
- bgDiff = bg - targetBGLow
- } else {
- bgDiff = bg - targetBGHigh
+ bgDiff = when {
+ bg in targetBGLow..targetBGHigh -> 0.0
+ bg <= targetBGLow -> bg - targetBGLow
+ else -> bg - targetBGHigh
}
insulinFromBG = bgDiff / sens
}
@@ -147,7 +143,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
}
- // Insuling from carbs
+ // Insulin from carbs
ic = profile.ic
insulinFromCarbs = carbs / ic
insulinFromCOB = if (useCob) (cob / ic) else 0.0
@@ -197,7 +193,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
log.debug(this.toString())
}
- fun nsJSON(): JSONObject {
+ private fun nsJSON(): JSONObject {
val boluscalcJSON = JSONObject()
try {
boluscalcJSON.put("profile", profileName)
@@ -260,7 +256,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
if (absorptionRate > .25)
confirmMessage += " " + MainApp.gs(R.string.slowabsorptiondetected, MainApp.gc(R.color.cobAlert), (absorptionRate * 100).toInt())
}
- if (Math.abs(insulinAfterConstraints - calculatedTotalInsulin) > pump.getPumpDescription().pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) {
+ if (abs(insulinAfterConstraints - calculatedTotalInsulin) > pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) {
confirmMessage += " " + MainApp.gs(R.string.bolusconstraintappliedwarning, MainApp.gc(R.color.warning), calculatedTotalInsulin, insulinAfterConstraints)
}
@@ -268,10 +264,10 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
}
fun confirmAndExecute(context: Context) {
- val profile = ProfileFunctions.getInstance().profile
- val pump = ConfigBuilderPlugin.getPlugin().activePump
+ val profile = ProfileFunctions.getInstance().profile ?: return
+ val pump = ConfigBuilderPlugin.getPlugin().activePump ?: return
- if (pump != null && profile != null && (calculatedTotalInsulin > 0.0 || carbs > 0.0)) {
+ if (calculatedTotalInsulin > 0.0 || carbs > 0.0) {
val confirmMessage = confirmMessageAfterConstraints(pump)
val builder = AlertDialog.Builder(context)
@@ -289,7 +285,7 @@ class BolusWizard @JvmOverloads constructor(val profile: Profile,
val loopPlugin = LoopPlugin.getPlugin()
if (loopPlugin.isEnabled(PluginType.LOOP)) {
loopPlugin.superBolusTo(System.currentTimeMillis() + 2 * 60L * 60 * 1000)
- MainApp.bus().post(EventRefreshOverview("WizardDialog"))
+ RxBus.send(EventRefreshOverview("WizardDialog"))
}
val pump1 = ConfigBuilderPlugin.getPlugin().activePump
diff --git a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java
index d592347d1b..98c4d3a071 100644
--- a/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java
+++ b/app/src/main/java/info/nightscout/androidaps/utils/DateUtil.java
@@ -93,15 +93,15 @@ public class DateUtil {
}
public static int toSeconds(String hh_colon_mm) {
- Pattern p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM | PM|)");
+ Pattern p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)");
Matcher m = p.matcher(hh_colon_mm);
int retval = 0;
if (m.find()) {
retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60;
- if ((m.group(3).equals(" a.m.") || m.group(3).equals(" AM")) && m.group(1).equals("12"))
+ if ((m.group(3).equals(" a.m.") || m.group(3).equals(" AM") || m.group(3).equals("AM")) && m.group(1).equals("12"))
retval -= 12 * 60 * 60;
- if ((m.group(3).equals(" p.m.") || m.group(3).equals(" PM")) && !(m.group(1).equals("12")))
+ if ((m.group(3).equals(" p.m.") || m.group(3).equals(" PM") || m.group(3).equals("PM")) && !(m.group(1).equals("12")))
retval += 12 * 60 * 60;
}
return retval;
@@ -185,7 +185,7 @@ public class DateUtil {
long remainingTimeMinutes = timeInMillis / (1000 * 60);
long remainingTimeHours = remainingTimeMinutes / 60;
remainingTimeMinutes = remainingTimeMinutes % 60;
- return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + "h ") : "") + remainingTimeMinutes + "')";
+ return "(" + ((remainingTimeHours > 0) ? (remainingTimeHours + MainApp.gs(R.string.shorthour) + " ") : "") + remainingTimeMinutes + "')";
}
public static String sinceString(long timestamp) {
diff --git a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java
index 3dd7fe4fd9..355623f38d 100644
--- a/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java
+++ b/app/src/main/java/info/nightscout/androidaps/utils/FabricPrivacy.java
@@ -8,10 +8,13 @@ import com.google.firebase.analytics.FirebaseAnalytics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import java.util.List;
+
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin;
/**
* Created by jamorham on 21/02/2018.
@@ -112,19 +115,23 @@ public class FabricPrivacy {
String closedLoopEnabled = MainApp.getConstraintChecker().isClosedLoopAllowed().value() ? "CLOSED_LOOP_ENABLED" : "CLOSED_LOOP_DISABLED";
// Size is limited to 36 chars
- String remote = BuildConfig.REMOTE
- .replace("https://","")
- .replace("http://","")
+ String remote = BuildConfig.REMOTE.toLowerCase()
+ .replace("https://", "")
+ .replace("http://", "")
.replace(".git", "")
.replace(".com/", ":")
.replace(".org/", ":")
.replace(".net/", ":");
MainApp.getFirebaseAnalytics().setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled);
- MainApp.getFirebaseAnalytics().setUserProperty("Language", LocaleHelper.getLanguage());
+ MainApp.getFirebaseAnalytics().setUserProperty("Language", LocaleHelper.INSTANCE.currentLanguage());
MainApp.getFirebaseAnalytics().setUserProperty("Version", BuildConfig.VERSION);
MainApp.getFirebaseAnalytics().setUserProperty("HEAD", BuildConfig.HEAD);
MainApp.getFirebaseAnalytics().setUserProperty("Remote", remote);
+ List hashes = SignatureVerifierPlugin.getPlugin().shortHashes();
+ if (hashes.size() >= 1)
+ MainApp.getFirebaseAnalytics().setUserProperty("Hash", hashes.get(0));
+
if (ConfigBuilderPlugin.getPlugin().getActivePump() != null)
MainApp.getFirebaseAnalytics().setUserProperty("Pump", ConfigBuilderPlugin.getPlugin().getActivePump().getClass().getSimpleName());
if (ConfigBuilderPlugin.getPlugin().getActiveAPS() != null)
@@ -137,7 +144,6 @@ public class FabricPrivacy {
MainApp.getFirebaseAnalytics().setUserProperty("Sensitivity", ConfigBuilderPlugin.getPlugin().getActiveSensitivity().getClass().getSimpleName());
if (ConfigBuilderPlugin.getPlugin().getActiveInsulin() != null)
MainApp.getFirebaseAnalytics().setUserProperty("Insulin", ConfigBuilderPlugin.getPlugin().getActiveInsulin().getClass().getSimpleName());
-
}
}
diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.java b/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.java
deleted file mode 100644
index d2e4c0622b..0000000000
--- a/app/src/main/java/info/nightscout/androidaps/utils/LocaleHelper.java
+++ /dev/null
@@ -1,69 +0,0 @@
-package info.nightscout.androidaps.utils;
-
-import android.content.Context;
-import android.content.SharedPreferences;
-import android.content.res.Configuration;
-import android.content.res.Resources;
-import android.preference.PreferenceManager;
-
-import java.util.Locale;
-
-/**
- * This class is used to change your application locale and persist this change for the next time
- * that your app is going to be used.
- *
- * 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/Round.java b/app/src/main/java/info/nightscout/androidaps/utils/Round.java
index ba7f7e3f86..3e312a20a9 100644
--- a/app/src/main/java/info/nightscout/androidaps/utils/Round.java
+++ b/app/src/main/java/info/nightscout/androidaps/utils/Round.java
@@ -1,14 +1,23 @@
package info.nightscout.androidaps.utils;
+import java.math.BigDecimal;
+
/**
* Created by mike on 20.06.2016.
*/
public class Round {
public static Double roundTo(double x, Double step) {
- if (x != 0d) {
- return Math.round(x / step) * step;
+ if (x == 0d) {
+ return 0d;
}
- return 0d;
+
+ //Double oldCalc = Math.round(x / step) * step;
+ Double newCalc = BigDecimal.valueOf(Math.round(x / step)).multiply(BigDecimal.valueOf(step)).doubleValue();
+
+ // just for the tests, forcing failures
+ //newCalc = oldCalc;
+
+ return newCalc;
}
public static Double floorTo(Double x, Double step) {
if (x != 0d) {
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_fragment.xml b/app/src/main/res/layout/automation_fragment.xml
index 96cbe8862b..2f24e1b70c 100644
--- a/app/src/main/res/layout/automation_fragment.xml
+++ b/app/src/main/res/layout/automation_fragment.xml
@@ -12,7 +12,7 @@
android:layout_above="@+id/automation_logView"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
- android:layout_marginBottom="-100dp" />
+ android:layout_marginBottom="15dp" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+ 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 @@
-
+
+
+
+
+
+
+
+
+
+
-
+
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
-
+
-
+
-
+
-
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/app/src/main/res/values-af-rZA/objectives.xml b/app/src/main/res/values-af-rZA/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-af-rZA/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-af-rZA/strings.xml b/app/src/main/res/values-af-rZA/strings.xml
index 0fd0888377..b6f38aa73a 100644
--- a/app/src/main/res/values-af-rZA/strings.xml
+++ b/app/src/main/res/values-af-rZA/strings.xml
@@ -5,7 +5,6 @@
-
Behandelings veiligheidMaks toelaatbare Bolus [U]Maks Toelaatbare karbs [g]
@@ -33,6 +32,7 @@
Mees onlangse algoritme vir gevorderde gebruikersWys die huidige staat van jou lus en knoppies vir mees algemene optredeToon \'n voortgesette kennisgewing met \'n kort oorsig van wat jou lus besig is om te doen
+ Definieer\'n profiel wat beskikbaar is aflyn.Bied die profiel wat jy het beskryf het in NightscoutDefinieer \'n profiel met net een tydblok.Pomp Integrasie met Accu-Chek Combo pompe, vereis dat ruffy geïnstalleer is
@@ -55,9 +55,6 @@
Monitor en beheer AndroidAPS met jou WearOS horlosie.Wys informasie van jou loop op jou xDrip+ horlosie-gesig.Afstandbeheer AndroidAPS met SMS kodes.
- Terug
- Begin
- VerifieerEenhedeDIAIC
@@ -175,9 +172,6 @@
Weergawe van NSClient nie ondersteunWeergawe van Nightscout nie ondersteunNSClient nie gevind. Rekord verlore!
- BG beskikbaar in NS
- Pompstatus beskikbaar in NS
- Per hand aksiesLOOP UIT AKSIE GESTEL DEUR BEPERKINGSBasale IABBolus beperking toegepas
@@ -220,7 +214,6 @@
TydelikeBasaalVerlengde BolusNightscout-weergawe:
- OntbreekVoorkeure uitgevoerUitvoer instellings naVoer instellings in vanaf
@@ -315,8 +308,6 @@
STAAK GEDRUKWag vir pompGaan %1$.2fU lewer
- Opstel van visualisering en monitering, en ontleed basale en verhoudings
- Verifieer dat BG beskikbaar is in Nightscout, en dat pomp insulien data opgelaai wordDie toegelate limiet is bereikGeen profiel gekiesLoop is gedeaktiveer
@@ -552,8 +543,6 @@
Wys status vlae op tuisskermDrempel waarskuwings stoor vlak [U]Drempel kritieke stoor vlak [U]
- Drempel waarskuwing battery vlak [%%]
- Drempel kritieke battery vlak [%%]IABKOBFirmware
@@ -846,8 +835,6 @@
ProfileSwitch ontbreek. Doen \'n profiel skakelaar of druk \"Aktiveer profiel\" in die LokaleProfiel.Bolus tellingTBR telling
- Objektief %1$d mie begin nie
- Objektief %1$d nie klaarPomp is nie tydelike basale bekwameGeen geldige basale tempo gelees van pompGeslote lus modus in voorkeure gedeaktiveer
@@ -968,7 +955,6 @@
Voltooi, baie mooi gedoen!Nog nie voltooi nieTydsverloop
- %1$d. DoelwitPoctechOntvang BG waardes van Poctech toepassingOntvang BG waardes vanaf Tomato toep (MiaoMiao toestel)
@@ -1152,8 +1138,6 @@
Laai tydelike basale opLaai profiel veranderings, tydelike teikens opLaai BG toetse op
- Daglig spaar tyd verandering in 24 h of minder
- Daglig spaar tyd het verander minder as 3 ure terug - Geslote lus afgeskakelinterne berging beperkingBevry ten minste %1$d MB van intene stoorspasie! Lus gedeaktiveer!Verkeerde formaat
@@ -1347,18 +1331,27 @@
Verkry Tydelike BasaleStel Tydelike BasaleStel Bolus
+ Verander profiel na
+ Verander profiel na %1$s
+ Laaste konneksie na pomp
+ Laaste konneksie na pomp [minute gelede]
+ Vorige konneksie na pomp %1$s %2$s min terug
+ Stuur\'n SMS: %1$s
+ Stuur SMS na alle fone in voorkeure
+ Stuur\'n SMS met die teksBolus beperking aangewend: %2$.2fU to %3$.2fU]]>%1$.0f / %2$d U
-
- %1$d dae
- %1$d dae
-
-
- %1$d uur
- %1$d ure
-
-
- %1$d minuut
- %1$d minute
-
+ Laai tans...
+ Sluimer
+ Tyd reeks
+ Tyd is tussen %1$s en %2$s
+ Tussen
+ Maak toe
+ Ongeldig boodskap teks
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Bolus slimjan
+ min
diff --git a/app/src/main/res/values-bg-rBG/objectives.xml b/app/src/main/res/values-bg-rBG/objectives.xml
new file mode 100644
index 0000000000..677b26f326
--- /dev/null
+++ b/app/src/main/res/values-bg-rBG/objectives.xml
@@ -0,0 +1,64 @@
+
+
+
+ Назад
+ Старт
+ Потвърждаване
+ Цел %1$d
+ Цел %1$d не е стартирана
+ Цел %1$d не е завършена
+ Настройка на визуализацията и наблюдението, а също и анализиране на базалните нужди и коефициенти
+ Потвърждаване, че КЗ се вижда в Найтскаут и данните за помпата се качват там
+ Стартиране в режим Отворен кръг (Open loop)
+ Работа в режим \"Отворен кръг\" за няколко дни и ръчно въвеждане на много временни базали. Настройте и използвайте временни и стандартни временни цели (напр. за активни въглехидрати или такива при хипо)
+ Опитайте се да разбирате по-добре вашият APS в режим \"Отворен кръг\", включително препоръчваните временни базали
+ Определяне на макс. лимит на базалния инсулин и настройване в помпата и програмата
+ Стартиране на \"Затворен кръг\" с изключване на базал при ниска КЗ
+ Стартиране на \"Затворен кръг\" с макс. IOB=0 без твърде много събития тип ниска КЗ
+ Настройване на \"Затворен кръг\" чрез повишаване на максималният IOB над 0 и понижаване на целевите нива на КЗ
+ Прекарайте няколко дни по този начин, като поне една нощ нямате аларма за ниска КЗ
+ Настройване на базалния инсулин и коефициенти ако е необходимо и активиране на auto-sens
+ Една седмица успешно дневно използване с редовно въвеждане на въглехидрати
+ Активиране на допълнителни функции за дневно използване, включително и advanced meal assist (АМА)
+ Добавяне на допълнителни функции за използване през деня, като SMB
+ Трябва да прочетете wiki и увеличите maxIOB за да може SMB да работи добре! Добро начало е maxIOB = средния болус за хранене + 3 пъти най-големия базал от профила
+ КЗ да се вижда в NS
+ Статуса на помпата да е достъпен в NS
+ Ръчно приложени
+ Изпълнено: %1$s
+ Научете се да управлявате AndroidAPS
+ Извършете различни действия в AndroidAPS
+ Настройте профила на 90% за 10 минути (задръжте върху името на профила в таб Общ)
+ Симулирайте душ. Изключете помпата за 1 час (задръжте върху Отворен кръг)
+ ... и отново я свържете по същия начин
+ Създаване на различна временна цел с продължителност 10 мин. (задръжте върху сегашната си цел)
+ В Конфигурация включете плъгин Действия и го направете видим, след което го изберете от списъка с табове.
+ Отворете съдържанието на Цикъл плъгина.
+ Използвайте функцията за удължаване на периода на графиката, като задържите върху нея.
+ Въведи
+ Ако сте били потребител на OpenAPS и НС има най-малко 3 месеца цикъл на данни, можете да изпращате по електронна поща objectives@androidaps.org с адрес на НС, за да поискате код за заобикаляне на останалите цели. Въведете кода, получен от разработчици
+ Код приет!
+ Неправилен код
+ Докажете знанията си
+ Отговорете правилно на въпросите
+ Изключено до: %1$s
+ Грешен отговор!
+ Следващия неотговорен
+ Код (request code): %1$s
+ (отбележете всички правилни отговори)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ Не може да се вземе времето
+ Задачите не са изпълнени
+
+ %1$d дни
+ %1$d дни
+
+
+ %1$d часа
+ %1$d часа
+
+
+ %1$d минута
+ %1$d минути
+
+
diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml
index 0d89d0b8b0..bf88d217b4 100644
--- a/app/src/main/res/values-bg-rBG/strings.xml
+++ b/app/src/main/res/values-bg-rBG/strings.xml
@@ -5,7 +5,6 @@
-
Настройки на сигурносттаМаксимален инсулин при болус [единици]Максимални въглехидрати [гр]
@@ -57,9 +56,6 @@
Наблюдавайте и контролирайте AndroidAPS, от вашия WearOS часовник.Покажи информация за вашия APS на xDrip + циферблат на часовник.Дистанционно управление AndroidAPS чрез използване на SMS команди.
- Назад
- Стартирай
- ПровериЕдинициDIA (Време на действие на инсулина):IC (Инсулин/въглехидр.):
@@ -102,6 +98,7 @@
ПрофилДанни за храненеРезултат
+ Резултат: %1$s %2$sНяма данни за КЗНе се изисква промянаИскане
@@ -177,9 +174,6 @@
Несъвместима версия на NSClientНесъвместима версия на NightscoutNSClient не е открит. Записът е загубен!
- КЗ да се вижда в NS
- Статуса на помпата да е достъпен в NS
- Ръчно приложениLOOP Е СПРЯН ОТ ОГРАНИЧЕНИЯТАБазален IOBПриложено ограничение на болус
@@ -222,7 +216,7 @@
Временен базалУдължен болусNightscout версия:
- Липсва
+ Нужни %1$dгНастройките са експортираниЕкспортирай настройките в Импорт на настройки от
@@ -266,11 +260,23 @@
Разрешени телефонни номера+XXXXXXXXXX;+YYYYYYYYYYЗа да доставите болус от %1$.2fЕ отговорете с код %2$s
+ За да стартирате болус от %1$.2fЕ отговорете с код %2$s
+ Зa zадаване на временна цел %1$s отговорете с код %2$s
+ За да спрете временната цел отговорете с код %1$s
+ За да изключите услугата за отдалечен SMS контрол отговорете с код %1$s.\n\nИмайте предвид, че можете да го активирате само от AAPS смартфона.
+ Отдалечен SMS контрол е изключен. Можете да го включите от AndroidAPS телефона.За да изпратите калибрация %1$.2f отговорете с код %2$sБолус отказан
+ Минимален брой минути, в които трябва да мине между един отдалечен болус и следващия
+ Колко най-малко минути трябва да минат два болуса
+ За вашата сигурност, променете тази настройка, трябва да добавите най-малко 2 телефонни номера.Болус от %1$.2fЕ доставен успешноЩе стартира %1$.2fЕ болусБолус от %1$.2fЕ доставен успешно
+ Болус от %1$.2fЕ доставен успешно
+ Временна цел от %1$s за %2$d минути
+ Временна цел от %1$s за %2$d минути стартирана успешно
+ Временна цел успешно спрянаСтартирам %1$.2fЕПозволи отдалечени команди чрез SMSПръст
@@ -317,21 +323,6 @@
Натиснат е СТОП!Очаква помпатаЩе стартира %1$.2fЕ болус
- Настройка на визуализацията и наблюдението, а също и анализиране на базалните нужди и коефициенти
- Потвърждаване, че КЗ е достъпна в Найтскаут и данните за помпата се качват там
- Стартиране в режим Отворен кръг (Open loop)
- Работа в режим \"Отворен кръг\" за няколко дни и ръчно въвеждане на много временни базали. Настройте и използвайте временни и стандартни временни цели (напр. за активни въглехидрати или такива при хипо)
- Опитайте се да разбирате по-добре вашият APS в режим \"Отворен кръг\", включително препоръчваните временни базали
- Определяне на макс. лимит на базалния инсулин и настройване в помпата и програмата
- Стартиране на \"Затворен кръг\" с изключване на базал при ниска КЗ
- Стартиране на \"Затворен кръг\" с макс. IOB=0 без твърде много събития тип ниска КЗ
- Настройване на \"Затворен кръг\" чрез повишаване на максималният IOB над 0 и понижаване на целевите нива на КЗ
- Прекарайте няколко дни по този начин, като поне една нощ нямате аларма за ниска КЗ
- Настройване на базалния инсулин и коефициенти ако е необходимо и активиране на auto-sens
- Една седмица успешно дневно използване с редовно въвеждане на въглехидрати
- Активиране на допълнителни функции за дневно използване, включително и advanced meal assist (АМА)
- Добавяне на допълнителни функции за използване през деня, като SMB
- Трябва да прочетете wiki и увеличите maxIOB за да може SMB да работи добре! Добро начало е maxIOB = средния болус за хранене + 3 x най-големия базал от профилаДостигнахте лимитаНяма избран профилAPS е деактивиран
@@ -345,10 +336,13 @@
За да стартирате базал от %1$.2fЕ/ч за %2$d мин отговорете с код %3$sЗа да превключите профила към %1$s %2$d%% отговорете с код %3$sЗа да започнете удължен болус %1$.2fЕ за %2$d мин отговорете с код %3$s
+ За да въведете %1$dг в %2$s отговорете с код %3$sЗа да стартирате базал от %1$d%Е/ч за %2$d мин отговорете с код %3$sЗа да спрете APS за %1$d минути отговорете с код %2$sВременен базал от %1$.2fЕ/ч за %2$d мин стартиран успешноУдължен болус %1$.2fU за %2$d мин стартиран успешно
+ Въглехидрати %1$dг въведени
+ Въвеждане на%1$dг въглехидрати - НЕУСПЕШНОВременен базал от %1$d%Е/ч за %2$d мин стартиран успешноНеуспешно стартиране на временен базалНеуспешно стартиране на удължен болус
@@ -569,8 +563,8 @@
Показвай подробни статус светлини за канула, инсулин, сензор, резервоар и батерията на началния екран.Ниво за аларма за останал инсулин в резервоара [Е]Критично ниво на останал инсулин в резервоар [Е]
- Ниско ниво на батерията под [%%]
- Критично ниво на батерията под [%%]
+ Аларма при заряд на батерия под [%]
+ Критично ниво на батерията под [%]IOBСОВФърмуер
@@ -701,6 +695,7 @@
гр.мин.ч.
+ д]]>килодж.Ен
@@ -729,6 +724,7 @@
Настройки при качване на КЗ към NightscoutПоказвай подробна делтаПоказвай делта с още един десетичен знак
+ Максимум минути СМБМаксимални минути за ограничаване на базала от SMBНеподдържан фърмуер на помпатаИзпращай данни за КЗ към xDrip+
@@ -864,8 +860,6 @@
Смяната на профила не е отразена. Моля, направете превключване на потребителския профил или натиснете \"Активирай профил\" в Локален профил.Брой болусиБрой TBR
- ЦЕЛ %1$d не е стартирана
- ЦЕЛ %1$d не е завършенаПомпата не поддържа временен базалНяма валиден базал в помпатаЗатворения кръг е забранен в настройките
@@ -987,7 +981,6 @@
Приключихме, Браво!Все още не сме неприключилиИзминало време
- %1$d. ЦелPoctechПолучавай данни за КЗ от Poctech апликацията.Получавай КЗ от Tomato апликация (устройство МяоМяо)
@@ -1260,6 +1253,8 @@
Не е избрано (общ)АлкалниЛитиева
+ NiZn батерия
+ Болус/Корекция подробноСКАНИРАЙСТОП
@@ -1368,6 +1363,15 @@
Получи временния базалПриложи временен базалСтартирай болус
+ Смени профила на
+ Смени профила на %1$s
+ Последно свързване към помпа
+ Последнa връзкa с помпата [минути]
+ Последна връзка с помпата е %1$s %2$s минути преди
+ Изпращане на SMS с текст %1$s
+ Изпрати SMS до всички телефони от настройките
+ Изпрати SMS с текст
+ %2$+.2fг Е]]>Ограничение на болуса: %2$.2fЕ на %3$.2fЕ]]>!!!!! Бавна абсорбция на въглехидрати: %2$d%% от времето. Проверете въведените данни. Може да има голяма грешка !!!!!]]>%1$.0f / %2$d Е
@@ -1375,38 +1379,19 @@
Калкулатора изчислява нужния инсулин, но само тази част ще бъде доставена. Полезно със SMB алгоритъма.Зареждане ...Отложи
- Изпълнено: %1$s
- Научете се да управлявате AndroidAPS
- Извършете различни действия в AndroidAPS
- Настройте профила на 90% за 10 минути (задръжте върху името на профила в таб Общ)
- Симулирайте душ. Изключете помпата за 1 час (задръжте върху Отворен кръг)
- ... и отново я свържете по същия начин
- Създаване на различна временна цел с продължителност 10 мин. (задръжте върху сегашната си цел)
- В Конфигурация включете плъгин Действия и го направете видим, след което го изберете от списъка с табове.
- Отворете съдържанието на Цикъл плъгина.
- Използвайте функцията за удължаване на периода на графиката, като задържите върху нея.
- Въведи
- Въведете кода, получен от разработчиците да прескочите останалите цели
- Код приет!
- Неправилен код
- Докажете знанията си
- Отговорете правилно на въпросите
- Изключено до: %1$s
- Грешен отговор!
- Следващия неотговорен
+ Времеви диапазон
+ Часът е между %1$s и %2$s
+ Между Затвори
- Код (request code): %1$s
- (отбележете всички правилни отговори)
-
- %1$d дeн
- %1$d дни
-
-
- %1$d часа
- %1$d часа
-
-
- %1$d минута
- %1$d минутa
-
+ Повишавам максималната стойност на базал, защото тя е по-ниска от най-високата в базалния профил
+ Невалиден текст на съобщение
+ %1$s ISF: %2$.1f
+ %1$.0fгр Чувств: %2$.1f
+ %1$.1fгр Чувств: %2$.1f
+ %1$d %%
+ Болус калкулатор
+ мин
+ %1$dг
+ Вкл
+ Изкл
diff --git a/app/src/main/res/values-cs-rCZ/exam.xml b/app/src/main/res/values-cs-rCZ/exam.xml
index 503870e0b7..a65151aee8 100644
--- a/app/src/main/res/values-cs-rCZ/exam.xml
+++ b/app/src/main/res/values-cs-rCZ/exam.xml
@@ -3,65 +3,66 @@
Co je pravda o DIA?Téma: Doba trvání účinku inzulínu
- Předem stanovené minimum je 3 hodiny.
- Předem stanovené minimum je 5 hodin.
+ Minimální hodnota je 3 hodiny.
+ Minimální hodnota je 5 hodin.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#inzulin
- Je rovno parametru DIA používaném ve vaší pumpě.
+ Význam se shoduje s parametrem DIA používaným ve vaší pumpě.Musíte určit svou individuální hodnotu (ale ne méně než 5 hodin).Téma: Dočasný cíl Hypoglykémie
- Proč je užitečné nastavit dočasný cíl pro hypoglykémii?
- Prevence nízké glykémie.
- Pomoci zotavit se z nízké glykémie.
- Aby se po vzestupu glykémie z rychlých sacharidů po řešení hypoglykémie zabránilo vydávání SMB.
+ Co je primárním důvodem k nastavení dočasného cíle Hypoglykémie?
+ Zabránit nízké glykémii, pokud je již spuštěn nulový dočasný bazál.
+ Aby se zabránilo AAPS podání příliš velkého množtví inzulínu po růstu glykémie způsobenému rychlými sacharidy použtými k léčbě hypoglykémie.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/temptarget.htmlKterý profil lze použít a konfigurovat offline?Téma: Offline profilNS profil může být použit, ale ne nastaven.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#profileTéma: Odpojení od pumpy
- Co dělat, když sundáte pumpu?
- Klikněte na možnost Odpojit pumpu a dejte smyčce vědět, že do vašeho těla nebude dodáván inzulín.
- Ve smyčce nic neměňte, jen odpojte pumpu.
+ Co se má provést při odpojení pumpy?
+ Klepněte na \"Odpojit pumpu\" tak, aby AAPS vědělo, že není dodáván žádný inzulín.
+ Klepněte na tlačítko \"Pozastavit smyčku\", aby AAPS zastavil smyčku na dobu, co je pumpa odpojená.
+ Neměňte nic v AAPS, jen odpojte pumpu.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#dalsi-nastaveniTéma: Nastavení AndroidAPSJaké jsou nejlepší postupy pro zálohování vašich nastavení?Exportovat je lokálně z nabídky Údržba.Uložte exportovaný soubor do jiného umístění, např. e-mail, Dropbox, Disk Google…Exportovat je ihned po instalaci AAPS.
- Exportovat je po každé změně nastavení.
+ Vyexportujte je po provedení změn v nastavení.
+ Exportujte je po dokončení cíle.Exportovat je, jakmile dokončíte počáteční nastavení.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/ExportImportSettings.htmlhttps://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#jake-vybaveni-pro-pripad-nouze-se-doporucuje-brat-s-sebouTéma: Šum dat ze senzoru
- Co dělat, když vidíte, že hodnoty CGM poskakují?
+ Co by mělo být provedeno v případě, že CGM data poskakují?Nic, smyčka se s tím vypořádá.
- Pozastavte uzavřenou smyčku, abyste předešli předávkování.
+ Zakažte smyčku, abyste se vyhnuli předávkování inzulínem.Vyměňte senzor.Vypnout telefon.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#vyhlazovani-zarusenych-dat-glykemii
- Zkontrolujte, zda vaše aplikace CGM vyhlazuje data.
+ Ověřte, že vaše aplikace CGM vyhlazuje gklykémie.Téma: CvičeníJak můžete pomoci systému vypořádat se s cvičením?
- Nastavit dočasný cíl aktivity.
+ Použití funkce dočasný cíl.Přepnout na profil pod 100 %.Přepnout na profil nad 100 %.Zastavit smyčku.Nastavit dočasný cíl aktivity před zahájením cvičení.
- Nastavit dočasný cíl aktivity po začátku cvičení.
+ Nastavení dočasného cíle aktivity až po zahájení cvičení vede k horšímu výsledku, než kdyby byl spuštěn před.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/temptarget.html#docasny-cil-pri-pohybove-aktivite
- Téma: Pozastavená smyčka
- Dostávám inzulín, když je smyčka pozastavena?
- Ano, běžný bazál.
+ Téma: Zakázaná/Pozastavená smyčka
+ Dostávám inzulín, když je smyčka zakázána/pozastavena?
+ Ano, bazální inzulín se dále dodává.Ne, podávání inzulínu je zastaveno.Téma: Testování bazálu, ISF a ICKdy mám ověřit hodnoty bazálů, ISF a IC?Než začnu provozovat smyčku.
- Když mám pravidelné hypoglykémie.
- Když mám pravidelné hyperglykémie.
+ Pokud máte často nízké glykémie.
+ Pokud máte často vysoké glykémie.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#nastaveni-androidapsTéma: Nezbytné předpokladyCo potřebuji?
- Zjistit správný profil (bazály, IC, ISF, DIA).
+ Ověřené informace o profilu (Bazál, IC, ISF, DIA).Počítač pro vytvoření APK.Podporovaný telefon.Auto.
@@ -69,7 +70,7 @@
Účet Tidepool.Účet Google.Účet Github.
- Je třeba být vývojářem pro Android.
+ Zkušenosti s vývojem pro Android.Pumpu MiniMed 670G.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Module/module.htmlChytré hodinky.
@@ -77,35 +78,35 @@
Téma: Aktualizace AndroidAPSCo je pravda?Musíte mít nainstalován Git.
- Aktualizovat ihned po uvolnění nové verze.
- Můžete použít stejné podpisové klíče.
+ Aktualizujte ihned, jakmile se uvolní nová verze a bude mít dostatek času na to, aby to bylo možné provést.
+ Měli byste používat stejné podpisové klíče.Nikdy neaktualizujte, pokud systém funguje dobře.Požádejte kamaráda o novou verzi APK.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Installing-AndroidAPS/Update-to-new-version.htmlTéma: Odstraňování problémůKde hledat pomoc?Připojte se do facebookové skupiny AndroidAPS.
- Navštivte AndroidAPS Wiki.
+ Přečtěte si dokumentaci AndroidAPS.Navštivte místnost AndroidAPS na Gitteru.Navštivte Google podporu AndroidAPSPromluvte si se svým diabetologem.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/index.html#poradce-pri-potizichhttps://www.facebook.com/groups/AndroidAPSUsers/https://gitter.im/MilosKozak/AndroidAPS
- Téma: Inzulín
- Kterou značku inzulínu lze použít s modulem Ultra-Rychlý-Oref?
+ Téma: Inzulínové pluginy
+ Jaký druh inzulínu může být použit s pluginem \'Ultra-Rychlý-Oref\'?Fiasp®NovoRapid®Humalog®Actrapid®https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#inzulin
- Téma: Modul citlivosti
- Který plugin pro detekci citlivosti má uživatelem definovaný časový rozsah pro detekci?
+ Téma: Pluginy citlivosti
+ Který algoritmus citlivosti má konfigurovatelnou dobu detekce?https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#detekce-citlivostiKterý modul citlivosti musí být použit pro funkci UAM (rozpoznání neoznámeného jídla)?
- Téma: Špatně zadané sacharidy
- Vidíte, že jste chybně zadali sacharidy. Co byste měli udělat?
- Jděte do Ošetření, smažte špatně zadané sacharidy a vložte nové sacharidy.
+ Téma: Chyby při zadávání sacharidů
+ Co byste měli udělat, pokud jste zadali chybně sacharidy?
+ V Ošetřeních odstraňte chybnou položku. Zadejte nové sacharidy.Přidat falešný inzulin pomocí funkce DoplňováníTéma: Jídlo s tukem a bílkovinamiCo dělat, když jídlo obsahuje vysoké množství tuků a/nebo bílkovin?
@@ -113,27 +114,27 @@
Přepočítejte tuky a bílkoviny na sacharidy a přidejte je do výpočtu bolusu.Použijte prodloužený bolus, abyste pokryli tuky a bílkoviny.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Extended-Carbs.html
- Téma: Monitorování dětí
+ Téma: Vzdálené sledováníJak můžete na dálku monitorovat AAPS svého dítěte?Pomocí stránky Nightscout.
- Aplikace Dexcom Follow, pokud používáte originální aplikaci Dexcom.
+ Dexcom follow, pokud používáte originální aplikaci Dexcom (pouze hodnoty glykémie).Aplikace Dexcom Follow, pokud používáte aplikaci xDrip.Aplikace xDrip v režimu sledování.Aplikace Loop na iPhone.Aplikace Spike na iPhone.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Children/Children.htmlTéma: Citlivost na inzulín
- Zvýšení hodnoty citlivosti bude mít za následek méně vydaného inzulinu, když se budete snažit snížit glykémii pomocí bolusové kalkulačky.
- Snížení hodnoty citlivosti bude mít za následek méně dodaného inzulinu, když se budete snažit snížit glykémii pomocí bolusové kalkulačky.
- Změna citlivosti nemá žádný vliv na množství inzulínu, který je vydán prostřednictvím AAPS při pokusu o korekci hyperglykémie.
+ Vyšší hodnoty ISF vedou k menší dávce inzulínu při korigování vysoké glykémie.
+ Nižší hodnoty ISF vedou k menší dávce inzulínu při korigování vysoké glykémie.
+ Změna hodnoty ISF nemá vliv na dávku inzulínu při korigování vysoké glykémie.Musíte zadat citlivost v Nastavení.Změna hodnoty citlivosti ve vašem profilu postačuje k tomu, aby se tato změna použila.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#korekcni-faktor-citlivost-na-inzulin-isf-mmol-l-u-nebo-mg-dl-uhttps://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html
- Téma: Hodnota inzulino-sacharidového poměru
- Zvýšení inzulino-sacharidového poměru bude mít za následek méně vydaného inzulinu na stejné množství sacharidů.
- Snížení hodnoty inzulino-sacharidového poměru bude mít za následek méně vydaného inzulinu na stejné množství sacharidů.
- Předpokládejme, že máte 0 COB. Změna inzulino-sacharidového poměru povede k jinému množství inzulínu vydanému pro korekci glykémie.
+ Téma: Inzulino-sacharidový poměr
+ Vyšší hodnoty IC vedou k menší dávce inzulínu pro stejné množství sacharidů.
+ Nižší hodnoty IC vedou k menší dávce inzulínu pro stejné množství sacharidů.
+ Pokud máte 0 COB změna inzulino-sacharidového poměru povede k jinému množství inzulínu vydanému pro korekci glykémie.Inzulino-sacharidový poměr se bude lišit podle toho, zda počítáte výměnnou jednotku jako 10 g nebo jako 12 g sacharidů.Inzulino-sacharidový poměr vyjadřuje: kolik výměnných jednotek pokryje 1 jednotka inzulinu.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#inzulino-sacharidovy-pomer-cr-g-u
@@ -145,21 +146,24 @@
Hodnota inzulino-sacharidového poměru bude o 10 % nižší.Hodnota citlivosti bude o 10 % vyšší.Hodnota citlivosti bude o 10 % nižší.
- Celkově dostanete o 10 % inzulinu méně.
+ Celkově dostanete o cca 10 % inzulinu méně.Cíl bude o 10 % vyšší.Cíl bude o 10 % nižší.Pouze dolní cíl bude o 10 % nižší.https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html?highlight=p%C5%99epnut%C3%AD%20profilu
- Chci přepnout profil, protože jsem se musel(a) probudit o 1 h dříve než obvykle, takže dává větší smysl oznámit tuto změnu prostřednictvím časového posunu profilu. Jaké číslo mám použít?
- 1
- -1
+ Pokud se probudíte o 1h dříve než obvykle, jak byste měli oznámit AAPS tuto změnu?
+ Proveďte přepnutí profilu s posunem času 1
+ Proveďte přepnutí profilu s posunem času -1https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html#posun-casu
- 60
- -60
+ Proveďte přepnutí profilu s posunem času 60
+ Proveďte přepnutí profilu s posunem času -60https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Module/module.html#spravny-individualni-algoritmus-davkovani-pro-lecbu-vaseho-diabetuTéma: Pomoc s bazályKam jít pro pomoc s bazály apod.K Vašemu lékařiGoogleFacebook
+ Jiné léky
+ AAPS snižuje bazály na zvýšení hladiny cukru v krvi. Léky ze skupiny inhibitorů SGLT2 (glifloziny) mohou zabránit očekávanému zvýšení hodnoty glykémie, a tak mohou produkovat nebezpečný nedostatek inzulínu (ketoacidózu).
+\nSpolečné značky jsou: Invokana ®, Forxiga ®, Jardiance ®, Steglatro ®, Suglat ®, Apleway ®, Deberza ®, Synjardy ®, Vokanamet ®, Xigduo ®.\n\n. Tímto slibuji, že tyto léky neberu při používání AAPS nebo deaktivuji smyčku před užíváním těchto léků.
diff --git a/app/src/main/res/values-cs-rCZ/objectives.xml b/app/src/main/res/values-cs-rCZ/objectives.xml
new file mode 100644
index 0000000000..259403ad81
--- /dev/null
+++ b/app/src/main/res/values-cs-rCZ/objectives.xml
@@ -0,0 +1,74 @@
+
+
+
+ Zpět
+ Začátek
+ Kontrola
+ %1$d. cíl
+ Výukový cíl %1$d nespuštěn
+ Výukový cíl %1$d nedokončen
+ Nastavit vizualizaci a monitoring, analyzovat bazály a koeficienty
+ Zkontrolovat, zda jsou glykémie a údaje z pumpy viditelné v Nightscoutu
+ Začít s otevřenou smyčkou
+ Provozovat několik dní otevřenou smyčku a ručně potvrzovat doporučené dočasné bazály. Nastavovat a používat dočasné cíle (např. pro sport nebo hypo)
+ Porozumět otevřené smyčce, včetně jejích doporučení ohledně dočasných bazálů
+ Na základě předchozích zkušeností rozhodnout, jaký je třeba maximální bazál a nastavit ho v pumpě a v aplikaci
+ Spustit uzavřenou smyčku pouze se zastavováním při nízké glykémii
+ Spustit uzavřenou smyčku s max IOB = 0 na několik dní s minimem nutných korekcí na nízkou glykémii
+ Zapnout uzavřenou smyčku, zvyšovat max IOB nad 0 a snižovat cílovou glykémii
+ Provozovat smyčku několik dní s alespoň jednou nocí bez alarmů na nízkou glykémii
+ Upravit bazály a poměry, bude-li to potřeba, a povolit automatickou detekci citlivosti na inzulín
+ Jeden týden úspěšného používání s běžným příjmem sacharidů
+ Povolení doplňkový funkcí pro každodenní použití, jako např. pokročilý jídelní asistent (AMA)
+ Povolit další funkce pro běžné používání jako SMB
+ Přečíst si dokumentaci a zvýšit maximální IOB, aby mohlo SMB fungovat. Pro začátek se dá použít velikost běžného bolusu + 3x maximální denní bazál
+ Glykémie dostupná v NS
+ Stav pumpy dostupný v NS
+ Ručně spuštěno
+ Splněno: %1$s
+ Naučte se, jak ovládat AndroidAPS
+ Provádějte v AndroidAPS různé akce
+ Nastavte profil na 90 % na 10 min (Dlouhé stisknutí názvu profilu na obrazovce Přehled)
+ Předstírejte, že se jdete sprchovat. Odpojte pumpu na 1 h (Dlouze přidržte tlačítko Otevřená smyčka)
+ ...a stejným způsobem ji znovu připojte
+ Vytvořte vlastní dočasný cíl s trváním 10 min (Dlouze přidržte aktuální cíl)
+ Na kartě Konfigurace povolte modul Akce, aktivujte jeho zobrazení a zobrazte jeho obsah z horní nabídky
+ Zobrazte obsah modulu Smyčka
+ Přepněte režim zobrazení dlouhým stisknutím grafu glykémie
+ Zadat
+ Pokud jste byli dříve uživateli OpenAPS a váš NS má alespoň 3 měsíce dat z používání smyčky, můžete poslat e-mail na adresu objectives@androidaps.org s adresou svého NS a požádat o kód, pomocí něhož budete moci obejít zbývající cíle. Zadejte kód získaný od vývojářů.
+ Kód přijat
+ Neplatný kód
+ Prokažte své znalosti
+ Studujte a správně zodpovězte otázky
+ Odpovídání zakázáno do: %1$s
+ Špatná odpověď!
+ Další nedokončená
+ Kód žádosti: %1$s
+ (zatrhněte všechny správné odpovědi)
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#co-delat-pri-sprchovani-a-koupani
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#hlavni-stranka
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#konfigurace
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#hlavni-stranka
+ Chybí připojení k internetu
+ Nepodařilo se načíst čas
+ Požadavky cíle nejsou splněny
+
+ %1$d den
+ %1$d dnů
+ %1$d dnů
+ %1$d dnů
+
+
+ %1$d hodina
+ %1$d hodin
+ %1$d hodin
+ %1$d hodin
+
+
+ %1$d minuta
+ %1$d minut
+ %1$d minut
+ %1$d minut
+
+
diff --git a/app/src/main/res/values-cs-rCZ/strings.xml b/app/src/main/res/values-cs-rCZ/strings.xml
index bde8479327..2e524d4586 100644
--- a/app/src/main/res/values-cs-rCZ/strings.xml
+++ b/app/src/main/res/values-cs-rCZ/strings.xml
@@ -5,7 +5,6 @@
-
Bezpečnost zadání ošetřeniMaximální povolený bolus [U]Maximální počet sacharidů [g]
@@ -57,9 +56,6 @@
Zobrazování stavu a řízení AndroidAPS z hodinek s WearOSZobrazování informací o smyčce na xDrip+ watchface.Vzdálené řízení pomocí SMS příkazů
- Zpět
- Začátek
- KontrolaJednotkyDoba působnosti inzulínuInzulínosacharidový poměr
@@ -102,6 +98,7 @@
ProfilData o jídleVýsledek
+ Výsledek: %1$s %2$sNedostupná data o glykémiíchZměna nepožadovánaPožadavek
@@ -177,9 +174,6 @@
Nepodporovaná verze NSClientNepodporovaná verze NightscoutuNSClient není nainstalován. Záznam je ztracen!
- Glykémie dostupná v NS
- Stav pumpy dostupný v NS
- Ručně spuštěnoSMYČKA ZAKÁZÁNA OMEZENÍMBazální IOBAplikováno omezení bolusu
@@ -222,7 +216,7 @@
Dočasný bazálProdloužený bolusVerze Nightscoutu:
- Chybí
+ Chybí %1$dgNastavení exportovánoExportovat nastavení doImportovat nastavení z
@@ -266,11 +260,23 @@
Povolená tel. čísla+XXXXXXXXXX;+YYYYYYYYYYK potvrzení bolusu %1$.2fU odpověz SMS s kódem %2$s
+ Pro potvrzení bolusu na jídlo %1$.2fU odpovězte pomocí SMS s kódem %2$s
+ Pro nastavení dočasného cíle %1$s odpovězte pomocí SMS s kódem %2$s
+ Pro zrušení dočasného cíle odpovězte pomocí SMS s kódem %1$s
+ Chcete-li deaktivovat Vzdálené řízení přes SMS, odpovězte pomocí SMS s kódem %1$s.\n\nUpozornění: tuto funkci budete moci znovu aktivovat pouze z telefonu s hlavní verzí AAPS.
+ Služba Vzdáleného řízení přes SMS zastavena. Chcete-li ji znovu aktivovat, použijte telefon s hlavní verzí AAPS.Odeslání kalibrace %1$.2f potvrďte kódem %2$sChyba při aplikování bolusu
+ Minimální počet minut, které musí uplynout mezi dvěma bolusy podanými přes vzdálené řízení
+ Kolik minut (minimálně) musí uplynout mezi dvěma bolusy
+ Úprava tohoto nastavení v zájmu vaší bezpečnosti vyžaduje, abyste zadali alespoň 2 telefonní čísla.Bolus %1$.2fU aplikován úspěšněPodávání %1$.2fU inzulínuBolus %1$.2fU aplikován úspěšně
+ Bolus na jídlo %1$.2fU byl úspěšně aplikován
+ Cíl %1$s na %2$d minut
+ Cíl %1$s na %2$d minut byl úspěšně nastaven
+ Dočasný cíl byl úspěšně zrušenAplikováno %1$.2fUPovolit posílání příkazů přes SMSGlukoměr
@@ -317,21 +323,6 @@
STISKNUTO STOPČekání na pumpuPodávání %1$.2fU inzulínu
- Nastavit vizualizaci a monitoring, analyzovat bazály a koeficienty
- Zkontrolovat, zda jsou glykémie a údaje z pumpy viditelné v Nightscoutu
- Začít s otevřenou smyčkou
- Provozovat několik dní otevřenou smyčku a ručně potvrzovat doporučené dočasné bazály. Nastavovat a používat dočasné cíle (např. pro sport nebo hypo)
- Porozumět otevřené smyčce, včetně jejích doporučení ohledně dočasných bazálů
- Na základě předchozích zkušeností rozhodnout, jaký je třeba maximální bazál a nastavit ho v pumpě a v aplikaci
- Spustit uzavřenou smyčku pouze se zastavováním při nízké glykémii
- Spustit uzavřenou smyčku s max IOB = 0 na několik dní s minimem nutných korekcí na nízkou glykémii
- Zapnout uzavřenou smyčku, zvyšovat max IOB nad 0 a snižovat cílovou glykémii
- Provozovat smyčku několik dní s alespoň jednou nocí bez alarmů na nízkou glykémii
- Upravit bazály a poměry, bude-li to potřeba, a povolit automatickou detekci citlivosti na inzulín
- Jeden týden úspěšného používání s běžným příjmem sacharidů
- Povolit další funkce pro běžné používání jako AMA
- Povolit další funkce pro běžné používání jako SMB
- Přečíst si dokumentaci a zvýšit maximální IOB, aby mohlo SMB fungovat. Pro začátek se dá použít velikost běžného bolusu + 3x maximální denní bazálDosaženo limituNení vybrán žádný profilSmyčka byla zakázána
@@ -345,10 +336,13 @@
Pro spuštění bazálu %1$.2fU/h na %2$d min odpovězte SMS s kódem %3$sPro přepnutí profilu na %1$s %2$d%% odpovězte SMS s kódem %3$sPro spuštění prodlouženého bolusu %1$.2fU na %2$d min odpovězte SMS s kódem %3$s
+ Pro zadání %1$dg na %2$s odpovězte pomocí SMS s kódem %3$sPro spuštění bazálu %1$d%% na %2$d min odpovězte SMS s kódem %3$sK pozastavení smyčky na %1$d minut odpověz SMS s kódem %2$sDočasný bazál %1$.2fU/h na %2$d minut spuštěnProdloužený bolus %1$.2fU na %2$d min úspěšně spuštěn
+ Sacharidy %1$dg byly úspěšně zadány
+ Zadání %1$dg sacharidů se nezdařiloDočasný bazál %1$d%% na %2$d minut úspěšně spuštěnSpuštění dočasného bazálu selhaloSpuštění prodlouženého bolusu selhalo
@@ -466,8 +460,8 @@
ProfilVýchozí hodnota: 3 Toto je klíčová hodnota zabezpečení. Říká, že maximální nastavitelný bazál je trojnásobkem maximálního denního bazálu. Patrně to nebudete muset měnit, případně si přečtete o tématu \"3x max denní; 4x aktuální\".Výchozí hodnota: 4 Toto je druhá klíčová hodnota. Říká, že maximální hodnota dočasného bazálu nikdy nebude větší, než čtyřnásobek aktuálního bazálu. Je to proto, aby se lidé nedostali do nebezpečných hodnot dříve, než pochopí jak OpenAPS pracuje. Znovu, výchozí hodnota je 4 a většina lidí ji nikdy nebude muset změnit. Pokud nestačí, obvykle je problém někde jinde.
- Výchozí hodnota: 1.2\nToto je bezpečnostní nastavení pro detekci sensitivity (a brzy autotune). Říká, že autosens může zvýšit bazály, snížit ISF a snížit cílovou hodnotu glykémie o 20%%.
- Výchozí hodnota: 0.7\nToto je bezpečnostní nastavení pro detekci sensitivity. Říká, že autosens může snížit bazály, zvýšit ISF a zvýšit cílovou hodnotu glykémie na 70%%.
+ Výchozí hodnota: 1.2\nToto je bezpečnostní nastavení pro detekci sensitivity (a brzy autotune). Říká, že autosense může zvýšit bazály, snížit ISF a snížit cílovou hodnotu glykémie o 20 %.
+ Výchozí hodnota: 0.7\nToto je bezpečnostní nastavení pro detekci sensitivity. Říká, že autosense může snížit bazály, zvýšit ISF a zvýšit cílovou hodnotu glykémie na 70 %.Úprava cílové glykémie pomocí AutosensVýchozí hodnota: zapnuto\nToto nastavení říká, že autosens může měnit také cílové hodnoty glykémií.Výchozí hodnota: 2\nToto nastavení říká, po jakou část z hodnoty DIA smyčka po bolusu čeká a nereaguje na změny glykémií (zde 3DIA/2 = 1,5h).
@@ -569,8 +563,8 @@
Povolí rozšířené stavové indikátory pro stáří kanyly, inzulínu, senzoru, zásobníku a baterie na domovské obrazovce.Úroveň varování stavu zásobníku [U]Úroveň kritického varování stavu zásobníku [U]
- Úroveň varování stavu baterie [%%]
- Úroveň kritického varování stavu baterie [%%]
+ Úroveň varování stavu baterie [%]
+ Úroveň kritického varování stavu baterie [%]IOBCOBFirmware
@@ -701,6 +695,7 @@
gmh
+ d]]>kJEn
@@ -729,6 +724,7 @@
Nastavení nahrávání glykémiíZobrazovat detailní změnyZobrazovat rozdíl s jedním desetinným místem navíc
+ Max. minut SMBMaximální počet minut bazálu, ke kterým se limituje SMBNepodporovaný firmware v pumpěOdesílat data do xDrip+
@@ -864,8 +860,6 @@
Přepnutí profilu chybí. Proveďte přepnutí profilu nebo ho aktivujte na záložce lokálního profilu.Počet bolusůPočet dočasných bazálů
- Výukový cíl %1$d nespuštěn
- Výukový cíl %1$d nedokončenPumpa nepodporuje dočasné bazályZ pumpy nepřečten žádný platný bazálUzavřená smyčka zakázána v nastavení
@@ -987,7 +981,6 @@
Hotovo, gratulujeme!NedokončenoČas
- %1$d. cílPoctechZískávat glykémie z aplikace PoctechPřijímat hodnoty glykémií z Tomato aplikace (MiaoMiao zařízení)
@@ -1012,7 +1005,7 @@
Poslat logy e-mailemSmazat logyOšetření (inzulín: %1$.2f, sacharidy: %2$d, čas: %3$s) nelze přidat. Zkontrolujte a podle potřeby ručně přidejte záznam.
- eCarbs: %1$d g (%2$d h), start: %3$d m
+ eCarbs: %1$d g (%2$d h), zpoždění: %3$d mNedostupná data o glykémiíchNastavení logováníObnovit výchozí
@@ -1172,7 +1165,7 @@
Nahrávat přepnutí profilu, dočasné cíleNahrávat měření z prstuZměna letního času za méně než 24 hodin
- Změna letního času za méně než 3 hodiny - Uzavřená smyčka zastavena
+ Změna letního času za méně než 3 hodiny – Uzavřená smyčka zastavenaomezení vnitřního úložištěUvolněte alespoň %1$d MB z vnitřního úložiště! Smyčka zakázána!Chybný formát
@@ -1260,6 +1253,8 @@
Nevybráno (Jednoduché)Alkalické (Rozšířené)Lithiové (Rozšířené)
+ NiZn (Rozšířené)
+ Bolus/Ošetření laděníVYHLEDATZASTAVIT
@@ -1368,52 +1363,35 @@
Načítání dočasného bazáluNastavování dočasného bazáluNastavování bolusu
+ Změna profilu na
+ Změna profilu na %1$s
+ Poslední připojení k pumpě
+ Poslední připojení k pumpě před [minutami]
+ Poslední připojení k pumpě %1$s před %2$s minutami
+ Poslat SMS: %1$s
+ Odeslat SMS na všechna čísla v předvolbách
+ Odeslat SMS s textem%2$+.2fU]]>Aplikováno omezení bolusu: %2$.2fU na %3$.2fU]]>
- !!!!! Detekována pomalá absorbce sacharidů: %2$d% % času. Překontrolujte kalkulaci. COB může být nadhodnocené, a proto může být počítáno více inzulínu !!!!!]]>
+ !!!!! Detekována pomalá absorbce sacharidů: %2$d%% času. Překontrolujte kalkulaci. COB může být nadhodnocené, a proto může být započítáno více inzulínu !!!!!]]>%1$.0f / %2$d UPodat tuto část z výsledku kalkulace [%]Kalkulátor provede výpočet, ale dodána je pouze tato část inzulínu. Výhodné při používání SMB algoritmu.Načítání…Ztišit
- Splněno: %1$s
- Naučte se, jak ovládat AndroidAPS
- Provádějte v AndroidAPS různé akce
- Nastavte profil na 90 % na 10 min (Dlouhé stisknutí názvu profilu na obrazovce Přehled)
- Předstírejte, že se jdete sprchovat. Odpojte pumpu na 1 h (Dlouze přidržte tlačítko Otevřená smyčka)
- ...a stejným způsobem ji znovu připojte
- Vytvořte vlastní dočasný cíl s trváním 10 min (Dlouze přidržte aktuální cíl)
- Na kartě Konfigurace povolte modul Akce, aktivujte jeho zobrazení a zobrazte jeho obsah z horní nabídky
- Zobrazte obsah modulu Smyčka
- Přepněte režim zobrazení dlouhým stisknutím grafu glykémie
- Zadat
- Zadejte kód, který jste získali od vývojářů, abyste obešli zbývající cíle
- Kód přijat
- Neplatný kód
- Prokažte své znalosti
- Studujte a správně zodpovězte otázky
- Odpovídání zakázáno do: %1$s
- Špatná odpověď!
- Další nedokončená
+ Časový rozsah
+ Čas je mezi %1$s a %2$s
+ Mezi Zavřít
- Kód žádosti: %1$s
- (zatrhněte všechny správné odpovědi)
-
- %1$d den
- %1$d dnů
- %1$d dnů
- %1$d dnů
-
-
- %1$d hodina
- %1$d hodin
- %1$d hodin
- %1$d hodin
-
-
- %1$d minuta
- %1$d minut
- %1$d minut
- %1$d minut
-
+ Zvýšena hodnota maximálního bazálu, protože nastavení je nižší než Vaše maximální hodnota bazální profilu
+ Neplatné tělo zprávy
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Bolusová kalkulačka
+ min
+ %1$dg
+ ZAP
+ VYP
diff --git a/app/src/main/res/values-de-rDE/exam.xml b/app/src/main/res/values-de-rDE/exam.xml
index 70489fbc5e..7d83ac2db7 100644
--- a/app/src/main/res/values-de-rDE/exam.xml
+++ b/app/src/main/res/values-de-rDE/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Welche Aussagen zum DIA stimmen?
+ Thema: Insulinwirkdauer
+ Der Mindestwert ist 3 Stunden.
+ Der Mindestwert ist 5 Stunden.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Configuration/Config-Builder.html#insulin
+ Entspricht der Insulinwirkdauer (DIA), die Du in Deiner Pumpe eingestellt hast.
+ Du musst den individuell für Dich passenden Wert (nicht weniger als 5 Stunden) ermitteln.
+ Thema: Temporäres Ziel \"Hypo\"
+ Was ist der Hauptgrund, ein Hypo TT zu setzen?
+ Um zu verhinden, dass der Glukosewert sinkt, wenn die temp. Basalrate bereits 0 ist (sog. zero temp).
+ Um zu verhindern, dass AAPS zu viel Insulin abgibt, wenn der Glukosewert durch Hypo-KH steigt.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/temptarget.html
+ Welches Profil kann offline verwendet und konfiguriert werden?
+ Thema: Offline-Profil
+ NS-Profil kann verwendet, aber nicht konfiguriert werden.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Configuration/Config-Builder.html#profil
+ Thema: Pumpe abkoppeln
+ Was soll getan werden, wenn die Verbindung zur Pumpe getrennt wird?
+ Klicke auf \'Pumpe trennen\', so dass AAPS weiß, dass kein Insulin abgegeben wird.
+ Klicke auf auf \'Loop pausieren\', damit AAPS den Loop unterbricht während die Pumpe nicht verbunden ist.
+ Ändere nichts in AAPS, trenne einfach die Verbindung zur Pumpe.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#andere-einstellungen
+ Thema: AndroidAPS Einstellungen
+ Welches ist die empfohlene Vorgehensweise, um ein Backup Deiner Einstellungen zu erstellen?
+ Exportiere sie lokal auf Deinem Smartphone über den Menüpunkt \"Wartung\".
+ Speichere die exportierte Datei an einen anderen Ort (E-Mail, Dropbox, Google Drive...).
+ Exportiere sie direkt nach der Installation von AAPS.
+ Exportiere sie, nachdem du Änderungen vorgenommen hast.
+ Exportiere sie, nachdem du ein Ziel (objective) abgeschlossen hast.
+ Exportiere sie, nachdem Du die Ersteinrichtung abgeschlossen hast.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#was-sollte-ich-fur-den-notfall-immer-dabei-haben
+ Thema: Verrauschte CGM-Werte
+ Was sollte getan werden, wenn CGM-Daten unzuverlässig werden?
+ Nichts, AAPS kümmert sich darum.
+ Deaktiviere den Loop, um zu hohe Insulinabgabe zu vermeiden.
+ Ersetze den CGM-Sensor.
+ Schalte das Smartphone aus.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html
+ Stelle sicher, dass deine CGM-app die Glukose-Werte glättet.
+ Thema: Aktivität
+ Wie kannst Du das System dabei unterstützen, mit Sport und Bewegung umzugehen?
+ Verwenden der Funktion temporäres Ziel.
+ Mache einen Profilwechsel auf UNTER 100%.
+ Mache einen Profilwechsel auf ÜBER 100%.
+ Stoppe den Loop.
+ Setze ein temporäres Ziel für Aktivität, bevor du mit Sport beginnst.
+ Ein temporäres Ziel nach dem Sport einzustellen führt zu schlechteren Resultaten als wenn das Ziel vor dem Sport eingestellt würde.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/temptarget.html#aktivitaten-temp-target
+ Thema: Deaktiviere/Pausiere den Loop
+ Bekomme ich Insulin, wenn der Loop deaktiviert/pausiert ist?
+ Ja, Basalinsulin wird weiter abgegeben.
+ Nein, die Insulinabgabe ist gestoppt.
+ Thema: Basalrate, Korrektur- und Kohlenhydratfaktoren überprüfen
+ Wann sollte ich Basalrate, Korrektur- und KH-Faktoren prüfen?
+ Bevor ich beginne zu loopen.
+ Bei häufig niedrigen Glukose-Werten.
+ Bei häufig hohen Glukose-Werten.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#androidaps-einstellungen
+ Thema: Grundvoraussetzungen
+ Was brauche ich?
+ Überprüfe die Profil-Einstellungen (Basal, IC, ISF, DIA).
+ Einen Computer zum Erstellen der APK.
+ Ein unterstütztes Smartphone.
+ Ein Auto.
+ Nightscout zum Erreichen der Objectives (Ziele)
+ Ein Tidepool-Konto.
+ Ein Google-Konto.
+ Ein Github-Konto.
+ Erfahrung in der Entwicklung von Android-Apps.
+ Eine Medtronic 670G Insulinpumpe.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Module/module.html
+ Eine Smartwatch.
+ Ein unterstütztes CGM.
+ Thema: AndroidAPS updaten
+ Was stimmt?
+ Du musst Git installieren.
+ Führe das Update durch, sobald die neue Version freigegeben ist und Du genug Zeit dafür hast.
+ Du solltest die gleichen Signaturschlüssel (keys) verwenden.
+ Nie updaten, wenn das System stabil läuft.
+ Frag deine Freunde nach einer neuen APK-Datei.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Installing-AndroidAPS/Update-to-new-version.html
+ Thema: Fehlerbehebung
+ Wo bekommst Du Hilfe?
+ Tritt den Facebook-Gruppen LoopedDE (deutsch) und androidapsusers (englisch) bei.
+ Lies die AndroidAPS-Dokumentation.
+ Nutze den AndroidAPS Gitter Channel.
+ Nutze AndroidAPS Google Support.
+ Sprich mit Deinem Diabetologen / Diabetesberater.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Installing-AndroidAPS/Update-to-new-version.html#problembehandlung
+ https://www.facebook.com/groups/loopedDE/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Thema: Insulin Plugins
+ Welches Insulin kann mit dem Plugin „Ultra-Rapid-Oref“ verwendet werden?
+ Fiasp®
+ Novorapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Configuration/Config-Builder.html#insulin
+ Thema: Empfindlichkeit (Sensitivity) Plugins
+ Welcher Empfindlichkeitsalgorithmus hat einen einstellbaren Zeitbereich?
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Configuration/Sensitivity-detection-and-COB.html
+ Welches Plugin zur Empfindlichkeitserkennung muss für die UAM-Funktion (\"nicht angegebene Mahlzeiten\") genutzt werden?
+ Thema: Fehler bei der KH-Eingabe
+ Was sollst Du tun, wenn Du einen falschen KH-Eintrag gemacht hast?
+ Lösche den falschen KH-Eintrag unter \"Behandlungen\" und gib die korrekten KH neu ein.
+ Gib \"Fake Insulin\" über die Funktion Vorfüllen/Füllen ab.
+ Thema: Mahlzeiten mit Fett und Protein (FPE)
+ Wie gehst Du vor, wenn Deine Mahlzeit viel Fett und\/oder Proteine enthält?
+ Rechne Fett und Proteine in Kohlenhydrate um und nutze die Funktion für verzögerte Kohlenhydrate (\"eCarbs\").
+ Rechne Fett und Proteine in Kohlenhydrate um und füge sie zu Deiner Bolusberechnung hinzu.
+ Verwende einen verzögerten Bolus, um Fett und Proteine abzudecken.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Extended-Carbs.html
+ Thema: Kontrolle aus der Ferne
+ Wie kannst Du den Loop eines Kindes mit AAPS aus der Ferne mitverfolgen?
+ Mit einer Nightscout-Website.
+ Dexcom Follow App zusammen mit der originalen Dexcom App (nur BZ).
+ Über Dexcom Follow, falls Du die xDrip App verwendest.
+ xDrip im Follower Modus.
+ Loop App auf einem iPhone.
+ Spike App auf einem iPhone.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Children/Children.html
+ Thema: Korrekturfaktoren (ISF)
+ Höhere ISF-Werte (Insulinempfindlichkeit) führen zu niedrigerer Insulin-Abgabe, wenn AAPS hohe Glukosewerte korrigiert.
+ Niedrigere ISF-Werte (Insulinempfindlichkeit) führen zu niedrigerer Insulin-Abgabe, wenn AAPS hohe Glukosewerte korrigiert.
+ Das Ändern von ISF-Werten hat keinen Einfluss auf die abgegebene Menge an Insulin, wenn AAPS hohe Glukosewerte korrigiert.
+ Du musst den ISF in den Einstellungen eingeben.
+ Wenn Du einen ISF-Wert im Profil änderst, wird dies sofort vom Loop berücksichtigt.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#korrekturfaktor-isf-mg-dl-ie-oder-mmol-l-ie
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Profiles.html
+ Thema: Das IC-Verhältnis (Insulin-Kohlenhydrate)
+ Ein höheres IC-Verhältnis bedeutet, dass weniger Insulin für die selbe Menge an KH abgegeben wird.
+ Ein niedrigeres IC-Verhältnis bedeutet, dass weniger Insulin für die selbe Menge an KH abgegeben wird.
+ Das Ändern des IC-Verhältnisses bedeutet, dass bei 0 COB eine andere Menge an Insulin zur Korrektur eines vorgegebenen BZ-Wertes abgegeben wird.
+ Der IC-Wert muss sich unterscheiden, je nachdem, ob Du eine BE mit 10g oder mit 12g berechnest.
+ IC bedeutet: Wie viele BE werden durch eine Einheit Insulin abgedeckt?
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#kh-faktor-carbohydrate-to-insulin-ratio-cr-g-ie
+ Thema: Profilwechsel
+ Durch einen Profilwechsel auf 90%…
+ wird 10% MEHR Basalinsulin abgegeben.
+ wird 10% WENIGER Basalinsulin abgegeben.
+ liegt der IC-Wert (KH-Faktor) 10% HÖHER.
+ liegt der IC-Wert (KH-Faktor) 10% NIEDRIGER.
+ liegt der ISF-Wert (Korrekturfaktor) 10% HÖHER.
+ wird der ISF-Wert (Korrekturfaktor) 10% NIEDRIGER sein.
+ Du wirst rund 10% weniger Insulin erhalten.
+ wird der Zielwert 10% HÖHER liegen.
+ wird der Zielwert 10% NIEDRIGER liegen.
+ wird nur der untere Zielwert 10% NIEDRIGER liegen.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Profiles.html#prozentsatz
+ Wenn du 1h früher als üblich aufwachst, wie solltest du AAPS über die Änderung in deinem Zeitplan informieren?
+ Profilwechsel mit einer Zeitverschiebung von 1
+ Profilwechsel mit einer Zeitverschiebung von -1
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Usage/Profiles.html#zeitverschiebung
+ Profilwechsel mit einer Zeitverschiebung von 60
+ Profilwechsel mit einer Zeitverschiebung von -60
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Module/module.html#gute-individuelle-profileinstellungen-fur-deine-diabetes-therapie
+ Thema: Hilfe zur Einstellung der Basalraten
+ An wen solltest Du Dich wenden, wenn Du Unterstützung zur Einstellung Deiner Basalrate etc. brauchst?
+ Dein Diabetes-Team
+ Google
+ Facebook
+ Andere Medikamente
+ AAPS reduziert die Basalrate zur Erhöhung des Blutzuckers. Medikamente aus der Gruppe der SGLT2-Hemmer (Gliflozine) können zu erwartende Blutzuckersteigungen verhindern und damit einen gefährlichen Insulinmangel (DKA) produzieren.
+\nÜbliche Handelsnamen sind: Invokana ®, Forxiga ®, Jardiance ®, Steglatro ®, Suglat ®, Apleway ®, Deberza ®, Synjardy ®, Vokanamet ®, Xigduo ®.\n\nIch verspreche, dass ich solche Medikamente bei der Anwendung von AAPS nicht einnehmen werde oder den Loop vor der Verwendung dieser Medikamente deaktivieren werde.
+
diff --git a/app/src/main/res/values-de-rDE/objectives.xml b/app/src/main/res/values-de-rDE/objectives.xml
new file mode 100644
index 0000000000..1158cee370
--- /dev/null
+++ b/app/src/main/res/values-de-rDE/objectives.xml
@@ -0,0 +1,69 @@
+
+
+
+ Zurück
+ Start
+ Bestätigen
+ %1$d. Objective (Ziel)
+ Objective %1$d nicht begonnen
+ Objective %1$d nicht abgeschlossen
+ Einrichten der Anzeige und Überwachung sowie Analysieren der Basalraten und Faktoren
+ Prüfe, ob der BZ-Wert in Nightscout angezeigt wird und die - Pumpen-Insulin-Daten erfolgreich hochgeladen werden
+ Beginne im Open Loop Modus
+ Probiere den Open Loop Modus für ein paar Tage aus und setze manuell ganz viele temporäre Basalraten. Richte temporäre Ziele ein und nutze sie (z.B. für Aktivität oder bei KH zur Hypobehandlung)
+ Versuche, den Open Loop und seine Empfehlungen für temporäre Basalraten nachzuvollziehen
+ Entscheide, wie hoch demzufolge max Basal sein sollte und übernimm diesen Wert in die Pumpe und in die AAPS-Einstellungen
+ Starte den Closed Loop Modus mit Abschaltung bei niedrigen Werten
+ Probiere den Closed Loop Modus mit max IOB = 0 für ein paar Tage aus, ohne zu viele Unterzuckerungen zu haben
+ Passe den Closed Loop an, indem du max IOB auf über 0 erhöhst und den BZ-Zielwert langsam heruntersetzt
+ Bevor Du den Zielwert niedriger einstellst, musst Du einige Tage Erfahrung sammeln und mindestens eine Nacht ohne Hypoalarm schaffen
+ Passe Basalraten und Faktoren bei Bedarf an und schalte anschließend Autosens ein.
+ Loope eine Woche tagsüber mit regelmäßiger Kohlenhydrat-Eingabe
+ Aktiviere zusätzliche Funktionen für die Nutzung tagsüber wie z. B. den erweiterten Mahlzeitenassistenten (AMA)
+ Aktiviere zusätzliche Funktionen für die Nutzung tagsüber wie z. B. SMB
+ Lies das Wiki und erhöhe maxIOB, damit der SMB gut funktioniert. Ein guter Anfang ist
+die Formel maxIOB = durchschnittlicher Essensbolus + 3 x höchste Basalrate
+ BZ in Nightscout verfügbar
+ Pumpen-Status in Nightscout verfügbar
+ Manuelle Aktionen
+ Erfüllt: %1$s
+ Lerne, wie AndroidAPS bedient wird
+ Führe verschiedene Aktionen in AndroidAPS aus.
+ Setzte das Profil für 10 Min. auf 90% (drücke dazu lange auf deinen Profilnamen im Homescreen)
+ Simuliere das Duschen . Trenne die Pumpe für 1 Std. (drücke dazu lang auf Open Loop im Homescreen)
+ ...und verbinde die Pumpe auf dieselbe Weise wieder
+ Erstelle ein benutzerdefiniertes temporäres Ziel mit 10 Min. Dauer (drücke lang auf Deinen aktuellen Zielwert im Homescreen)
+ Aktiviere das Plugin \"Aktionen\" unter Konfiguration, mache es sichtbar und rufe es über das obere Menü auf
+ Zeige den Inhalt des Loop-Plugins an
+ Nutze die Skalierfunktion. Drücke dazu lange auf das BZ-Diagramm
+ OK
+ Wenn Du früher bereits OpenAPS genutzt hast und auf Deiner Nightscout-Seite mindestens drei Monate Closed-Loop-Daten ersichtlich sind, kannst Du eine E-Mail an objectives@androidaps.org mit Deiner NS-URL und Deinem Anforderungscode senden, um die restlichen Ziele zu überspringen. Code eingeben, der von den Entwicklern übermittelt wurde:
+ Code akzeptiert
+ Code ungültig
+ Prüfe Dein Wissen
+ Lies und beantworte die Fragen richtig
+ Frage gesperrt bis: %1$s
+ Falsch!
+ Nächste offene
+ Code anfordern: %1$s
+ (Kreuze alle richtigen Antworten an)
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/FAQ.html#was-mache-ich-wenn-ich-duschen-oder-ein-bad-nehmen-mochte
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/Screenshots.html#die-startseite
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/Screenshots.html#konfiguration
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/de/Getting-Started/Screenshots.html#die-startseite
+ Keine Verbindung zum Internet
+ Abruf der Uhrzeit fehlgeschlagen
+ Anforderungen des Zieles nicht erfüllt
+
+ %1$d Tag
+ %1$d Tage
+
+
+ %1$d Stunde
+ %1$d Stunden
+
+
+ %1$d Minute
+ %1$d Minuten
+
+
diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml
index 9acf4ba696..b8b04fbce0 100644
--- a/app/src/main/res/values-de-rDE/strings.xml
+++ b/app/src/main/res/values-de-rDE/strings.xml
@@ -5,7 +5,6 @@
-
Sicherheitseinstellungen der BehandlungenMax. erlaubter Bolus [IE]Max. erlaubte Kohlenhydrate [g]
@@ -57,9 +56,6 @@
Überwache und steuere AndroidAPS mit Deiner WearOS-Smartwatch.Zeige Loop-Informationen auf Deinem xDrip+-Watchface.Steuere AndroiAPS fern mittels SMS-Anweisungen.
- Zurück
- Start
- BestätigenEinheitenDIAIC
@@ -102,6 +98,7 @@
ProfilMahlzeiten-DatenErgebnis
+ Ergebnis: %1$s %2$sKeine BZ-Werte verfügbarKeine Anpassung benötigtAnfrage
@@ -177,9 +174,6 @@
Nicht unterstützte Version des Nightscout-ClientsNicht unterstütze Nightscout-VersionNightscout-Client ist nicht installiert. Eintrag verloren!
- BZ verfügbar in Nightscout
- Pumpen-Status verfügbar in Nightscout
- Manuelle AktionenLOOP DEAKTIVIERT DURCH BESCHRÄNKUNGENBasal-IOBBolus-Beschränkung angewendet
@@ -222,7 +216,7 @@
TBRVerzögerter BolusNightscout-Version:
- Fehlend
+ Fehlend %1$dgEinstellungen exportiertEinstellungen exportieren nachImportiere Einstellungen von
@@ -266,11 +260,23 @@
Erlaubte Telefonnummern+XXXXXXXXXX;+YYYYYYYYYYUm einen Bolus von %1$.2f IE abzugeben, antworte mit dem Code %2$s.
+ Um einen Mahlzeitenbolus von %1$.2f IE abzugeben, antworte mit dem Code %2$s.
+ Um ein Temp Target von %1$s zu setzen, antworte mit dem Code %2$s
+ Um das temporäre Ziel zu stoppen, antworte mit dem Code %1$s
+ Um den SMS Remote Service zu deaktivieren, antworte mit dem Code %1$s.\n\nBeachte, dass Du diesen nur am AAPS Master Smartphone wieder aktivieren kannst.
+ SMS Remote Service gestoppt. Verwende das AAPS Master, um ihn wieder zu aktivieren.Um die Kalibrierung %1$.2f zu senden, antworte mit dem Code %2$s.Bolus fehlgeschlagen
+ Minimale Dauer in Minuten, die nach einem Remote Bolus verstrichen sein muss, bevor ein neuer abgegeben werden kann.
+ Anzahl Minuten, die mindestens zwischen zwei Bolusgaben liegen müssen.
+ Aus Sicherheitsgründen musst Du mindestens zwei Telefonnummern eintragen, um diese Voreinstellung zu ändern.Bolus %1$.2fIE erfolgreich abgegebenWerde %1$.2fIE abgebenBolus %1$.2fIE erfolgreich abgegeben
+ Mahlzeiten-Bolus %1$.2f IE erfolgreich abgegeben.
+ Ziel %1$s für %2$d Minuten
+ Ziel %1$s für %2$d Minuten erfolgreich gesetzt.
+ Temporäres Ziel wurde erfolgreich abgebrochenGebe %1$.2fIE abErlaube externe Befehle per SMSFinger
@@ -317,26 +323,10 @@
STOPP GEDRÜCKTWarte auf PumpeWerde %1$.2fIE abgeben
- Konfiguriere die Anzeige und das Monitoring (Nightscout) und analysiere Basal-Raten und Faktoren
- Verifiziere, dass BZ- und Pumpen-Insulin-Daten erfolgreich zu Nightscout hochgeladen werden.
- Den Open Loop starten.
- Erprobe den Open Loop Modus für ein paar Tage und setze manuell temporäre Basal-Raten. Richte temporäre Ziele ein und nutze sie (z.B. für Bewegung, unterstützend zur Hypobehandlung).
- Verstehe den Open Loop und die TBR-Empfehlungen
- Entscheide anhand von dieser Erfahrung, wie hoch max Basal sein sollte, und übernehme den Wert in die Pumpen- und AAPS-Einstellungen.
- Starte den Closed Loop Modus mit Abschaltung bei niedrigen Werten
- Erprobe den Closed Loop Modus mit max IOB = 0 für ein paar Tage, ohne zu viele Unterzuckerungen zu haben.
- Stelle den Closed Loop feiner ein, erhöhe max IOB über 0 und setze den Zielwert langsam herunter.
- Bevor Du den Zielwert runter setzt, musst Du einige Tage Erfahrung sammeln und mind. eine Nacht ohne Alarm wegen niedriger BZ-Werte absolvieren.
- Passe, falls notwendig, Basal und Faktoren an und aktiviere dann die Autosens-Funktion.
- Loope eine Woche erfolgreich tagsüber mit regelmäßiger Kohlenhydrat-Eingabe.
- Aktiviere zusätzliche Funktionen wie z. B. den erweiterten Mahlzeitenassistenten (AMA).
- Aktiviere zusätzliche Funktionen wie z. B. SMB
- Lies das Wiki und hebe maxIOB an, damit SMB funktioniert. Ein guter Startwert ist
-maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateLimit erreichtKein Profil ausgewähltLoop wurde deaktiviert.
- Lopp wurde aktiviert
+ Loop wurde aktiviertLoop ist deaktiviert.Loop ist aktiviert.%1$.2f limitiert auf %2$.2f
@@ -346,10 +336,13 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateUm eine Basalrate von %1$.2fIE/h für %2$d Minuten zu setzen, antworte mit dem Code %3$sUm das Profil auf %1$s %2$d%% zu setzen, antworte mit dem Code %3$sUm den erweiterten Bolus %1$.2fIE für %2$d Minuten abzugeben, antworte mit dem Code %3$s
+ Um %1$dg Kohlenhydrate um %2$s einzugeben, antworte mit dem Code %3$sUm die Basalrate von %1$d%% für %2$d Minuten zu setzen, antworte mit dem Code %3$sUm das Loopen für %1$d Minuten zu pausieren, antworte mit dem Code %2$s.TBR mit %1$.2f IE/h für %2$d min wurde erfolgreich gestartet.Der erweiterte Bolus %1$.2f IE/h für %2$d Minuten wurde erfolgreich gestartet
+ %1$dg Kohlenhydrate erfolgreich erfasst
+ Eingabe von %1$dg Kohlenhydraten ist fehlgeschlagen.Die temporäre Basalrate wurde erfolgreich für %2$d Minuten auf %1$d%% gesetztDas Starten der TBR ist fehlgeschlagen.Die Abgabe des erweiterten Bolus ist fehlgeschlagen
@@ -500,7 +493,7 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalratePasswort für die EinstellungenEinstellungen freischaltenTagesinsulin-Limit wird bald erreicht
- Nighscout-Client
+ Nightscout-ClientNSClURL:Auto-Scrollen
@@ -570,8 +563,8 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateErweiterte Statusanzeige für CAGE, IAGE, SAGE, Reservoir- und Batteriestand auf dem Homescreen.Warnschwelle Reservoirstand [IE]Warnschwelle kritischer Reservoirstand [IE]
- Warnschwelle Batteriestand [%%]
- Warnschwelle kritischer Batteriestand [%%]
+ Warnschwelle Batteriestand [%]
+ Warnschwelle kritischer Batteriestand [%]IOBCOBFirmware
@@ -702,6 +695,7 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale Basalrategminh
+ T]]>kJEn
@@ -730,6 +724,7 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateBZ Upload EinstellungenZeige detailliertes DeltaDelta wird mit Dezimalstelle angezeigt.
+ SMB max. MinutenSMB Basal-Limit in MinutenNicht unterstützte Pumpen-FirmwareSende BZ-Werte zu xDrip+
@@ -865,8 +860,6 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateProfil-Wechsel fehlt, bitte nimm einen Profil-Wechsel vor oder drücke \"AKTIVIERE PROFIL\" im lokalen Profil.Anzahl BoliAnzahl TBR
- Zielsetzung %1$d nicht gestartet
- Zielsetzung %1$d nicht abgeschlossenPumpe verfügt nicht über temporäre BasalratenVon der Pumpe konnte keine gültige Basalrate eingelesen werden.Closed-Loop-Modus in den Einstellungen deaktiviert
@@ -988,7 +981,6 @@ maxIOB = durchschnittlicher Essensbolus + 3 x maximale BasalrateAbgeschlossen, gut gemacht!Noch nicht abgeschlossenVerstrichene Zeit
- %1$d. ZielPoctechEmpfange Blutzucker-Werte von der Poctech-App.Empfange Blutzucker-Werte von der Tomato-App (MiaoMiao-Geräte)
@@ -1237,7 +1229,7 @@ Unerwartetes Verhalten.Bitte wähle einen Auslöser:Auslöser:ENTFERNEN
- Vorbedingung:
+ Voraussetzung:Operation nicht durch Pumpe und/oder Treiber unterstützt.Operation NOCH NICHT von Pumpe unterstützt.
@@ -1262,6 +1254,8 @@ Unerwartetes Verhalten.Nicht ausgewählt (Einfache Ansicht)Alkaline Batterie (erweiterte Ansicht)Lithium Batterie (erweiterte Ansicht)
+ Nickel-Zink-Akku (erweiterte Ansicht)
+ Fehlersuche Bolus/BehandlungenSCANNENSTOP
@@ -1370,6 +1364,14 @@ Unerwartetes Verhalten.Hole Temporäre BasalratenSetze Temporäre BasalrateSetze Bolus
+ Profil wechseln zu
+ Profil wechseln zu %1$s
+ Letzte Verbindung zur Pumpe
+ Letzte Verbindung zur Pumpe [vor X Minuten]
+ Letzte Verbindung zur Pumpe vor %1$s %2$s Minuten
+ SMS senden: %1$s
+ SMS an alle vorgegebenen Nummern senden
+ SMS mit Text senden%2$+.2fU]]>Bolus-Einschränkung angewendet: %2$.2fIE zu %3$.2fIE]]>!!!!! Langsamer Kohlenhydrat-Abbau erkannt: %2$d%% der Zeit. Überprüfe Deine Berechnung. COB könnte zu hoch sein und deswegen zu viel Insulin abgegeben werden!!!!!]]>
@@ -1378,38 +1380,19 @@ Unerwartetes Verhalten.Der Bolus-Assistent führt Berechnungen durch, aber nur dieser Teil der berechneten Insulin wird abgegeben. Nützlich mit SMB-Algorithmus.Lädt ...Schlummern
- Erfüllt: %1$s
- Lerne, AndroidAPS zu bedienen.
- Führe verschiedene Aktionen in AndroidAPS aus.
- Setzte das Profil für 10 min. auf 90% (Drücke dazu lange auf den Profilnamen auf der Startseite)
- Simuliere duschen. Trenne die Pumpe für 1 Std. (Drücke lang auf Open Loop)
- ...und verbinde die Pumpe auf dem selben Weg wieder.
- Erstelle ein benutzerdefiniertes temporäres Ziel mit 10 min. Dauer (Drücke lange auf Deinen aktuellen Zielwert)
- Aktiviere das Plugin Aktionen im Konfigurations-Generator, zeige es an und rufe es vom Startbildschirm aus auf.
- Zeige den Inhalt des Loop-Plugins ein.
- Nutze die Skalierfunktion. Drücke dazu lange auf das Diagramm.
- Eingabe
- Gib den Code ein, den Du von den Entwicklern erhalten hast, um die restlichen Objectives zu überspringen.
- Code akzeptiert
- Code ungültig
- Belege Dein Wissen
- Beantworte die Fragen richtig.
- Beantwortung deaktiviert bis: %1$s
- Falsche Antwort!
- Nächte unbeantwortete
+ Zeitraum
+ Für die Zeit zwischen %1$s und %2$s
+ Zwischen Schließen
- Erfrage Code:: %1$s
- (kreuze alle richtigen Antworten an)
-
- %1$d Tag
- %1$d Tage
-
-
- %1$d Stunde
- %1$d Stunden
-
-
- %1$d Minute
- %1$d Minuten
-
+ Der Wert max basal wird erhöht, weil Du ihn niedriger eingestellt hast als die höchste Basalrate in Deinem Profil.
+ Ungültiger Inhalt
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Bolus-Rechner
+ Min.
+ %1$dg
+ Ein
+ Aus
diff --git a/app/src/main/res/values-el-rGR/exam.xml b/app/src/main/res/values-el-rGR/exam.xml
index 70489fbc5e..f939334dd5 100644
--- a/app/src/main/res/values-el-rGR/exam.xml
+++ b/app/src/main/res/values-el-rGR/exam.xml
@@ -1,3 +1,166 @@
-
+
+ Ποια είναι η αλήθεια για το DIA;
+ Θέμα: η Διάρκεια της Δράσης Ινσουλίνη
+ Η ελάχιστη τιμή είναι 3 ώρες.
+ Η ελάχιστη τιμή είναι 5 ώρες.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ Το νόημα είναι ίσο με την DIA που χρησιμοποιείται στην αντλία.
+ Θα πρέπει να καθορίσει την ατομική τιμή (αλλά όχι λιγότερο από 5 ώρες).
+ Θέμα: Προσωρινοί στόχοι Υπό
+ Ποιος είναι ο πρωταρχικός λόγος για να ορίσετε ένα υπο TT;
+ Για να αποτρέψετε BG να πάει χαμηλά εάν υπάρχει ενεργός ήδη μηδενικό; προσωρινός.
+ Για να αποτρέψετε AAPS από τη χορήγηση υπερβολικής ινσουλίνης μετά από μια αύξηση που προκαλείται από ταχείας δράσης υδατάνθρακες που χρησιμοποιούνται για τη θεραπεία υπογλυκαιμίας.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Ποιο προφίλ μπορεί να χρησιμοποιηθεί και να διαμορφωθεί χωρίς σύνδεση;
+ Θέμα: Προφίλ Εκτός Σύνδεσης
+ Το προφίλ NS μπορεί να χρησιμοποιηθεί, αλλά όχι να ρυθμιστεί.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Θέμα: Αποσύνδεση από την Αντλία
+ Τι πρέπει να γίνει όταν αποσυνδέεται η αντλία;
+ Πατήστε το κουμπί \"Αποσύνδεση αντλίας\", έτσι ώστε το AAPS να ξέρει ότι δεν χορηγείται ινσουλίνη.
+ Πατήστε το κουμπί \"Αναστολή κυκλώματος\", έτσι ώστε το AAPS να σταματά το κύκλωμα, ενώ η αντλία είναι αποσυνδεδεμένη.
+ Μην αλλάζετετίποτα στο AAPS, απλά αποσυνδέστε την αντλία.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Θέμα: AndroidAPS Ρυθμίσεις
+ Ποιες είναι οι καλύτερες πρακτικές για να αποθηκεύσετε τις ρυθμίσεις σας;
+ Εξάγετέ τις τοπικά από το Μενού Συντήρηση.
+ Αποθηκεύστε το αρχείο σε ένα άλλο μέρος όπως email, Dropbox, Google drive…
+ Εξάγετε τις ρυθμίσεις αμέσως μετά την εγκατάσταση του AAPS.
+ Εξάγετέ τις μετά από κάθε αλλαγή στις ρυθμίσεις.
+ Εξάγετέ τις έπιτα από κάθε επίτευξη στόχου.
+ Εξάγετέ τις όταν ολοκληρώσετε τις αρχικές ρυθμίσεις.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Θέμα: Θορυβώδης CGM Μετρήσεις
+ Τι πρέπει να κάνετε αν τα δεδομένα του CGM έχουν θόρυβο;
+ Τίποτα, το AAPS θα το αντιμετωπίσει.
+ Απενεργοποίηση κυκλώματος για αποφυγή υπερβολικής δόσης.
+ Αντικαταστήστε τον αισθητήρα CGM.
+ Απενεργοποιήστε το τηλέφωνο.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Βεβαιωθείτε ότι το CGM app λειαίνει τις μετρήσεις BG.
+ Θέμα: Άσκηση
+ Πώς μπορείτε να βοηθήσετε το σύστημα να αντιμετωπίσει την άσκηση;
+ Χρησιμοποιώντας το χαρακτηριστικό προσωρινό-στόχο.
+ Κάντε ένα προφίλ κάτω από το 100%.
+ Κάντε ένα προφίλ πάνω από το 100%.
+ Σταματήστε το κύκλωμα.
+ Ορίστε έναν προσωρινό-στόχο πριν την έναρξη της άσκησης.
+ Ο ορισμός προσωρινού-στόχου μετά την έναρξη της άσκησης οδηγεί σε χειρότερα αποτελέσματα από το να οριστεί πριν.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Θέμα: Απενεργοποίηση/Αναστολή κυκλώματος
+ Λαμβάνω ινσουλίνη όταν το κύκλωμα είναι απενεργοποιημένο/αναστολή;
+ Ναι, ο βασικός ρυθμός συνεχίζει να χορηγείται.
+ Όχι, η χορήγηση ινσουλίνης σταμάτησε.
+ Θέμα: Βασική, ISF, και IC Έλεγχος
+ Πότε θα πρέπει να επικυρώσετε τις τιμές του Βασικού, του ISF, και του IC;
+ Πριν αρχίσει το κύκλωμα.
+ Όταν αντιμετωπίζετε συχνά χαμηλές τιμές BG.
+ Όταν αντιμετωπίζετε συχνά υψηλές τιμές BG.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Θέμα: Προϋποθέσεις
+ Τι χρειάζομαι;
+ Έγκυρες πληροφορίες προφίλ (Βασικός, IC, ISF, DIA).
+ Έναν υπολογιστή για δημιουργία ενός APK.
+ Ένα τηλέφωνο που υποστηρίζεται.
+ Ένα Αυτοκίνητο.
+ Nightscout να περάσει τους στόχους.
+ Ένα Tidepool λογαριασμό.
+ Ένα λογαριασμό Google.
+ Ένα λογαριασμό Github.
+ Εμπειρία προγραμματιστή Android.
+ Μία αντλία MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Ένα Smartwatch.
+ Ένα Υποστηριζόμενο CGM.
+ Θέμα: Αναβάθμιση AndroidAPS
+ Τι είναι αλήθεια;
+ Θα πρέπει να έχετε εγκατεστημένο το Git.
+ Αναβαθμίστε μόλις μία έκδοση είναι διαθέσιμη και έχοντας αρκετό χρόνο για να το κάνετε.
+ Θα πρέπει να χρησιμοποιήσετε την ίδια υπογραφή κλειδιών.
+ Ποτέ μην αναβαθμίζετε εάν το σύστημα λειτουργεί καλά.
+ Ρωτήστε ένα φίλο γα το νέο APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Θέμα: Αντιμετώπιση Προβλημάτων
+ Πού ψάχνω για βοήθεια;
+ Γίνετε μέλος της ομάδας AndroidAPS στο Facebook.
+ Διαβάστε τον οδηγό AndroidAPS.
+ Επισκεφθείτε το AndroidAPS Gitter Room.
+ Επισκεφθείτε την υποστήριξη AndroidAPS Google
+ Μιλήσετε με τον ενδοκρινολόγο σας.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Θέμα: Προσθήκη Ινσουλίνης
+ Ποια μάρκα ινσουλίνης μπορεί να χρησιμοποιηθεί με την ΄Έξτρα-Γρήγορη-Oref΄ προσθήκη;
+ Fiasp®
+ NovoRapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Θέμα: Προσθήκες Ευαισθησία
+ Ποιος αλγόριθμος ευαισθησίας έχει ένα ρυθμιζόμενο χρονικό εύρος;
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Ποια προσθήκη ευαισθησίας πρέπει να χρησιμοποιείται για το UAM χαρακτηριστικό;
+ Θέμα: Σφάλματα Εισαγωγής Υδατανθράκων
+ Τι πρέπει να κάνετε αν γίνει μια λανθασμένη εισαγωγή υδατανθράκων;
+ Στις Θεραπείες, διαγράψτε την λανθασμένη εισαγωγή υδατανθράκων. Εισάγετε νέους υδατάνθρακες.
+ Προσθέσθε ψεύτικη ινσουλίνη, χρησιμοποιώντας την λειτουργία Ξαναγέμισμα
+ Θέμα: Τρόφιμα με Λίπος και Πρωτεΐνη
+ Τι να κάνετε αν το φαγητό περιέχει ένα μεγάλο ποσό λίπους και/ή πρωτεΐνών;
+ Επανυπολογισμός του λίπους και των πρωτεϊνών σε υδατάνθρακες και χρησιμοποιήστε το χαρακτηριστικό \"Εκτεταμμένους υδατάνθρακες\".
+ Επανυπολογισμός του λίπους και των πρωτεϊνών σε υδατάνθρακες και προσθέστε το στον υπολογισμό bolus.
+ Χρήση εκτεταμμένου bolus για κάλυψη λίπους και πρωτεϊνών.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Θέμα: Απομακρυσμένη Παρακολούθηση
+ Πώς μπορείτε να παρακολουθήσετε το AAPS του παιδιού σας από απόσταση;
+ Χρησιμοποιώντας την σελίδα του Nightscout.
+ Dexcom Follow app αν χρησιμοποιείτε το αυθεντικό Dexcom app (BG μόνο).
+ Dexcom Follow εάν χρησιμοποιείτε το xDrip app.
+ το xDrip τρέχει σε λειτουργία ακολούθου.
+ App κύκλωμα για το iPhone.
+ Spike app για iPhone.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Θέμα: ISF Διορθωτικός Παράγοντας
+ Υψηλότερη τιμή ISF οδηγεί σε λιγότερη χορήγηση ινσουλίνης, όταν το AAPS διορθώνει την υψηλή BG.
+ Χαμηλότερη τιμή ISF οδηγεί σε λιγότερη χορήγηση ινσουλίνης, όταν το AAPS διορθώνει την υψηλή BG.
+ Αλλάζοντας την τιμή του ISF δεν έχει καμία επίδραση στην ποσότητα ινσουλίνης που χορηγείται όταν το AAPS διορθώνει την υψηλή BG.
+ Θα πρέπει να εισάγετε την ISF στις Επιλογές.
+ Η αλλαγή της τιμής της ISF στο προφίλ σας είναι αρκετό για να εφαρμόσετε την αλλαγή αυτή.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Θέμα: IC Αναλογία Υδατανθράκων
+ Υψηλή αναλογία IC οδηγεί σε λιγότερη χορήγηση ινσουλίνης για μια δεδομένη ποσότητα υδατανθράκων.
+ Μικρή αναλογία IC οδηγεί σε λιγότερη χορήγηση ινσουλίνης για μια δεδομένη ποσότητα υδατανθράκων.
+ Αν έχετε 0 COB Ενεργούς Υδατ., αλλάζοντας την αναλογία IC θα οδηγήσει σε μια διαφορετική ποσότητα ινσουλίνης για να διορθωθεί μια συγκεκριμένη τιμή BG.
+ Το IC θα είναι διαφορετικό αν υπολογίζετε το ψωμί ως 10g ή 12g.
+ Η έννοια του IC είναι: Πόσες φέτες ψωμί καλύπτονται από 1 μονάδα ινσουλίνης.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Θέμα: Αλλαγή Προφίλ
+ Όταν καθορίζεται 90% στην αλλαγή προφίλ…
+ Ο Βασικός θα είναι 10% υψηλότερος.
+ Ο Βασικός θα είναι 10% χαμηλότερος.
+ Η τιμή IC θα είναι 10% υψηλότερη.
+ Η τιμή IC θα είναι 10% χαμηλότερη.
+ Η τιμή ISF θα είναι 10% υψηλότερη.
+ Η τιμή ISF θα είναι 10% χαμηλότερη.
+ Θα πάρετε περίπου 10% λιγότερη ινσουλίνη στο σύνολο.
+ Ο στόχος θα είναι 10% υψηλότερος.
+ Ο στόχος θα είναι 10% χαμηλότερος.
+ Μόνο ο χαμηλός στόχος θα είναι 10% χαμηλότερος.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Αν ξυπνήσετε 1 ώρα νωρίτερα από το συνηθισμένο, πώς θα πρέπει να ενημερώσετε το AAPS για την αλλαγή στο πρόγραμμά σας;
+ Ξεκινήστε μία αλλαγή προφίλ με χρονική μετατόπιση 1
+ Ξεκινήστε μία αλλαγή προφίλ με χρονική μετατόπιση -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Ξεκινήστε μία αλλαγή προφίλ με χρονική μετατόπιση 60
+ Ξεκινήστε μία αλλαγή προφίλ με χρονική μετατόπιση -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Θέμα: Βοήθεια με βασικό ρυθμό
+ Πού θα πάτε για βοήθεια με Βασικό ρυθμό κτλ.
+ Στην ομάδα του γιατρού σας
+ Google
+ FaceBook
+
diff --git a/app/src/main/res/values-el-rGR/objectives.xml b/app/src/main/res/values-el-rGR/objectives.xml
new file mode 100644
index 0000000000..7941ad4e61
--- /dev/null
+++ b/app/src/main/res/values-el-rGR/objectives.xml
@@ -0,0 +1,67 @@
+
+
+
+ Πίσω
+ Έναρξη
+ Επικύρωση
+ %1$d. Στόχος
+ Ο στόχος %1$d δεν ξεκίνησε
+ Ο στόχος %1$d δεν ολοκληρώθηκε
+ Δημιουργία παρακολούθησης και ανάλυση βασικού ρυθμού και αναλογιών
+ Επιβεβαιώστε ότι η BG φαίνεται στο Nightscout και τα δεδομένα της αντλίας φορτώθηκαν
+ Ξεκινήστε σε ανοιχτό κύκλωμα
+ Τρέξτε σε ανοιχτό κύκλωμα μερικές ημέρες και χειροκίνητα κάντε πολλούς προσωρινούς ρυθμούς. Φτιάξτε και χρησιμοποιήστε προσωρινούς και στανταρντ προσωρινούς στόχους (π.χ. για άσκηση ή θεραπεία υπογλυκαιμίας)
+ Κατανοήστε το ανοιχτό κύκλωμα, περιλαμβάνοντας τις προτάσεις για Προσωρινό ρυθμό
+ Βάση της εμπειρίας σας, αποφασίστε ποιο είναι το μέγιστο βασικής δόσης και αποθηκεύστε το στην αντλία και στις Επιλογές
+ Ξεκινήστε να κλείσετε το κύκλωμα με Σταμάτημα Χαμηλής Γλυκόζης (Low Glucose Suspend)
+ Τρέξτε σε κλειστό κύκλωμα με μέγιστο IOB = 0 για μερικές ημέρες χωρίς πολλά LGS - υπογλυκαιμίες
+ Ρυθμίζοντας το κλειστό κύκλωμα, αυξήστε το μέγιστο IOB πάνω από 0 και σταδιακά μειώστε τους στόχους BG
+ Τρέξτε το για λίγες ημέρες, και τουλάχιστον μία νύχτα χωρίς χαμηλό συναγερμό BG, πριν χαμηλώσετε τα όρια
+ Ρυθμίστε τον βασικό ρυθμό και τις αναλογίες αν χρειάζεται, και μετά ενεργοποιήστε το auto-sens
+ 1 επιτυχής εβδομάδα ημερήσιου κυκλώματος με κανονική εισαγωγή υδατανθράκων
+ Ενεργοποιώντας επιπρόσθετα χαρακτηριστικά για χρήση κατά την ημέρα, όπως τον Προχωρημένο Βοηθό Γεύματος
+ Ενεργοποιώντας επιπρόσθετα χαρακτηριστικά για χρήση κατά την ημέρα, όπως το SMB
+ Πρέπει να διαβάσετε τον οδηγό wiki και να αυξήσετε το ανώτατο όριο του IOB για να μπορέσει να λειτουργήσει σωστά το SMB! Μια καλή αρχή είναι μέγιστο IOB= μέσο bolus γεύματος + 3 x το μέγιστο ημερήσιο βασικού ρυθμού
+ BG διαθέσιμες στο NS
+ Η κατάσταση της αντλίας διαθέσιμη στο NS
+ Ξεκινήστε χειροκίνητα
+ Επιτεύχθηκε: %1$s
+ Μάθετε πώς να ελέγχετε το AndroidAPS
+ Κάντε διαφορετικές ενέργειες στο AndroidAPS
+ Θέστε το προφίλ στο 90% για 10 λεπτά (Παρατεταμένο πάτημα του προφίλ στην Επισκόπηση)
+ Προσομοίωση ένδειξης. Αποσυνδέστε την αντλία για 1 ώρα (Παρατεταμένο στο Ανοιχτό Κύκλωμα)
+ ... και επανασυνδέστε με τον ίδιο τρόπο
+ Φτιάξτε προσωρινούς στόχους με διάρκεια 10 λεπτά (Παρατεταμένο πάτημα στον στόχο σας)
+ Στην Διαμόρφωση ενεργοποιήστε την προσθήκη Ενέργειες, κάντε την ορατή ώστε να την βλέπετε από το δικό της tab
+ Εμφάνιση περιεχομένου της προσθήκης Κύκλωμα
+ Χρησιμοποιήστε τη λειτουργία κλίμακας πατώντας παρατεταμένα το διάγραμμα BG
+ Εισαγωγή
+ Κωδικός αποδεκτός
+ Μη έγκυρος κωδικός
+ Αποδείξτε τις γνώσεις σας
+ Διαβάστε και απαντήστε τις ερωτήσεις σωστά
+ Οι απαντήσεις εμφανίζονται στο: %1$s
+ Λάθος απάντηση!
+ Επόμενο ημιτελές
+ Κωδικός αιτήματος: %1$s
+ (ελέγξτε όλες τις σωστές απαντήσεις)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Δεν είστε συνδεδεμένοι στο internet
+ Απέτυχε η ανάκτηση ώρας
+ Αντικειμενικές προϋποθέσεις δεν πληρούνται
+
+ %1$d ημέρα
+ %1$d ημέρες
+
+
+ %1$d hour
+ %1$d ώρες
+
+
+ %1$d minute
+ %1$d λεπτά
+
+
diff --git a/app/src/main/res/values-el-rGR/strings.xml b/app/src/main/res/values-el-rGR/strings.xml
index 55af02c156..cd860161bc 100644
--- a/app/src/main/res/values-el-rGR/strings.xml
+++ b/app/src/main/res/values-el-rGR/strings.xml
@@ -5,7 +5,6 @@
-
Ασφάλεια ΘεραπειώνΜέγιστο Επιτρεπτό bolus[U]Μέγιστο Επιτρεπτό υδατανθράκων [g]
@@ -57,9 +56,6 @@
Παρακολουθεί και ελέγχει το AndroidAPS χρησιμοποιώντας το ρολόι σας WearOS.Δείτε πληροφορίες σχετικά με το κύκλωμά σας στην πρόσοψη xDrip +.Ελεγξτε απομακρυσμένα το AndroidAPS χρησιμοποιώντας τις εντολές SMS.
- Πίσω
- Έναρξη
- ΕπικύρωσηΜονάδεςDIAIC
@@ -102,6 +98,7 @@
ΠροφίλΔεδομένα ΓεύματοςΑποτέλεσμα
+ Αποτέλεσμα: %1$s %2$sΜη διαθέσιμα δεδομένα γλυκόζηςΔεν απαιτείται αλλαγήΑίτημα
@@ -177,9 +174,6 @@
Μη υποστηριζόμενη έκδοση NSClientΜη υποστηριζόμενη έκδοση NightscoutNSClient δεν εγκαταστάθηκε. Τα δεδομένα χάθηκαν!
- BG διαθέσιμες στο NS
- Η κατάσταση της αντλίας διαθέσιμη στο NS
- Ξεκινήστε χειροκίνηταΤΟ ΚΥΚΛΩΜΑ ΑΠΕΝΕΡΓΟΠΟΙΗΘΗΚΕ ΑΠΟ ΠΕΡΙΟΡΙΣΜΟΥΣΒασική ΙΟΒΕνεργός Περιορισμός Bolus
@@ -222,7 +216,7 @@
Προσ ΡυθμόςΕκτεταμμένο BolusΈκδοση Nightscout:
- Χαμένες
+ Λείπει %1$dgΕπιλογές εξήχθησανΕξαγωγή ρυθμίσεων σεΕισαγωγή ρυθμίσεων από
@@ -317,21 +311,6 @@
Πιέστε STOPΑναμονή για αντλίαΠρος έγχυση %1$.2fU
- Δημιουργία παρακολούθησης και ανάλυση βασικού ρυθμού και αναλογιών
- Επιβεβαιώστε ότι η BG φαίνεται στο Nightscout και τα δεδομένα της αντλίας φορτώθηκαν
- Ξεκινώντας ανοιχτό κύκλωμα
- Τρέξτε σε ανοιχτό κύκλωμα μερικές ημέρες και χειροκίνητα κάντε πολλούς προσωρινούς ρυθμούς. Φτιάξτε και χρησιμοποιήστε προσωρινούς και στανταρντ προσωρινούς στόχους (π.χ. για άσκηση ή θεραπεία υπογλυκαιμίας)
- Κατανοήστε το ανοιχτό κύκλωμα, περιλαμβάνοντας τις προτάσεις για Προσωρινό ρυθμό
- Βάση της εμπειρίας σας, αποφασίστε ποιο είναι το μέγιστο βασικής δόσης και αποθηκεύστε το στην αντλία και στις Επιλογές
- Ξεκινήστε να κλείσετε το κύκλωμα με Σταμάτημα Χαμηλής Γλυκόζης (Low Glucose Suspend)
- Εκτελέστε σε κλειστό κύκλωμα με μέγιστο IOB = 0 για μερικές ημέρες χωρίς πολλά LGS - υπογλυκαιμίες
- Ρυθμίζοντας το κλειστό κύκλωμα, αυξήστε το μέγιστο IOB πάνω από 0 και σταδιακά μειώστε τους στόχους BG
- Τρέξτε το για λίγες ημέρες, και τουλάχιστον μία νύχτα χωρίς χαμηλό συναγερμό BG, πριν χαμηλώσετε τα όρια
- Ρυθμίστε τον βασικό ρυθμό και τις αναλογίες αν χρειάζεται, και μετά ενεργοποιήστε το auto-sens
- 1 επιτυχής εβδομάδα ημερήσιου κυκλώματος με κανονική εισαγωγή υδατανθράκων
- Ενεργοποιώντας επιπρόσθετα χαρακτηριστικά για χρήση κατά την ημέρα, όπως τον Προχωρημένο Βοηθό Γεύματος
- Ενεργοποιήστε άλλες λειτουργίες για χρήση κατά την ημέρα, όπως SMB
- Πρέπει να διαβάσετε τον οδηγό wiki και να αυξήσετε το ανώτατο όριο του IOB για να μπορέσει να λειτουργήσει σωστά η SMB! Μια καλή αρχή είναι μέγιστο IOB= μέσο bolus γεύματος + 3 x το μέγιστο ημερήσιο βασικού ρυθμούΦτάσατε το επιτρεπτό όριοΔεν επηλέχθηκε προφίλΤο κύκλωμα απενεργοποιήθηκε
@@ -569,8 +548,8 @@
Ενεργοποίηση του φωτισμού κατάστασης για cage, iage, sage, reservoir και επίπεδο μπαταρίας στην αρχική οθόνη.Όριο προειδοποίησης χαμηλής αμπούλας [U]Όριο προειδοποίησης πολύ χαμηλής αμπούλας [U]
- Όριο προειδοποίησης χαμηλής μπαταρίας [%%]
- Όριο προειδοποίησης πολύ χαμηλής μπαταρίας [%%]
+ Όριο προειδοποίησης χαμηλής μπαταρίας [%]
+ Όριο προειδοποίησης πολύ χαμηλής μπαταρίας [%]IOBCOBΈκδοση
@@ -640,6 +619,7 @@
ΑκύρωσηΔεν έχουν φορτωθεί όλα τα προφίλ!Οι τιμές δεν αποθηκεύτηκαν!
+ Ενεργοποιήστε εκπομπές σε άλλες εφαρμογές (όπως το xDrip). Μην το ενεργοποιήσετε εάν έχετε περισσότερες από μία εγκατεστημένες εφαρμογές του AAPS ή NSClient!Ενεργοποιήστε τις τοπικές αποστολές.ΔΡΑΣΤΗΡΙΟΤΗΤΑ & FEEDBACKΥΔΑΤΑΝΘΡΑΚΕΣ & BOLUS
@@ -863,8 +843,6 @@
Η αλλαγή προφίλ λείπει. Αλλάξτε το προφίλ ή πατήστε \"Ενεργοποίηση Προφίλ\" στο Τοπικό Προφίλ.Αριθμός bolusΑριθμός TBR
- Ο στόχος %1$d δεν ξεκίνησε
- Ο στόχος %1$d δεν ολοκληρώθηκεΗ αντλία δεν υποστηρίζει προσωρινό βασικό ρυθμόΔιαβάζεται από την αντλία μη έγκυρος βασικός ρυθμόςΤο κλειστό κύκλωμα είναι απενεργοποιημένο στις Επιλογές
@@ -986,7 +964,6 @@
Ολοκληρώθηκε, συγχαρητήρια!Δεν ολοκληρώθηκε ακόμηΟ χρόνος που πέρασε
- %1$d. ΣτόχοςPoctechΛάβετε τις τιμές BG από την εφαρμογή PoctechΛάβετε τιμές BG από Tomato app (MiaoMiao)
@@ -1170,8 +1147,6 @@
Αποστολή προσωρινών ρυθμώνΑποστολή αλλαγών προφίλ, προσωρινών στόχωνΑποστολή BG βαθμονομήσεων
- Αλλαγή σε Θερινή ώρα σε 24h ή λιγότερο
- Η Θερινή ώρα αλλάζει σε λιγότερο από 3 ώρες - Απενεργοποιήθηκε το κλειστό κύκλωμαπεριορισμός εσωτερικής μνήμηςΕλευθερώστε τουλάχιστον %1$d MB από εσωτερική μνήμη! Κύκλωμα απενεργοποιήθηκε!Λάθος μορφή αρχείου
@@ -1297,6 +1272,7 @@
Δεν ξεκίνησεΑρχικοποίηση του RileyLink…RileyLink Σφάλμα
+ Συντονισμός RileyLink και ΑντλίαςΠρόβλημα σύνδεσης με την ΑντλίαΣυνδέθηκε
@@ -1366,6 +1342,15 @@
Λάβετε Προσωρινό ΡυθμόΒάλτε Προσωρινό ΡυθμόΒάλτε Bolus
+ Αλλαγή προφίλ σε
+ Αλλαγή προφίλ σε %1$s
+ Τελευταία σύνδεση με αντλία
+ Τελευταία σύνδεση με αντλία [λεπτά πριν]
+ Τελευταία σύνδεση με αντλία %1$s %2$s λεπτά πριν
+ Στείλτε SMS: %1$s
+ Στείλτε SMS προς όλους τους αριθμούς στις Επιλογές
+ Στείλτε SMS με κείμενο
+ %2$+.2fU]]>Bolus constraint applied: %2$.2fU to %3$.2fU]]>!!!!! Μικρή απορρόφηση υδατανθράκων ανιχνεύτηκε: %2$d%% της ώρας. Τσεκάρετε τους υπολογισμούς σας. COB μπορεί να υπερεκτιμήθηκε και να δόθηκε περισσότερη ινσουλίνη!!!!!]]>%1$.0f / %2$d U
@@ -1373,38 +1358,17 @@
Ο Υπολογισμός Bolus κάνει υπολογισμούς αλλά μόνο αυτό το μέρος της υπολογίσημης ινσουλίνης χορηγείται. Χρήσιμο με τον αλγόριθμο SMB.Φόρτωση ...Αναβολή
- Επιτεύχθηκε: %1$s
- Μάθε πως να ελέγχεις το AndroidAPS
- Κάντε διαφορετικές ενέργειες στο AndroidAPS
- Θέστε το προφίλ στο 90% για 10 λεπτά (Παρατεταμένο πάτημα του προφίλ στην Επισκόπηση)
- Προσομοίωση ένδειξης. Αποσυνδέστε την αντλία για 1 ώρα (Παρατεταμένο στο Ανοιχτό Κύκλωμα)
- ... και επανασυνδέστε με τον ίδιο τρόπο
- Φτιάξτε προσωρινούς στόχους με διάρκεια 10 λεπτά (Παρατεταμένο πάτημα στον στόχο σας)
- Στην Διαμόρφωση ενεργοποιήστε την προσθήκη Ενέργειες, κάντε την ορατή ώστε να την βλέπετε από το δικό της tab
- Εμφάνιση περιεχομένου της προσθήκης Κύκλωμα
- Χρησιμοποιήστε τη λειτουργία κλίμακας πατώντας παρατεταμένα το διάγραμμα BG
- Εισαγωγή
- Εισαγάγετε τον κωδικό που λαμβάνετε από τους προγραμματιστές για να παρακάμψετε τους υπόλοιπους στόχους
- Κωδικός αποδεκτός
- Μη έγκυρος κωδικός
- Αποδείξτε τις γνώσεις σας
- Διαβάστε και απαντήστε τις ερωτήσεις σωστά
- Οι απαντήσεις εμφανίζονται στο: %1$s
- Λάθος απάντηση!
- Επόμενο ημιτελές
+ Εύρος χρόνου
+ Ο χρόνος είναι μεταξύ %1$s και %2$s
+ Ανάμεσα Κλείσιμο
- Κωδικός αιτήματος: %1$s
- (ελέγξτε όλες τις σωστές απαντήσεις)
-
- %1$d ημέρα
- %1$d ημέρες
-
-
- %1$d ώρα
- %1$d ώρες
-
-
- %1$d λεπτό
- %1$d λεπτά
-
+ Αυξείστε την μέγιστη βασική τιμή, επειδή η ρύθμιση είναι χαμηλότερη από τη μέγιστη βασική στο προφίλ σας
+ Μη έγκυρο μήνυμα
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Οδηγός Bolus
+ min
+ %1$dg
diff --git a/app/src/main/res/values-es-rES/exam.xml b/app/src/main/res/values-es-rES/exam.xml
index 70489fbc5e..c3c2af8b25 100644
--- a/app/src/main/res/values-es-rES/exam.xml
+++ b/app/src/main/res/values-es-rES/exam.xml
@@ -1,3 +1,169 @@
-
+
+ ¿Qué es cierto acerca de DIA?
+ Tema: la Duración de la Acción de la Insulina
+ El valor mínimo es de 3 horas.
+ El valor mínimo es de 5 horas.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ El significado es igual al parámetro DIA utilizado en su bomba.
+ Debes determinar tu valor individual (pero no menos de 5 horas).
+ Tema: Objetivo Temporal por Hipoglucemia
+ ¿Cuál es la razón principal para establecer un objetivo temporal por hipoglucemia?
+ Para evitar que la glucemia caiga si ya hay una basal temporal a cero activada.
+ Para evitar que AAPS inyecte demasiada insulina después de una subida causada por los carbohidratos de acción rápida utilizados para tratar una bajada en las lecturas de glucosa.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ ¿Qué perfil puede ser usado y configurado estando desconectado?
+ Tema: Perfil fuera de línea
+ El perfil NS puede ser usado pero no configurado.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Tema: Desconectando de la bomba
+ ¿Qué se debe hacer al desconectar la bomba?
+ Haga clic en \"Desconectar bomba\" para que AAPS sepa que no se está inyectando insulina.
+ Haga clic en \'Suspender lazo \' para que la AAPS deje de estar en lazo cerrado mientras la bomba está desconectada.
+ No cambies nada en AAPS, sólo desconecta la bomba.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Tema: Ajustes AndroidAPS
+ ¿Cuál es la mejor práctica para hacer copias de seguridad de tus ajustes?
+ Exportarlos localmente desde el menú de Mantenimiento.
+ Guardar archivo exportado a otro lugar como correo electrónico, Dropbox, Google drive…
+ Exportarlos justo después de la instalación de AAPS.
+ Exportarlos después de realizar cambios en la configuración.
+ Exportarlos tras completar un objetivo.
+ Exportarlos al terminar la configuración inicial.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Tema: Lecturas de CGM ruidosas
+ ¿Qué se debe hacer si los datos de CGM tienen ruido?
+ Nada, AAPS se ocupará de ello.
+ Desactivar el lazo cerrado para evitar una sobredosis.
+ Sustituya el sensor de CGM.
+ Apagar el movil.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Verifique que la aplicación CGM suaviza los datos de glucosa.
+ Tema: Ejercicio
+ ¿Cómo puedes ayudar al sistema a lidiar con el ejercicio?
+ Utilización de la característica de objetivo temporal.
+ Realice un cambio de perfil por debajo del 100%.
+ Realice un cambio de perfil por encima del 100%.
+ Detener el lazo.
+ Establezca un objetivo temporal de actividad antes de iniciar el ejercicio.
+ Establecer un objetivo temporal de actividad después de comenzar el ejercicio conduce a peores resultados que si se inicia antes de hacerlo.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Tema: Lazo inhabilitado/suspendido
+ ¿Recibo insulina cuando el lazo está desactivado/suspendido?
+ Sí, la insulina basal sigue siendo entregada.
+ No, la administración de la insulina está detenida.
+ Tema: Basal, ISF, y IC Pruebas
+ ¿Cuándo debo validar los valores basales, ISF y IC?
+ Antes de empezar en uso de lazo.
+ Si se experimentan valores bajos de BG frecuentemente.
+ Si se experimentan valores altos de BG frecuentemente.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Tema: Requisitos previos
+ ¿Qué necesito?
+ Información de perfil validada (Basal, IC, ISF, DIA).
+ Un ordenador para crear un APK.
+ Un teléfono compatible.
+ Un Coche.
+ Nightscout para pasar los objetivos.
+ Una cuenta de Tidepool.
+ Una cuenta de Google.
+ Una cuenta de Github.
+ Experiencia en desarrollo de Android.
+ Una bomba MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Un Smartwatch.
+ Un CGM soportado.
+ Tema: Actualización de AndroidAPS
+ ¿Qué es verdad?
+ Tienes que tener instalado Git.
+ Actualice tan pronto como se libere la nueva versión y prevea tener tiempo suficiente para hacerlo.
+ Debes usar las mismas claves de firma.
+ Nunca actualice si el sistema está funcionando bien.
+ Pregúntale a tu amigo por el nuevo APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Tema: Resolución de problemas
+ Donde buscar ayuda?
+ Únete al grupo AndroidAPS de Facebook.
+ Lea la documentación de AndroidAPS.
+ Visite AndroidAPS Gitter Room.
+ Visite el soporte de Google AndroidAPS
+ Hable con su endocrinólogo.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Tema: Plugins sobre Insulina
+ ¿Qué marca de insulina se puede utilizar con el plugin Ultra-Rapid-Oref?
+ Fiasp®
+ NovoRapid ®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Tema: Plugins de sensibilidad
+ ¿Qué algoritmo de sensibilidad tiene un rango de tiempo configurable?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ ¿Qué plugin de sensibilidad se debe utilizar para la funcionalidad UAM?
+ Tema: Errores en la entrada de carbohidratos
+ ¿Qué deberías hacer si has hecho una entrada incorrecta de carbohidratos?
+ En los Tratamientos, eliminar la entrada incorrecta de carbohidratos. Introducir los nuevos valores de carbohidratos.
+ Cómo agregar una insulina falsa utilizando la función llenado de cánula
+ Tema: Comida con Grasa y Proteína
+ ¿Qué hacer si su comida contiene una gran cantidad de grasas y /o proteínas?
+ Recalcular grasas y proteínas a los carbohidratos y utilizar la función \"carbohidratos extendidos\".
+ Recalcular grasa y proteínas a los carbohidratos y añadirlo al cálculo del bolo.
+ Utilice el bolus extendido para cubrir grasas y proteínas.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Tema: Supervisión remota
+ ¿Cómo puede supervisar la AAPS de su hijo de forma remota?
+ Cómo utilizar un sitio de \"Nightscout\".
+ App Dexcom seguidora si está usando la aplicación original Dexcom (sólo valores BG).
+ Dexcom Seguidora si está utilizando la aplicación xDrip.
+ xDrip ejecutado en modo seguidor.
+ Aplicación de Loop en el iPhone.
+ App de Spike en el iPhone.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Tema: Factor de sensibilidad de la insulina
+ Los valores más altos de ISF llevan a una menor cantidad de insulina cuando AAPS corrige los valores altos de glucemia.
+ Los valores más bajos de ISF llevan a una menor cantidad de insulina cuando AAPS corrige los valores altos de glucemia.
+ El cambio de los valores de ISF no afecta a la cantidad de insulina que se entrega cuando AAPS corrige para compensar los valores altos de glucemia.
+ Tiene que especificar ISF en Preferencias.
+ El cambio del valor de ISF en el perfil es suficiente para aplicar el cambio.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Tema: El ratio IC
+ Los ratios IC más altos conducen a menos insulina entregada por una cantidad determinada de carbohidratos.
+ Los ratios IC más bajos conducen a menos insulina entregada por una cantidad determinada de carbohidratos.
+ Si tiene 0 COB, cambiar la ratio IC conducirá a una cantidad distinta de insulina para corregir un valor de glucemia determinado.
+ El IC será diferente si cuenta con una unidad de pan como 10g o 12g.
+ IC significa: Cuántas unidades de pan están cubiertas por 1U de insulina.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Tema: Cambio de perfil
+ Especificando el 90% en el cambio de perfil…
+ Las basales serán 10% más altas.
+ Las basales serán 10% más bajas.
+ El valor IC será 10% superior.
+ El valor IC será 10% inferior.
+ El valor sensibilidad será 10% superior.
+ El valor sensibilidad será 10% inferior.
+ En total obtendrás alrededor del 10% menos insulina.
+ El objetivo será 10% más alto.
+ El objetivo será 10% más bajo.
+ Sólo el objetivo inferior será 10% inferior.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profilewitch#profile-switch
+ Si se despierta 1h antes de lo habitual, ¿cómo debe notificar a AAPS el cambio en su horario?
+ Iniciar un cambio de perfil con un intervalo de tiempo de 1
+ Iniciar un cambio de perfil con un intervalo de tiempo de -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Iniciar un cambio de perfil con un intervalo de tiempo de 60
+ Iniciar un cambio de perfil con un intervalo de tiempo de -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Tema: Ayuda con tasas basales
+ A donde ir para obtener ayuda con tasa basal y demás.
+ Tu equipo de diabetes
+ Google
+ Facebook
+ Otra medicación
+ La AAPS reduce el BR para aumentar la glucosa en la sangre. Los inhibidores del grupo de las SGLT2 (gliflozinas) pueden prevenir el aumento esperado de BG y, por lo tanto, pueden producir una deficiencia de insulina peligrosa (DKA).
+\nLos nombres comunes de marca son: Invokana ®, Forxiga ®, Steglatro ®, Suglat ®, Apleway ®, Synjardy ®, Vokanamet ®, Xigduo ®.\n\nI prometo que no tomaré este tipo de medicamentos cuando use AAPS o desactivará el lazo cerrado antes de usar estas drogas.
+
diff --git a/app/src/main/res/values-es-rES/insight_alert_titles.xml b/app/src/main/res/values-es-rES/insight_alert_titles.xml
index f5babbe83a..c47fc15c82 100644
--- a/app/src/main/res/values-es-rES/insight_alert_titles.xml
+++ b/app/src/main/res/values-es-rES/insight_alert_titles.xml
@@ -10,7 +10,7 @@
Pila bajaFecha/hora no válidaFin de la garantía
- TBR cancelada
+ Basal Temporal canceladaBolo canceladoAviso de préstamo de infusoraReservorio no insertado
diff --git a/app/src/main/res/values-es-rES/objectives.xml b/app/src/main/res/values-es-rES/objectives.xml
new file mode 100644
index 0000000000..1a24ac5d0c
--- /dev/null
+++ b/app/src/main/res/values-es-rES/objectives.xml
@@ -0,0 +1,67 @@
+
+
+
+ Atrás
+ Inicio
+ Verificar
+ %1$d. Objetivo
+ Objetivo %1$d no iniciado
+ Objetivo %1$d no finalizado
+ Configurar la visualización y la monitorización, analizar los valores basales y las ratios
+ Comprobar que los datos de glucosa están disponibles en Nightscout, y que los datos de la bomba de insulina se están subiendo
+ Comenzando en lazo abierto
+ Ejecutar en modo de lazo abierto durante unos días, y aceptar manualmente las basales temporales. Configure y use objetivos temporales y predeterminados (por ejemplo, para actividad o carbohidratos para hipoglucemia)
+ Entender el lazo abierto, incluidas las recomendaciones de basales temporales
+ Sobre la base de esa experiencia, decidir valores de máximo basal, y ajustar la bomba y preferencias
+ Iniciando el lazo cerrado con suspensión con baja glucosa
+ Ejecutar en lazo cerrado con max IOB=0 durante unos días sin demasiados valores bajos de glucosa
+ Ajuste del lazo cerrado, aumentando máximo IOB por encima de 0 y bajando gradualmente objetivos BG
+ Usar unos cuantos días, y al menos una noche sin alarmas de glucosa baja, antes de bajar valor de glucosa
+ Ajustar las basales y ratios, si es necesario, y luego activar auto-sens
+ Una semana con éxito en lazo cerrado durante el día con entrada regular de carbohidratos
+ Habilitar funciones adicionales para su uso durante el día, como el asistente de comida avanzado
+ Habilitar funciones adicionales para uso durante el día como SMB
+ ¡Debes leer el wiki y subir maxIOB para que SMB funcione bien! Para comenzar un buen valor sería maxIOB = bolo de comida medio + 3 x máximo basal diario
+ Glucosa disponible en NS
+ Estado de la bomba disponible en NS
+ Aprobación Manual
+ Completado: %1$s
+ Aprende a controlar AndroidAPS
+ Realice diferentes acciones en AndroidAPS
+ Establecer perfil 90% durante 10 min (Pulsación larga en nombre del perfil en Resumen)
+ Simular ducha. Desconectar bomba durante 1h (Pulsación larga en el lazo abierto)
+ ... y volver a conectar de la misma manera
+ Crear un objetivo temporal personalizado con 10 min de duración (Pulsación larga en tu objetivo actual)
+ En Config Builder habilitar el plugin Acciones, hágalo visible y muestre su contenido desde el menú superior
+ Mostrar contenido del plugin Loop
+ Usar función de escala mediante un gráfico BG pulsado largo
+ Intro
+ Código aceptado
+ Código no válido
+ Compruebe su conocimiento
+ Responder correctamente
+ Respuesta deshabilitada a: %1$s
+ Respuesta incorrecta!
+ Siguien&te sin terminar
+ Solicitar código: %1$s
+ (compruebe todas las respuestas correctas)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Sin conexión a Internet
+ Fallo tiempo de recuperación
+ No se cumplen los requisitos de objetivo
+
+ %1$d día
+ %1$d días
+
+
+ %1$d hora
+ %1$d horas
+
+
+ %1$d minuto
+ %1$d minutos
+
+
diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml
index 7b4720874e..0b5ac4ac22 100644
--- a/app/src/main/res/values-es-rES/strings.xml
+++ b/app/src/main/res/values-es-rES/strings.xml
@@ -5,8 +5,7 @@
-
- Seguridad de tratamientos
+ Seguridad tratamientosMáximo Bolo permitido [U]Máximos carbohidratos permitidos [g]Preferencias
@@ -57,9 +56,6 @@
Usar tu reloj WearOS para observar y controlar AndroidAPS.Mostrar información sobre tu lazo en tu esfera xDrip+.Control remoto de AndroidAPS mediante comandos SMS.
- Atrás
- Inicio
- VerificarUnidadesDIA (Duración Insulina Activa)IC (Ratio Insulina/Carbohidratos)
@@ -102,6 +98,7 @@
PerfilDatos de comidasResultado
+ Resultado: %1$s %2$ssNo hay disponibles datos de glucosaNinguna acción requeridaSolicitud
@@ -177,9 +174,6 @@
Versión de NSClient no soportadaVersión no aceptada de NightscoutNSClient no instalado. ¡Registro perdido!
- BG disponible en NS
- Estado de la bomba disponible en NS
- Aprobación ManualLOOP DESACTIVADO POR RESTRICCIONESBasal IOBRestricción aplicada en bolo
@@ -222,7 +216,7 @@
Basal TemporalBolo extendidoNightscout versión:
- Faltan
+ Falta %1$dgPreferencias exportadasExportar ajustes aImportar configuración de
@@ -317,21 +311,6 @@
DETENER PULSADOEsperando bombaSe van a infundir %1$.2fU
- Configuración de visualización y monitorización, y análisis de basales y ratios
- Comprobar que los datos de BG están disponibles en Nightscout, y que los datos de la bomba de insulina se están subiendo
- Comenzando en lazo abierto
- Ejecutar en modo de lazo abierto durante unos días, y aceptar manualmente las basales temporales. Configure y use objetivos temporales y predeterminados (por ejemplo, para actividad o carbohidratos para hipoglucemia)
- Entender el lazo abierto, incluidas las recomendaciones de basales temporales
- Sobre la base de esa experiencia, decidir valores de máximo basal, y ajustar la bomba y preferencias
- Iniciando el lazo cerrado con suspensión con baja glucosa
- Ejecutar en lazo cerrado con max IOB=0 durante unos días sin demasiados valores bajos de glucosa
- Ajuste del lazo cerrado, aumentando máximo IOB por encima de 0 y bajando gradualmente objetivos BG
- Usar unos cuantos días, y al menos una noche sin alarmas de glucosa baja, antes de bajar valor de glucosa
- Ajustar las basales y ratios, si es necesario, y luego activar auto-sens
- Una semana con éxito en lazo cerrado durante el día con entrada de carbohidratos
- Habilitar funciones adicionales para su uso durante el día, como asistente de comida avanzado
- Habilitar funciones adicionales para uso durante el día como SMB
- ¡Debes leer el wiki y subir maxIOB para que SMB funcione bien! Para comenzar un buen valor sería maxIOB = bolo de comida medio + 3 x máximo basal diarioAlcanzado el límite permitidoSin perfil seleccionadoLazo se ha desactivado
@@ -569,8 +548,8 @@
Habilita luces de estado extendidas para tiempo de cánula, tiempo de insulina, tiempo del sensor, reservorio y nivel de batería en pantalla de inicio.Umbral de advertencia de nivel de reservorio [U]Umbral crítico de nivel de reservorio [U]
- Umbral de advertencia de nivel de batería [%%]
- Umbral crítico de nivel de batería [%%]
+ Umbral de advertencia de nivel de pila [%]
+ Umbral crítico de nivel de batería [%]IOBCOBFirmware
@@ -640,6 +619,7 @@
CancelarFaltan perfiles por cargar!Valores no guardados!
+ Habilite las transmisiones a otras aplicaciones (como xDrip). ¡ No habilite si tiene más de una instancia de AAPS o NSClient instalada!Permitir emisión de mensajes localmente.ACTIVIDAD Y FEEDBACKCARBS Y BOLUS
@@ -863,8 +843,6 @@
Falta Cambio de Perfil. Haga un Cambio de Perfil o presione \"Activar perfil\" en PerfilLocal.Contador BolosContador TBR
- Objetivo %1$d no iniciado
- Objetivo %1$d no finalizadoLa bomba no tiene capacidad basal temporalTasa Basal no valida en la bombaLazo cerrado deshabilitado en preferencias
@@ -986,7 +964,6 @@
¡Logrado, bien hecho!No logradoTiempo agotado
- %1$d. ObjetivoPoctechRecibir valores de glucosa de PoctechRecibir valores de glucosa de Tomato app (MiaoMiao)
@@ -1170,8 +1147,8 @@
Subir basales temporalesSubir conmutaciones de perfil, objetivos tempsSubir pruebas BG
- Cambio al horario de verano/invierno en menos de 24 horas
- Cambio al horario de verano/invierno hace menos de 3 horas - Lazo cerrado deshabilitado
+ Cambio al horario de verano en menos de 24 horas
+ Cambio al horario de verano hace menos de 3 horas - Lazo cerrado deshabilitadorestricción de almacenamiento internoLibera al menos %1$d MB de almacenamiento interno. ¡Loop desactivado!Formato incorrecto
@@ -1259,6 +1236,8 @@
No seleccionado (Vista simple)Alcalina (vista extendida)Litio (vista extendida)
+ NiZn (vista ampliada)
+ Bolos/Depuración de TratamientosESCANEARDETENER
@@ -1297,6 +1276,7 @@
No iniciadoInicialización de RileyLink…Error de RileyLink
+ Configurando RileyLink y la bombaProblema al conectar con la infusoraConectado
@@ -1366,45 +1346,35 @@
Obtener la basal temporalEstablecer la basal temporalFijar Bolo
+ Cambiar perfil a
+ Cambiar perfil a %1$s
+ Última conexión con la bomba
+ Última conexión con la bomba [ minutos atrás]
+ Última conexión con la bomba hace %1$s %2$s min
+ Enviar a %1$s
+ Enviar SMS a todos los números en las preferencias
+ Mandar mensaje SMS
+ %2$+.2fU]]>Restricción de bolo aplicada: %2$.2fU a %3$.2fU]]>
- ! Se ha detectado una absorción lenta de hidratos de carbono: %2$d% de tiempo. Compruebe de nuevo su calculo. Los COB se pueden sobrestimar, por lo que ¡se podría administrar más insulina de la cuenta!]]>
+ ! Se ha detectado una absorción lenta de hidratos de carbono: %2$d%% de tiempo. Compruebe de nuevo su calculo. Los COB se pueden sobrestimar, por lo que ¡se podría administrar más insulina de la cuenta!]]>%1$.0f/%2$dUAdministrar esta parte del resultado del asistente de bolos [%]El asistente de bolos realiza el cálculo, pero solo se entrega esta parte de la insulina calculada. Útil con el algoritmo SMB.Cargando...Silenciar
- Completado: %1$s
- Aprende a controlar AndroidAPS
- Realice diferentes acciones en AndroidAPS
- Establecer perfil 90% durante 10 min (Pulsación larga en nombre del perfil en Resumen)
- Simular ducha. Desconectar bomba durante 1h (Pulsación larga en el bucle abierto)
- ... y volver a conectar de la misma manera
- Crear un objetivo temporal personalizado con 10 min de duración (Pulsación larga en tu objetivo actual)
- En Config Builder habilitar el plugin Acciones, hágalo visible y muestre su contenido desde el menú superior
- Mostrar contenido del plugin Loop
- Usar función de escala mediante un gráfico BG pulsado largo
- Intro
- Introduzca el código obtenido de los desarrolladores para eludir el resto de objetivos
- Código aceptado
- Código no válido
- Compruebe su conocimiento
- Responder correctamente
- Respuesta deshabilitada a: %1$s
- Respuesta incorrecta!
- Siguien&te sin terminar
+ Intervalo de tiempo
+ El tiempo está entre %1$s y %2$s
+ Entre Cerrar
- Solicitad código: %1$s
- (compruebe todas las respuestas correctas)
-
- %1$d día
- %1$d días
-
-
- %1$d hora
- %1$d horas
-
-
- %1$d minuto
- %1$d minutos
-
+ Aumentar el valor basal máximo porque el ajuste es inferior a tu base máxima en el perfil
+ El cuerpo del mensaje es inválido
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Asistente Bolus
+ min
+ %1$dg
+ Activado
+ Desactivado
diff --git a/app/src/main/res/values-fi-rFI/objectives.xml b/app/src/main/res/values-fi-rFI/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-fi-rFI/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-fi-rFI/strings.xml b/app/src/main/res/values-fi-rFI/strings.xml
index 7879323748..df88c88e20 100644
--- a/app/src/main/res/values-fi-rFI/strings.xml
+++ b/app/src/main/res/values-fi-rFI/strings.xml
@@ -5,7 +5,6 @@
-
diff --git a/app/src/main/res/values-fr-rFR/exam.xml b/app/src/main/res/values-fr-rFR/exam.xml
index 70489fbc5e..c908bb5b59 100644
--- a/app/src/main/res/values-fr-rFR/exam.xml
+++ b/app/src/main/res/values-fr-rFR/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Qu\'est-ce qu\'il y a de vrai pour le DAI (Durée Action Insuline)?
+ Rubrique : Durée de l\'Action de l\'Insuline
+ La valeur minimale est de 3 heures.
+ La valeur minimale est de 5 heures.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Configuration/Config-Builder.html?#insulin
+ La signification est la même que le paramètre DAI utilisé dans votre pompe.
+ Vous devez déterminer votre valeur personnelle (mais pas moins de 5 heures).
+ Rubrique: Cible Temporaire Hypo
+ Quelle est la principale raison de fixer une CT hypo ?
+ Pour empêcher la glycémie de baisser si aucune basale temporaire en cours d\'exécution.
+ Afin d\'éviter qu\' AAPS n\'administre trop d\'insuline suite à une forte montée de la glycémie causée par des glucides à action rapide utilisés pour traiter une hypoglycémie.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/temptarget.html
+ Quel profil peut être utilisé et configuré hors ligne?
+ Rubrique : Profil Hors Ligne
+ Le profil NS peut être utilisé, mais il n\'est pas configuré.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Configuration/Config-Builder.html#profile
+ Rubrique : Déconnexion de la pompe
+ Que faire en déconnectant la pompe ?
+ Cliquez sur \"Déconnecter la pompe\" pour que APS sache qu\'aucune insuline ne soit délivrée.
+ Cliquez sur \"Suspendre la boucle\" pour que AAPS s\'arrête tant que la pompe est déconnectée.
+ Ne changez rien dans AAPS, débranchez juste la pompe.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/FAQ.html#other-settings
+ Rubrique : Paramètres AndroidAPS
+ Quelles sont les meilleures pratiques pour sauvegarder vos paramètres ?
+ Les exporter localement à partir du menu Maintenance.
+ Stocker le fichier exporté à un autre endroit comme un email, Dropbox, Google drive…
+ Les exporter juste après l\'installation d\'AAPS.
+ Exportez-les après avoir modifié les paramètres.
+ Exportez-les après avoir atteint un objectif.
+ Les exporter lorsque vous terminez le paramétrage initial.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Rubrique : Lectures MGC incohérentes
+ Que faut-il faire si les données de MGC sont bruitées ?
+ Rien, AAPS s\'en occupera.
+ Désactivez la boucle pour éviter un surdosage.
+ Remplacer le capteur MGC.
+ Éteindre le téléphone.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Vérifiez que votre application de MGC filtre les glycémies.
+ Rubrique : Activités physiques
+ Comment pouvez-vous aider le système à gérer l\'exercice physique ?
+ Utilisation de la fonction cible temporaire.
+ Faire un changement de profil inférieur à 100%.
+ Faire un changement de profil supérieur à 100%.
+ Arrêter la boucle.
+ Définissez une cible temporaire d\'activité avant de commencer votre effort.
+ Définir une cible temporaire d\'activité après le début d\'un effort entraîne des résultats moins efficace que si elle est définie avant.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/temptarget.html#activity-temp-target
+ Rubrique : Désactivation/activation de boucle
+ Est-ce que je reçois de l\'insuline lorsque la boucle est désactivée / suspendue ?
+ Oui, l\'insuline basale continue à être délivrée.
+ Non, l\'injection d\'insuline est arrêtée.
+ Rubrique : Tests des débits de basal, SI et G/I
+ Quand dois-je valider les débits de basal, SI et G/I ?
+ Avant de commencer la boucle.
+ Lors d\'hypoglycémies fréquentes.
+ Lors d\'hyperglycémies fréquentes.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/FAQ.html#androidaps-settings
+ Rubrique : Les Prérequis
+ De quoi ai-je besoin ?
+ Informations de profil validées (Basal, G/I, SI, DAI).
+ Un ordinateur pour créer un APK.
+ Un téléphone compatible.
+ Une voiture.
+ Nightscout pour réussir les objectifs.
+ Un compte Tidepool.
+ Un compte Google.
+ Un compte Github.
+ Expérience de développement Android.
+ Une pompe MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Module/module.html
+ Une montre connectée.
+ Un MGC pris en charge et compatible.
+ Rubrique : Mettre à jour AndroidAPS
+ Qu\'est-ce qui est vrai ?
+ Vous devez avoir Git installé.
+ Mettre à jour dès qu\'une nouvelle version est publiée et avoir suffisamment de temps pour le faire.
+ Vous devez utiliser les mêmes clés de signature.
+ Ne jamais mettre à jour si le système fonctionne correctement.
+ Demandez à un ami le nouveau APK.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Rubrique : Dépannage
+ Où chercher de l\'aide ?
+ Rejoindre le groupe Facebook d\'AndroidAPS.
+ Lisez la documentation AndroidAPS.
+ Consulter la Gitter room pour AndroidAPS.
+ Consulter le support Google d\'AndroidAPS
+ Parler en à votre diabétologue.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Rubrique : Plugins d\'Insuline
+ Quelle marque d\'insuline peut être utilisée avec le plugin \"Ultra-Rapid-Oref\" ?
+ Fiasp®
+ Novorapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Configuration/Config-Builder.html#insulin
+ Rubrique : Plugins de Sensibilité
+ Quel algorithme de sensibilité a un intervalle de temps paramétrable ?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Quel plugin de sensibilité doit être utilisé pour la fonction RNP (UAM) ?
+ Rubrique : Entrées de glucides erronées
+ Que devez-vous faire si vous avez renseigné une valeur erronée de glucides ?
+ Dans Traitements, supprimez la mauvaise valeur de glucides. Entrez la nouvelle.
+ Ajouter une insuline fictive à l\'aide de la fonction Remplissage
+ Rubrique : Aliments avec Graisses et Protéines
+ Que faire si votre nourriture contient une grande quantité de matières grasses ou de protéines ?
+ Convertir les graisses et les protéines en glucides et utiliser la fonction \"glucides étendus\".
+ Convertir les graisses et protéines en glucides et ajoutez les au calcul du Bolus.
+ Utiliser les Bolus étendus pour gérer les graisses et les protéines.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/Extended-Carbs.html
+ Rubrique : Surveillance à distance
+ Comment pouvez-vous surveiller AAPS de votre enfant à distance ?
+ En utilisant un site Nightscout.
+ Dexcom Follow si vous utilisez l\'application officielle Dexcom (Glycémie uniquement).
+ Dexcom Follow si vous utilisez l\'application xDrip.
+ xDrip exécuté en mode suiveur.
+ Application Loop sur iPhone.
+ Application Spike sur iPhone.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Children/Children.html
+ Rubrique : Sensibilité à l\'Insuline (SI)
+ Les valeurs de SI plus élevées conduisent à moins d\'insuline injectée quand AAPS corrige une hyperglycémie.
+ Des valeurs plus faibles de SI entraînent une diminution de l\'administration d\'insuline lorsque l\'AAPS corrige une hyperglycémie.
+ Changer les valeurs de SI n\'a aucun effet sur la quantité d\'insuline injectée quand AAPS corrige une hyperglycémie.
+ Vous devez renseigner la SI dans les Préférences.
+ La modification de la SI dans le profil est suffisant pour appliquer le changement.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/Profiles.html
+ Rubrique : Ratio Glucides/Insuline
+ Les ratios G/I plus élevés conduisent à moins d\'insuline injectée pour une quantité donnée de glucides.
+ Les ratios G/I plus faibles conduisent à moins d\'insuline injectée pour une quantité donnée de glucides.
+ Si vous avez 0 GA, changer le ratio G/I conduira à différentes quantités d\'insuline pour corriger une valeur de glycémie donnée.
+ Le G/I sera différent si vous comptez l\'unité de pain à 10g ou à 12g.
+ Le G/I (Ratio Glucides/Insuline) est : combien d\'unités de pain sont couverte par 1U d\'insuline.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Rubrique : Changement de profil
+ Quand on renseigne 90% dans le changement de profil…
+ Le débit de base sera 10% plus élevé.
+ Le débit de base sera 10% plus faible.
+ Le G/I sera augmenté de 10%.
+ Le G/I sera diminué de 10%.
+ La valeur de SI sera augmentée de 10%.
+ La valeur SI sera diminuée de 10%.
+ Vous aurez au total environ 10% d\'insuline en moins.
+ La Cible sera 10% plus élevée.
+ La Cible sera 10% plus faible.
+ Seule la cible inférieure sera diminuée de 10%.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Si vous vous réveillez 1h plus tôt que d\'habitude, comment informez-vous AAPS du changement de votre planning ?
+ Faites un changement de profil avec un décalage horaire de 1
+ Faites un changement de profil avec un décalage horaire de -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profilewitch#timeshift
+ Faites un changement de profil avec un décalage horaire de 60
+ Faites un changement de profil avec un décalage horaire de -60
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Rubrique : Aide avec le débit Basal
+ Où aller pour avoir de l\'aide avec le débit Basal etc.
+ Votre équipe médicale
+ Google
+ Facebook
+ Autres médicaments
+ AAPS réduit le débit de basal pour augmenter le taux de sucre dans le sang. Les médicaments du groupe d\'inhibiteurs SGLT2 (gliflozins) peuvent empêcher l\'augmentation prévue de la glycémie et ainsi produire une carence dangereuse en insuline (DKA).
+\nLes noms de marque communes sont : Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nJe m\'engage à ne pas prendre ces médicaments lors de l\'utilisation d\'AAPS ou à désactiver la boucle avant de les utiliser.
+
diff --git a/app/src/main/res/values-fr-rFR/objectives.xml b/app/src/main/res/values-fr-rFR/objectives.xml
new file mode 100644
index 0000000000..b39e5ce285
--- /dev/null
+++ b/app/src/main/res/values-fr-rFR/objectives.xml
@@ -0,0 +1,68 @@
+
+
+
+ Retour
+ Départ
+ Vérifier
+ %1$d. Objectif
+ Objectif %1$d non démarré
+ Objectif %1$d non terminé
+ Paramétrage de la visualisation et la surveillance des données, analyse des débits Basal et des ratios
+ Vérifiez que la Glycémie est disponible sur Nightscout et que les données d’insuline ont été téléchargées de la pompe
+ Démarrage de la boucle ouverte
+ Utilisez votre boucle ouverte pendant plusieurs jours et lancez manuellement plusieurs débits Basal temporaires. Définissez et utilisez les cibles temporaires et celles par défaut (ex : sport ou resucrage suite à une hypo)
+ Compréhension de la Boucle Ouverte, y compris les propositions de débits Basal temporaires
+ Partant de ce constat, décidez quel doit être le débit de base maximum, et entrez le dans la pompe et les préférences
+ Démarrage de la boucle fermée avec le système AGB ( Arrêt pour Glycémie Basse )
+ Activez la boucle fermée avec le paramètre max IOB = 0 pendant plusieurs jours sans avoir un trop grand nombre d\'AGB (Arrêt pour Glycémie Basse)
+ Réglage de la Boucle Fermée, augmentation de l\'IA (Insuline Active) maximale au dessus de 0 et abaissement progressif des cibles glycémiques
+ Utilisez pendant plusieurs jours, et au moins une nuit sans alarme d’hypoglycémie, avant d\'abaisser les cibles glycémiques
+ Ajustement des débits Basal et des ratios si nécessaire, puis activation de la fonction auto-sens
+ 1 semaine de Boucle Fermée en journée en saisissant régulièrement les glucides
+ Activation de fonctionnalités supplémentaires en journée, comme l\'Aide au Repas Améliorée ARA (AMA)
+ Activation de fonctionnalités supplémentaires pour l\'utilisation en journée, telles que la fonction SMB
+ Lisez le wiki et augmentez le maxIA pour que les SMBs fonctionnent correctement ! Un bon début est maxIA = moyenne des Bolus Repas + 3 x maximum débit Basal quotidien
+ Glycémie disponible sur NS
+ Statut de la pompe disponible sur NS
+ Activation manuelle
+ Accompli : %1$s
+ Apprendre comment contrôler AndroidAPS
+ Exécutez différentes actions dans AndroidAPS
+ Sélection du profil à 90% pendant 10 min (appui long sur le nom du profil à l\'Accueil)
+ Simulation d\'une douche. Déconnectez la pompe pendant 1h (Appui long sur Boucle Ouverte)
+ ... et reconnectez la pompe de la même façon
+ Créer une cible temporaire personnalisée avec une durée de 10 min (Appui long sur votre cible actuelle)
+ Dans le Générateur de configuration, activez le plugin Actions, rendez le visible et affichez son contenu dans le menu supérieur
+ Affichage du contenu du plugin Boucle
+ Modification de l\'échelle du graphique par un appui long sur la courbe de glycémie
+ Entrer
+ Si vous étiez avant un utilisateur d\'OpenAPS et que votre NS a au moins 3 mois de données de bouclage, vous pouvez envoyer un e-mail à objectives@androidaps.org avec votre adresse NS et demander un code pour contourner le reste des objectifs. Entrez le code obtenu auprès des développeurs
+ Code accepté
+ Code invalide
+ Prouver ses connaissances
+ Étudiez et répondez correctement aux questions
+ Réponse désactivée jusqu\'à : %1$s
+ Mauvaise réponse !
+ Prochain non terminé
+ Code requis : %1$s
+ (Sélectionnez toutes les bonnes réponses)
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/fr/Getting-Started/Screenshots.html#the-homescreen
+ Non connecté à Internet
+ Échec de la récupération de l\'heure
+ Exigences de l\'objectif non atteintes
+
+ %1$d jour
+ %1$d jours
+
+
+ %1$d heure
+ %1$d heures
+
+
+ %1$d minute
+ %1$d minutes
+
+
diff --git a/app/src/main/res/values-fr-rFR/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml
index d04a6fc056..595fd9fdc4 100644
--- a/app/src/main/res/values-fr-rFR/strings.xml
+++ b/app/src/main/res/values-fr-rFR/strings.xml
@@ -5,7 +5,6 @@
-
Sécurités des traitementsMaximum Bolus autorisé [U]Maximum de Glucides autorisé [g]
@@ -46,7 +45,7 @@
Intégration pour les pompes qui n’ont pas encore de pilote (Boucle Ouverte)La Sensibilité est calculée de la même manière que Oref0, mais vous pouvez spécifier la periode concernée. L\'absorption minimale des glucides est calculée à partir des temps d’absorption max des glucides du menu préférences.Sensibilité est calculée à partir des données sur les dernières 24h et les glucides (non absorbés) ne sont plus pris en compte après l’heure spécifiée dans les préférences.
- Sensibilité est calculée à partir des données des dernières 8 heures et des glucides (si non absorbés) ne sont plus pris en compte après le temps spécifié dans les préférences. Plugin calcule également UAM.
+ Sensibilité est calculée à partir des données des dernières 8 heures et des glucides (si non absorbés) ne sont plus pris en compte après le temps spécifié dans les préférences. Plugin calcule également RNS (UAM).Sensibilité est calculée comme une moyenne pondérée des écarts. Les écarts les plus récents ont un poids plus élevé. L\'absorption minimale des glucides est calculée à partir des temps d’absorption des glucides max du menu préférences. Cet algorithme est le plus rapide pour s\'adapter aux changements de sensibilité.Recevoir les valeurs de glycémie de l’app Eversense patchée.Recevoir les glycémies depuis Glimp.
@@ -57,12 +56,9 @@
Surveillez et contrôlez AndroidAPS en utilisant votre montre WearOS.Afficher les informations de votre Boucle sur votre écran de montre xDrip+.Commander à distance AndroidAPS en utilisant les commandes SMS.
- Retour
- Démarrer
- VérifierUnitésDAI
- I:G (Ratio Insuline/Glucides)
+ G/I (g/U)SI Sensibilité InsulineBasalCible
@@ -102,6 +98,7 @@
ProfilDonnées repasRésultats
+ Résultat: %1$s %2$sPas de données glycémiques disponiblesPas de changement demandéRequête
@@ -158,9 +155,9 @@
ConfirmationEntrez le nouveau traitement :Bolus
- Bolus :
+ Bolus:Basal
- Basal :
+ Basal:GlucidesChangez vos entrées !Définir un nouveau bolus étendu
@@ -177,9 +174,6 @@
Version incompatible du NSClientVersion incompatible de NightscoutNSClient non installé. Enregistrement perdu !
- Glycémie disponible sur NS
- Statut pompe disponible sur NS
- Activation manuelleBOUCLE DÉSACTIVÉE PAR RESTRICTIONSBasal IARestriction du Bolus appliquée
@@ -190,8 +184,8 @@
QuestionActivité PhysiqueChangement Zone D\'insertion
- Insertion Capteur MCG
- Début Capteur MCG
+ Insertion Capteur MGC
+ Début Capteur MGCChangement du RéservoirChangement profilBolus Goûter
@@ -208,7 +202,7 @@
CapteurGlucidesInsuline
- Durée glucides
+ Heure glucidesDiviserDuréePour cent
@@ -222,7 +216,7 @@
Basal TemporaireBolus étenduVersion Nightscout :
- Manque
+ Manquant %1$dgPréférences exportéesExporter les paramètres auImporter les paramètres depuis
@@ -277,7 +271,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
DoigtCapteurManuel
- Cible temporaire
+ Cible temp.Annulation Cible TemporaireParamètres du profil DanaRDurée d\'Action [h]
@@ -318,11 +312,9 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
BOUTON ARRÊT ACTIVÉAttente connection pompe%1$.2fU vont être injectées
- Paramétrer la visualisation et la surveillance des données, analyser les débits de basal et les ratios
- Vérifiez que la Glycémie est disponible sur Nightscout et que les données d’insuline ont été téléchargées de la pompeVous avez atteint la limite maximaleAucun profil séléctionné
- La Boucle été désactivée
+ La Boucle a été désactivéeLa Boucle a été activéeLa Boucle est désactivéeLa Boucle est activée
@@ -330,17 +322,17 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
La valeur %1$s est en dehors des limitesLa commande à distance n\'est pas autoriséeBolus à distance non disponible. Réessayez plus tard.
- Pour démarrer Basal %1$.2fU/h pendant %2$d min, renvoyer le code %3$s
+ Pour démarrer la Basal %1$.2fU/h pendant %2$d min, renvoyer le code %3$sPour changer le profil vers %1$s %2$d%%, renvoyer le code %3$sPour démarrer le Bolus étendu %1$.2fU pendant %2$d min, renvoyer le code %3$s
- Pour démarrer le Basal %1$d%% pendant %2$d min, renvoyer le code %3$s
+ Pour démarrer la Basal %1$d%% pendant %2$d min, renvoyer le code %3$sEnvoyer le code %2$s pour suspendre la Boucle pour %1$d minutesDémarrage réussi pour %1$.2fU/h de basal temporaire pour %2$d minLe Bolus étendu %1$.2fU pendant %2$d min a commencé avec succèsDémarrage réussi pour %1$d%% de Basal temporaire pour %2$d minLe démarrage du basal temporaire a échouéLe départ du Bolus étendu a échoué
- Envoyer le code %1$s pour arrêter le Basal temporaire
+ Envoyer le code %1$s pour arrêter la Basal temporairePour arrêter le Bolus étendu, renvoyer le code %1$sBasal temporaire annuléBolus étendu annulé
@@ -401,7 +393,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Notification en coursDONNÉES ANCIENNES%1$d min passées
- %1$dmin passées
+ il y a %1$d minProfil LocalOpenAPS AMADelta basé sur une courte moyenne
@@ -434,13 +426,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
ACTCONFBOUCLE
- SP
+ P.S.OAPS
- LP
+ P.L.DANAACCUEILPOMPEV
- PROFIL NS
+ P.NSTRAITCPOBJ
@@ -538,10 +530,10 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Durée incorrecteBoucle suspendueBoucle relancée
- Tendance 15 min
+ Delta 15 minGASuperbolus
- Démarrage de l\'app journaux vers NS
+ Démarrage AAPS entré dans NSSortie de l’application pour appliquer de nouveaux paramètres.DanaRv2Insuline
@@ -552,11 +544,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
INSActiver les Superbolus dans l’AssistantActiver la fonctionnalité SuperBolus dans l’Assistant. Ne pas l’activer avant de bien comprendre comment cela fonctionne réellement. IL PEUT PROVOQUER UNE OVERDOSE D’INSULINE SI UTILISÉ AVEUGLÉMENT !
- Afficher les lumières d\'état sur l\'écran d\'accueil
+ Afficher les voyants d\'état sur l\'écran d\'accueil
+ Afficher les voyants d\'état prolongés sur l\'écran d\'accueil
+ Activer les voyants d\'état prolongés pour AgeC, AgeI, AgeS, niveaux du réservoir et de batterie sur l\'écran d\'accueil.Seuil d\'avertissement de niveau du réservoir [U]Seuil critique de niveau du réservoir [U]
- Seuil d’avertissement du niveau de batterie [%%]
- Seuil critique du niveau de la batterie [%%]
+ Seuil d’avertissement du niveau de batterie [%]
+ Seuil critique du niveau de la batterie [%]IAGAFirmware
@@ -626,10 +620,11 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
AnnulerLes profils ne sont pas tous téléchargés !Valeurs non enregistrées !
+ Active les diffusions vers d\'autres applications (comme xDrip). Ne pas activer si plusieurs instances d\'AAPS ou de NSClient sont installées !Activer les transmissions locales.ACTIVITÉ et FEEDBACKGLUCIDES et BOLUS
- MCG et OPENAPS
+ MGC et OPENAPSPOMPEValeur Basal [U/h] Durée [min]
@@ -686,6 +681,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
gmh
+ j]]>kJEn
@@ -710,13 +706,14 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
BT WatchdogCeci va arrêter le Bluetooth du téléphone pour une seconde si la connexion pompe n’est pas possible. Cela peut assister certains téléphones dont la connexion Bluetooth se bloque.App Eversense (patché)
- Remonter les données glycémiques vers NS
+ Remonter les Gly vers NSParamètres de téléchargement des glycémiesAfficher le delta détailléAfficher delta avec une décimale supplémentaire
+ SMB minutes maxMax. minutes de basal pour limiter le SMBFirmware pompe incompatible
- Transmettre les données G vers xDrip+
+ Transmettre les Gly vers xDrip+Dans xDrip+ veuillez séléctionner 640g/Eversense comme source de donnéesGlycémie NSClientValeur de basal remplacée par la valeur minimale autorisée : %1$s
@@ -777,13 +774,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
L\'administration de bolus et la vérification de l\'historique de la pompe ont échoué. Vérifiez la pompe manuellement. Si un bolus a été administré, il sera ajouté aux traitements au cours de la prochaine connexion avec la pompe.Pas assez d\'insuline dans le réservoir pour le bolusErreur administration bolus étendu
- Vue
+ AC-Ipassé(e)s%1$.2f hActiver en permanence les SMBActiver toujours SMB de manière autonome pour les bolus. Ceci est possible uniquement avec une source de glycémie ayant un très bon filtrage de données comme le G5Activer SMB après ingestion de glucides
- Activer SMB pendant 6h après ingestion de glucides, même s’il y a 0 GI (Glucides Actifs). Ceci est possible uniquement avec une source de glycémie ayant un très bon filtrage de données comme le G5
+ Activer SMB pendant 6h après ingestion de glucides, même s’il y a 0 GA (Glucides Actifs). Ceci est possible uniquement avec une source de glycémie ayant un très bon filtrage de données comme le G5Activer SMB avec les glucidesActiver SMB tant que des Glucides sont actifs.Activer SMB avec les cibles temporaires
@@ -799,8 +796,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Ouvre xDrip+, le bouton de retour renverra vers AAPSNombre de glucides à ajouter lorsque vous appuyez sur le boutonQuantité d’insuline à ajouter lorsque vous appuyez sur le bouton
- Impossible d’exécuter l’application de MCG. Assurez-vous de que celle-ci est installée.
- MCG
+ Impossible d’exécuter l’application de MGC. Assurez-vous de que celle-ci est installée.
+ MGCHistoriqueNotifier en SMBAfficher SMB sur la montre comme un bolus standard.
@@ -849,15 +846,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
ProfileSwitch manquant. S’il vous plaît faire un changement de profil ou appuyez sur « Activer le profil » dans le LocalProfile.Nombre de bolusNombre de TBR
- Objectif %1$d non démarré
- Objectif %1$d non terminéPompe n’est pas capable de basals temporairesAucun taux basal valide provenant de la pompeMode de Boucle Fermée désactivé dans les préférencesAutosens désactivé dans les préférencesSMB désactivée dans les préférences
- Repas Non Prévu (UAM) désactivé dans les préférences
- Repas Non Prévu (UAM) désactivé car il utilise le plugin Sensibilité de Oref1
+ Repas Non Signalé (UAM) désactivé dans les préférences
+ Repas Non Signalé (UAM) désactivé car il utilise le plugin Sensibilité de Oref1Limiter le taux basal max à %1$.2f U/h en raison de %2$sLimite de la pompela valeur doit être positive
@@ -876,7 +871,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
utilisation dangereuseLa lecture du statut a échouéEnregistrer changement de site de cathéter
- Enregistrer changement de réservoir
+ Enreg. changement de réservoirSMB toujours et post-ingestion de glucides désactivé car la source de glycémies actuelle ne supporte pas de filtrage avancéSMB non autorisé en mode Boucle OuverteAliments
@@ -904,7 +899,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Premier incrément de glucidesDeuxième incrément de glucidesTroisième incrément de glucides
- MCG
+ MGCUtilisez uniquement connexion Wi-fiWi-fi SSIDWi-fi uniquement pendant la charge
@@ -972,7 +967,6 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Terminé, félicitations !Pas encore terminéTemps écoulé
- %1$d. ObjectifPoctechRecevoir les glycémies depuis l\'app PoctechRecevoir les valeurs de glycémie de l\'application Tomato (appareil MiaoMiao)
@@ -1068,7 +1062,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Bolus mixte%1$.2f / %2$.2f U pour %3$d minActiver la notification de la fin DBT\n(réglage de pompe)
- Activer la notification de la fin de DBT\n(réglage de pompe)
+ Désactiver la notification de la fin de DBT\n(réglage de pompe)ActualiserIntégration des pompes Accu-Chek InsightNon inséré
@@ -1156,8 +1150,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Transférer les Basal temporairesTransférer les changements de profils, les objectifs temporairesTransférer les tests de glycémies
- Changement d\'heure d\'été dans moins de 24 heures
- Changement d\'heure d\'été dans moins de 3 heures - Boucle fermée désactivée
+ Changement d\'heure dans moins de 24 heures
+ Changement d\'heure dans moins de 3 heures - Boucle fermée désactivéestockage interne limitéBoucle désactivée ! Libérez au moins %1$d Mo du stockage interne !Format incorrect
@@ -1245,6 +1239,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Non sélectionné (vue simple)Alcaline (vue étendue)Lithium (vue étendue)
+ NiZn (vue étendue)
+ Débogage de Bolus/TraitementsSCANNERARRÊT
@@ -1283,6 +1279,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Non démarréInitialisation du RileyLink…Erreur RileyLink
+ Association du RileyLink et de la PompeProblème communication avec la pompeConnecté
@@ -1352,6 +1349,15 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
Obtenir le Basal TemporaireDéfinir le Basal TemporaireDéfinir le Bolus
+ Remplacer le profil par
+ Remplacer le profil par %1$s
+ Dernière connexion à la pompe
+ Dernière connexion de pompe [minutes]
+ Dernière connexion à la pompe %1$s il y a %2$s min
+ Envoyer SMS : %1$s
+ Envoyer SMS à tous les numéros dans les préférences
+ Envoyer SMS avec du texte
+ %2$+.2fU]]>Contraintes de Bolus appliquées : %2$.2fU à %3$.2f]]>!!!!! Absorption lente des glucides détectée : %2$d%% du temps. Vérifiez de nouveau votre calcul. Les GA (Glucides Actifs) peuvent être surestimés et alors plus d\'insuline pourrait être délivré !!!!!]]>%1$.0f / %2$d U
@@ -1359,16 +1365,19 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S
L\'assistant Bolus effectue le calcul mais seulement cette partie de l\'insuline calculée est délivrée. Utile avec l\'algorithme SMB.Chargement ...Report alarme
-
- %1$d jour
- %1$d jours
-
-
- %1$d heure
- %1$d heures
-
-
- %1$d minute
- %1$d minutes
-
+ Plage horaire
+ L\'heure est comprise entre %1$s et %2$s
+ Entre
+ Fermer
+ Augmentation de la valeur du débit Basal max parce que ce paramètre est inférieur au débit Basal max de votre profil
+ Message invalide
+ %1$s SI: %2$.1f
+ %1$.0fg G/I: %2$.1f
+ %1$.1fg G/I: %2$.1f
+ %1$d%%
+ Assistant Bolus
+ min
+ %1$dg
+ On
+ Off
diff --git a/app/src/main/res/values-ga-rIE/objectives.xml b/app/src/main/res/values-ga-rIE/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-ga-rIE/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-ga-rIE/strings.xml b/app/src/main/res/values-ga-rIE/strings.xml
index 7879323748..df88c88e20 100644
--- a/app/src/main/res/values-ga-rIE/strings.xml
+++ b/app/src/main/res/values-ga-rIE/strings.xml
@@ -5,7 +5,6 @@
-
diff --git a/app/src/main/res/values-hr-rHR/objectives.xml b/app/src/main/res/values-hr-rHR/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-hr-rHR/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-hr-rHR/strings.xml b/app/src/main/res/values-hr-rHR/strings.xml
index 7879323748..df88c88e20 100644
--- a/app/src/main/res/values-hr-rHR/strings.xml
+++ b/app/src/main/res/values-hr-rHR/strings.xml
@@ -5,7 +5,6 @@
-
diff --git a/app/src/main/res/values-it-rIT/exam.xml b/app/src/main/res/values-it-rIT/exam.xml
index e7705078e0..4b9047c775 100644
--- a/app/src/main/res/values-it-rIT/exam.xml
+++ b/app/src/main/res/values-it-rIT/exam.xml
@@ -3,65 +3,66 @@
Cosa è vero riguardo DIA?Argomento: Durata dell\'Azione dell\'Insulina
- Il minimo predefinito è 3 ore.
- Il minimo predefinito è 5 ore.
+ Il valore minimo è 3 ore.
+ Il valore minimo è 5 ore.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
- È uguale al parametro DIA utilizzato nel tuo micro.
+ Il significato è uguale al parametro DIA utilizzato nel tuo micro.Devi determinare il tuo valore individuale (ma non meno di 5 ore).Argomento: Temp-Target \"Ipoglicemia\"
- Perché è utile impostare un TT Ipoglicemia?
- Evitare che la glicemia vada in basso.
- Per aiutare il recupero da una glicemia bassa.
- Per evitare che SMB reagisca all\'aumento della glicemia dovuto ai carboidrati a rapido assorbimento durante una ipo.
+ Qual è la ragione principale per impostare un TT Ipoglicemia?
+ Per impedire che la glicemia vada in basso se c\'è già in esecuzione una basale temporanea impostata a zero.
+ Per evitare che AAPS somministri troppa insulina dopo un aumento di glicemia causato da carboidrati a veloce assorbimento usati per trattare una glicemia bassa.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.htmlQuale profilo può essere usato e configurato offline?
- Argomento: Profilo Offline
+ Argomento: Profilo offlineIl profilo NS può essere utilizzato, ma non configurato.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profileArgomento: Disconnessione dal micro
- Cosa fare quando si toglie il micro?
- Far sapere al Loop che non viene erogata insulina al tuo corpo facendo click su \"disconnettere micro\".
- Non cambiare nulla nel Loop, staccare solo il micro.
+ Cosa dovrebbe essere fatto quando si disconnette il micro?
+ Click su \'Disconnetti micro\' cosicché AAPS sappia che non viene erogata alcuna insulina.
+ Click su \'Sospendi loop\' cosicché AAPS stoppi l\'attività di loop mentre il micro è disconnesso.
+ Non cambiare alcunché in AAPS, solo disconnettere il micro.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settingsArgomento: Impostazioni di AndroidAPSQuali sono le migliori pratiche per il backup delle impostazioni?Esportarle localmente dal menu Manutenzione.Salvare il file esportato in un altro posto come l\'email, Dropbox, Google drive…Esportarle subito dopo l\'installazione di AAPS.
- Esportarle dopo ogni modifica di un\'impostazione.
+ Esportarle dopo aver fatto modifiche d\'impostazione.
+ Esportarle dopo il completamento di un obiettivo.Esportarle quando termini le configurazioni iniziali.https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.htmlhttps://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-meArgomento: Letture CGM \"rumorose\" (noisy)
- Cosa fare quando vedi che i valori CGM sono troppo \"rumorosi\" (instabili)?
- Nulla, il Loop se ne occuperà.
- Sospendere la modalità \"Loop Chiuso\" per evitare il sovradosaggio.
+ Cosa dovrebbe essere fatto se i dati CGM sono \"rumorosi\"?
+ Nulla, AAPS se ne occuperà.
+ Disabilitare il loop per evitare il sovradosaggio.Sostituire il sensore CGM.Spegnere il telefono.https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
- Controllare se la tua app CGM fa lo \"smoothing\" dei dati (ne filtra il \"rumore\").
- Argomento: Esercizio Fisico
+ Verificare che la tua app CGM faccia lo smoothing dei dati della glicemia.
+ Argomento: Esercizio fisicoCome puoi aiutare il sistema a gestire l\'esercizio fisico?
- Impostare un Temp-Target \"Attività\".
+ Utilizzo della funzione temp-target.Fare un cambio profilo sotto il 100%.Fare un cambio profilo sopra il 100%.
- Stoppare il Loop.
- Impostare il Temp-Target \"Attività\" prima dell\'inizio dell\'esercizio.
- Impostare il Temp-Target \"Attività\" dopo l\'inizio dell\'esercizio.
+ Stoppare il loop.
+ Impostare un temp-target \"attività\" prima dell\'inizio dell\'esercizio fisico.
+ L\'impostazione di un temp-target \"attività\" dopo l\'inizio dell\'esercizio fisico porta a risultati peggiori rispetto all\'avviarlo prima dell\'inizio dell\'esercizio.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
- Argomento: Loop sospeso
- Ricevo insulina quando il Loop è sospeso?
- Sì, la velocità basale ordinaria.
+ Argomento: Loop Disabilitato/Sospeso
+ Ricevo insulina quando il loop è disabilitato/sospeso?
+ Sì, l\'insulina basale continua a essere erogata.No, l\'erogazione di insulina è interrotta.Argomento: Basale, ISF e Test ICQuando dovrei verificare i valori di basali, ISF e IC?
- Prima di iniziare il Loop.
- Quando si hanno Ipoglicemie regolarmente.
- Quando si hanno Iperglicemie regolarmente.
+ Prima che io inizi l\'attività di loop.
+ Quando si verificano frequentemente glicemie basse.
+ Quando si verificano frequentemente glicemie alte.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settingsArgomento: PrerequisitiDi cosa ho bisogno?
- Profilo determinato correttamente (Basali, IC, ISF, DIA).
+ Informazioni profilo convalidate (Basale, IC, ISF, DIA).Un computer per creare un APK.Un telefono supportato.Un\'auto.
@@ -69,75 +70,75 @@
Un account Tidepool.Un account Google.Un account Github.
- È necessario essere uno sviluppatore Android.
+ Esperienza di sviluppo Android.Un micro MiniMed 670G.https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
- Uno Smartwatch.
+ Uno smartwatch.Un CGM Supportato.Argomento: Aggiornamento di AndroidAPSCosa è vero?Hai bisogno di avere Git installato.
- Aggiornare non appena la nuova versione viene rilasciata.
- Puoi usare le stesse chiavi di firma.
+ Aggiornare appena la nuova versione viene rilasciata e avere abbastanza tempo per farlo.
+ Dovresti usare le stesse chiavi di firma.Non aggiornare mai se il sistema funziona bene.Chiedere al tuo amico il nuovo APK.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branchArgomento: Risoluzione dei problemiDove cercare aiuto?Entrare nel gruppo Facebook di AndroidAPS.
- Visitare il Wiki di AndroidAPS.
+ Leggere la documentazione di AndroidAPS.Visitare la Gitter Room di AndroidAPS.Visitare il supporto Google di AndroidAPSParlare con il tuo endocrinologo.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshootinghttps://www.facebook.com/groups/aapsitalia/https://gitter.im/MilosKozak/AndroidAPS
- Argomento: Insulina
- Quale marca di insulina può essere usata con il plugin Ultra-Rapid-Oref?
+ Argomento: Plugin Insulina
+ Quale marca di insulina può essere usata con il plugin \'Ultra-Rapid-Oref\'?Fiasp®NovoRapid®Humalog®Actrapid®https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulinArgomento: Plugin di Sensibilità
- Quale plugin di sensibilità ha un intervallo di tempo definito dall\'utente per il rilevamento?
+ Quale algoritmo di sensibilità ha un intervallo di tempo configurabile?https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.htmlQuale plugin di sensibilità deve essere utilizzato per la funzione UAM?
- Argomento: Inserimenti non corretti dei Carboidrati
- Ti accorgi che hai inserito erroneamente i carboidrati. Cosa dovresti fare?
- Andare nella sezione Trattamenti, eliminare i carboidrati \"errati\" e fare un nuovo inserimento.
- Aggiungere insulina fittizia usando la funzione Riempimento
+ Argomento: Errori di immissione carboidrati
+ Cosa dovresti fare se hai fatto un inserimento non corretto di carboidrati?
+ Nella sezione Trattamenti, eliminare la voce carboidrati non corretta. Inserire nuovi carboidrati.
+ Aggiungere insulina fittizia usando la funzione di riempimentoArgomento: Cibo con Grassi e ProteineCosa fare se il tuo cibo contiene una grande quantità di grassi e/o proteine?Convertire grassi e proteine in carboidrati e utilizzare la funzione \"carboidrati estesi\" (eCarbs).Convertire grassi e proteine in carboidrati e aggiungerli al calcolo del bolo.Utilizzare il bolo esteso per coprire grassi e proteine.https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
- Argomento: Monitoraggio dei bambini
+ Argomento: Monitoraggio remotoCome puoi monitorare AAPS del tuo bambino in remoto?Usando un sito Nightscout.
- L\'app Dexcom Follow se stai usando l\'app originale Dexcom.
+ L\'app Dexcom Follow se stai usando l\'app originale Dexcom (solo glicemia).Dexcom Follow se stai usando l\'app xDrip.xDrip in modalità follower.App Loop su iPhone.App Spike su iPhone.https://androidaps.readthedocs.io/en/latest/EN/Children/Children.htmlArgomento: Fattore di Sensibilità all\'Insulina
- L\'aumento del valore ISF porterà a una minore erogazione di insulina se stai cercando di abbassare la tua glicemia con il \"bolus wizard\".
- La riduzione del valore ISF porterà a una minore erogazione di insulina se stai cercando di abbassare la tua glicemia con il \"bolus wizard\".
- La modifica di ISF non ha alcun effetto sulla quantità di insulina somministrata da APPS quando si cerca di correggere l\'iperglicemia.
+ Valori ISF più alti portano a una minore erogazione di insulina quando AAPS corregge glicemie alte.
+ Valori ISF più bassi portano a una minore erogazione di insulina quando AAPS corregge glicemie alte.
+ Cambiare i valori di ISF non ha alcun effetto sulla quantità di insulina erogata quando AAPS corregge glicemie alte.Devi inserire ISF nelle Preferenze.Cambiare il valore ISF nel tuo profilo è sufficiente per applicare la modifica.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-uhttps://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
- Argomento: Il Valore IC
- L\'aumento del valore IC porterà a una minore erogazione di insulina per la stessa quantità di carboidrati.
- La riduzione del valore IC porterà a una minore erogazione di insulina per la stessa quantità di carboidrati.
- Supporre di avere 0 COB. La modifica dell\'IC porterà a una diversa quantità di insulina necessaria per correggere il valore della glicemia.
+ Argomento: Il Rapporto IC
+ Rapporti IC più alti portano a una minore insulina erogata per una data quantità di carboidrati.
+ Rapporti IC più bassi portano a una minore insulina erogata per una data quantità di carboidrati.
+ Se hai 0 COB, cambiare il rapporto IC porterà a una differente quantità di insulina necessaria a correggere una determinata glicemia.IC sarà diverso se consideri l\'unità di pane (BE) come 10g o 12g.Il significato di IC è: Quante unità di pane (BE) sono coperte da 1U di insulina.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
- Argomento: Cambio Profilo
+ Argomento: Cambio profilo Quando si specifica il 90% nel cambio profilo…Le basali saranno il 10% più alte.Le basali saranno il 10% più basse.
@@ -145,15 +146,24 @@
Il valore IC sarà il 10% più basso.Il valore ISF sarà il 10% più alto.Il valore ISF sarà il 10% più basso.
- Riceverai il 10% in meno di insulina, in totale.
- Il Target sarà il 10% più alto.
- Il Target sarà il 10% più basso.
+ Riceverai circa il 10% in meno di insulina, in totale.
+ Il target sarà il 10% più alto.
+ Il target sarà il 10% più basso.Solo il target inferiore sarà il 10% più basso.https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
- Voglio fare un cambio profilo perché mi sono dovuto svegliare 1h prima del solito, quindi è più sensato annunciare lo spostamento d\'orario mediante un cambio profilo. Che valore dovrei usare?
- 1
- -1
+ Se ti svegli 1h prima del solito, come dovresti informare AAPS del cambiamento nei tuoi programmi?
+ Avviare un cambio profilo con un timeshift di 1
+ Avviare un cambio profilo con un timeshift di -1https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
- 60
- -60
+ Avviare un cambio profilo con un timeshift di 60
+ Avviare un cambio profilo con un timeshift di -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Argomento: Aiuto le con velocità basali
+ Dove andare per avere aiuto con le velocità basali e il resto.
+ Il tuo team diabetologico
+ Google
+ Facebook
+ Altri Medicinali
+ AAPS riduce la velocità basale per aumentare la glicemia. Farmaci appartenenti al gruppo degli inibitori dell\'SGLT2 (gliflozine) possono ostacolare l\'aumento previsto della glicemia e, quindi, provocare una pericolosa carenza di insulina (DKA).
+\nI marchi più comuni sono: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nCon ciò prometto che non prenderò tali farmaci durante l\'utilizzo di AAPS o disattiverò il loop prima di usare questi farmaci.
diff --git a/app/src/main/res/values-it-rIT/insight_alert_titles.xml b/app/src/main/res/values-it-rIT/insight_alert_titles.xml
index 97ed97fa7f..d510f14df2 100644
--- a/app/src/main/res/values-it-rIT/insight_alert_titles.xml
+++ b/app/src/main/res/values-it-rIT/insight_alert_titles.xml
@@ -1,7 +1,7 @@
- Eroga Bolo
+ Eroga boloBolo persoSvegliaCambia set infusione
diff --git a/app/src/main/res/values-it-rIT/objectives.xml b/app/src/main/res/values-it-rIT/objectives.xml
new file mode 100644
index 0000000000..6097ec7ddd
--- /dev/null
+++ b/app/src/main/res/values-it-rIT/objectives.xml
@@ -0,0 +1,68 @@
+
+
+
+ Indietro
+ Avvia
+ Verifica
+ %1$d. Obiettivo
+ Obiettivo %1$d non avviato
+ Obiettivo %1$d non terminato
+ Impostazione della visualizzazione e del monitoraggio. Analisi di basali e rapporti
+ Verifica che la glicemia sia disponibile su Nightscout e che i dati sull\'insulina del micro siano in fase di caricamento
+ Avvio in un loop aperto
+ Esegui l\'applicazione in modalità loop aperto per alcuni giorni. Attiva manualmente il maggior numero possibile di basali temporanee suggerite. Imposta e utilizza i target temporanei, anche quelli predefiniti (ad esempio per l\'attività fisica o il trattamento dell\'ipoglicemia con carboidrati)
+ Comprensione del tuo loop aperto, incluse le relative raccomandazioni sulle basali temporanee
+ Sulla base di tale esperienza, decidi quale dovrebbe essere il valore di \'max basale\' e impostalo sul microinfusore e nelle preferenze
+ Avvio della chiusura del loop con Low Glucose Suspend
+ Esegui l\'applicazione in loop chiuso con max IOB = 0 per pochi giorni senza troppi eventi LGS
+ Regolazione del loop chiuso, aumentando max IOB al di sopra di 0 e abbassando gradualmente i target glicemici
+ Esegui l\'applicazione per alcuni giorni e almeno una notte senza allarmi di glicemia bassa, prima di abbassare il target glicemico
+ Adatta basali e rapporti se necessario, quindi attiva auto-sens
+ 1 settimana di looping diurno con dichiarazione regolare dei carboidrati, eseguito con successo
+ Abilitazione funzioni aggiuntive per l\'uso diurno, ad esempio AMA (advanced meal assist - assistenza avanzata del pasto)
+ Abilitazione funzioni aggiuntive per l\'uso diurno, come SMB
+ È necessario leggere il wiki e aumentare maxIOB affinché le azioni di SMB funzionino adeguatamente! Un buon inizio è maxIOB = media bolo posto + 3 x max basale giornaliera
+ Glicemia disponibile in NS
+ Stato micro disponibile in NS
+ Attivazioni manuali
+ Compiuto: %1$s
+ Impara a controllare AndroidAPS
+ Esegui varie azioni in AndroidAPS
+ Imposta il profilo \"90%\" per 10 min (premi a lungo sul nome profilo nella sezione Panoramica)
+ Simula la doccia. Disconnetti il micro per 1h (premi a lungo su Loop aperto)
+ ... e riconnetti allo stesso modo
+ Crea un target temporaneo personalizzato con una durata di 10 min (premi a lungo sul tuo target corrente)
+ Nel Configuratore strutturale attiva il plugin Azioni, rendilo visibile e visualizzane i contenuti tramite il menu in alto
+ Visualizza il contenuto del plugin Loop
+ Usa la funzione di ridimensionamento premendo a lungo sul grafico delle glicemie
+ Entra
+ Se prima eri un utente OpenAPS e il tuo NS ha almeno 3 mesi di dati in loop, puoi inviare un\'e-mail a objectives@androidaps.org con il tuo indirizzo NS e richiedere il codice per ignorare il resto degli obiettivi. Inserisci il codice ottenuto dagli sviluppatori
+ Codice accettato
+ Codice non valido
+ Dai prova della tua conoscenza
+ Studia e rispondi correttamente alle domande
+ Risposta disabilitata per: %1$s
+ Risposta sbagliata!
+ Prossimo N.C.
+ Codice richiesta: %1$s
+ (segna tutte le risposte corrette)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Non connesso a internet
+ Impossibile recuperare l\'orario
+ Requisiti obiettivo non soddisfatti
+
+ %1$d giorno
+ %1$d giorni
+
+
+ %1$d ora
+ %1$d ore
+
+
+ %1$d minuto
+ %1$d minuti
+
+
diff --git a/app/src/main/res/values-it-rIT/strings.xml b/app/src/main/res/values-it-rIT/strings.xml
index fb842a6f32..08b124cd5f 100644
--- a/app/src/main/res/values-it-rIT/strings.xml
+++ b/app/src/main/res/values-it-rIT/strings.xml
@@ -5,104 +5,101 @@
-
Sicurezza trattamenti
- Max Bolo consentito [U]
- Max Carboidrati consentiti [g]
+ Max bolo consentito [U]
+ Max CHO consentiti [g]Preferenze
- Ricaricare trattamenti da NS
- Reset database
+ Ricarica trattamenti da NS
+ Resetta databaseVuoi davvero resettare i database?
- Uscita
- Usare boli estesi per >200%%
+ Esci
+ Usa boli estesi per >200%%Dispositivo DanaR Bluetooth
- Utilizzare sempre valori basali assoluti
+ Utilizza sempre valori basali assolutiPer favore riavvia il tuo telefono oppure fai ripartire AndroidAPS dalle impostazioni di sistema \naltrimenti Android APS non farà il log (è importante monitorare e verificare che gli algoritmi stiano funzionando correttamente)!Questo dispositivo non sembra supportare la whitelist dell\'ottimizzazione della batteria: potrebbero verificarsi problemi di prestazioni.
- Alcuni pulsanti per accedere rapidamente alle funzioni comuni
- Inserire voci di registro avanzate.
+ Alcuni tasti per accedere rapidamente alle funzioni comuni
+ Inserisci voci di registro avanzate.Utilizzato per configurare i plugin attiviProgramma di apprendimentoVisualizza l\'elenco dei cibi definiti in NightscoutPreset per insulina Humalog e NovoRapidPreset per insulina FiaspTi consente di definire il picco dell\'insulina e deve essere utilizzato solo dagli utenti avanzati
- Attivare o disattivare l\'implementazione del loop.
+ Attiva o disattiva l\'implementazione del loop.Sincronizza i tuoi dati con NightscoutStato dell\'algoritmo nel 2016Stato dell\'algoritmo nel 2017Algoritmo più recente per gli utenti avanzati
- Visualizza lo stato corrente del tuo loop e i pulsanti per le azioni più comuni
+ Visualizza lo stato corrente del tuo loop e i tasti per le azioni più comuniMostra una notifica con una breve panoramica di ciò che sta facendo il tuo loop
- Definire un profilo disponibile offline.
+ Definisci un profilo disponibile offline.Fornisce il profilo definito in Nightscout
- Impostare un profilo con un solo intervallo temporale.
- Integrazione del microinfusore Accu-Chek Combo, è necessario avere Ruffy installato
+ Imposta un profilo con un solo intervallo temporale.
+ Integrazione del microinfusore Accu-Chek Combo, è necessario avere ruffy installatoIntegrazione del microinfusore DANA Diabecare RIntegrazione del microinfusore DANA Diabecare R KoreanIntegrazione del microinfusore DANA Diabecare R con firmware aggiornatoIntegrazione del microinfusore DANA Diabecare RSPer le persone in terapia multi-iniettivaPer microinfusori che non hanno ancora alcun driver (Loop Aperto)
- La sensibilità è calcolata allo stesso modo di Oref0, ma è possibile specificare l\'intervallo di tempo al passato. L\'assorbimento minimo dei carboidrati è calcolato da \'max tempo assorbimento carb\' nelle preferenze.
+ La sensibilità è calcolata allo stesso modo di Oref0, ma puoi specificare l\'intervallo di tempo al passato. L\'assorbimento minimo dei carboidrati è calcolato da \'max tempo assorbimento pasto\' nelle preferenze.La sensibilità è calcolata dai dati delle ultime 24h e i carboidrati (se non assorbiti) vengono tagliati fuori dopo il tempo specificato nelle preferenze.La sensibilità è calcolata dai dati delle ultime 8h e i carboidrati (se non assorbiti) vengono tagliati fuori dopo il tempo specificato nelle preferenze. Il Plugin calcola anche UAM.
- La sensibilità è calcolata come media ponderata dalle deviazioni. Le deviazioni più recenti hanno peso maggiore. L\'assorbimento minimo dei carboidrati è calcolato da \'max tempo assorbimento carb\' nelle preferenze. Questo algoritmo è il più veloce nel seguire i cambiamenti di sensibilità.
- Ricevere valori Glicemia dall\'app Eversense modificata.
- Ricevere valori Glicemia da Glimp.
- Ricevere valori Glicemia da 600SeriesAndroidUploader.
- Scarica dati Glicemia da Nightscout
- Ricevere dati Glicemia da xDrip.
- Salva tutti i trattamenti
- Monitorare e controllare AndroidAPS usando il tuo smartwatch WearOS.
- Visualizzare le informazioni del loop sulla watchface di xDrip+.
- Controllare AndroidAPS in remoto utilizzando i comandi SMS.
- Indietro
- Avviare
- Verificare
+ La sensibilità è calcolata come media ponderata dalle deviazioni. Le deviazioni più recenti hanno peso maggiore. L\'assorbimento minimo dei carboidrati è calcolato da \'max tempo assorbimento pasto\' nelle preferenze. Questo algoritmo è il più veloce nel seguire i cambiamenti di sensibilità.
+ Ricevi valori glicemia dall\'app Eversense modificata.
+ Ricevi valori glicemia da Glimp.
+ Ricevi valori glicemia da 600SeriesAndroidUploader.
+ Scarica dati glicemia da Nightscout
+ Ricevi dati glicemia da xDrip.
+ Salva tutti i trattamenti che sono stati fatti
+ Monitora e controlla AndroidAPS usando il tuo smartwatch WearOS.
+ Mostra le informazioni del loop sulla watchface di xDrip+.
+ Controlla AndroidAPS in remoto utilizzando i comandi SMS.Unità
- DIA - Durata Azione dell\'Insulina
- IC - Rapporto Insulina/Carboidrati
- ISF - Fattore Sensibilità all\'Insulina
+ DIA
+ IC
+ ISFBasaleTargetNESSUN PROFILO IMPOSTATOInsulina:
- Carboidrati:
+ CHO:IOB:IOB:
- IOB Totale:
- Attività IOB Totale:
+ IOB totale:
+ Attività IOB totale:Dur:Rapporto:Ins:IOB:
- IOB Totale:
+ IOB totale:Insulina
- Carboidrati
- Glicemia
+ CHO
+ BGTT
- Carboidrati
+ CHOCorrezioneUIOB da bolo
- Avviare ora
- MICROINFUSORE VIRTUALE
- Vel. basale originale
- Basale Temporanea
- Bolo Esteso
+ Esegui ora
+ MICRO VIRTUALE
+ Velocità basale originale
+ Basale temporanea
+ Bolo estesoBatteriaSerbatoioOKUltima esecuzioneParametri di inputStato glicemia
- Temp. Corrente
+ Temp. correnteDati IOBProfilo
- Dati Pasto
+ Dati pastoEsito
- Dati Glicemia non disponibili
+ Risultato: %1$s %2$s
+ Dati glicemia non disponibiliNessun cambiamento richiestoRichiestaTasso
@@ -111,17 +108,17 @@
GlicemiaDeltaDelta:
- Configuratore
+ Configuratore strutturaleObiettiviOpenAPS MAPanoramicaProfilo NSProfilo semplice
- Basale Temporanea
+ Basale temporaneaTrattamentiMicro VirtualePortale
- Microinfusore
+ MicroQuale microinfusore desideri utilizzare con AndroidAPS?TrattamentiQuale plugin dovrebbe essere utilizzato per la gestione del trattamento?
@@ -136,10 +133,10 @@
VincoliLoopLoop
- Consente di attivare l\'integrazione del loop di AndroidAPS.
+ Usalo per attivare l\'integrazione del loop di AndroidAPS.APSDopo aver elaborato i vincoli
- Basale Temporanea impostata dal micro
+ Basale temporanea impostata dal microUltima attivazioneOKAnnulla
@@ -148,43 +145,40 @@
Il Plugin è disabilitatoViolazione dei vincoliErrore erogazione bolo
- Errore erogazione Basale Temporanea
+ Errore erogazione basale temporaneaValore Basale [%%]%% (100%% = corrente)
- Accetta nuova Basale Temporanea:
+ Accetta nuova basale temporanea:TrattamentoCalcolatoreVincolo applicato!Conferma
- Inserire nuovo trattamento:
+ Inserisci nuovo trattamento:BoloBolo:BasaleBasale
- Carboidrati
- Cambiare il tuo input!
- Impostare nuovo bolo esteso:
- Origine Glicemia
+ CHO
+ Cambia il tuo input!
+ Imposta nuovo bolo esteso:
+ Origine glicemiaDa dove AndroidAPS dovrebbe ottenere i suoi dati?xDripModalità APS
- Loop Chiuso
- Loop Aperto
- Loop Disabilitato
- Disabilitare Loop
- Abilitare Loop
+ Loop chiuso
+ Loop aperto
+ Loop disabilitato
+ Disabilita Loop
+ Abilita LoopNuovo suggerimento disponibileVersione non supportata di NSClientVersione non supportata di NightscoutNSClient non installato. Record perduto!
- Glicemia disponibile in NS
- Stato Micro disponibile in NS
- Attivazioni manualiLOOP DISABILITATO DAI VINCOLI
- IOB da Basale
+ IOB da basaleVincolo bolo applicato
- Vincolo carboidrati applicato
- Controllo Glicemia
+ Vincolo CHO applicato
+ Controllo glicemiaAnnuncioNotaDomanda
@@ -194,47 +188,47 @@
Avvio SensoreCambio serbatoio insulinaCambio profilo
- Bolo Spuntino
+ Bolo spuntinoBolo pasto
- Bolo di Correzione
- Bolo Combo
- Inizio Basale Temporanea
- Fine Basale Temporanea
- Correzione con carboidrati
+ Bolo di correzione
+ Bolo combo
+ Inizio basale temporanea
+ Fine basale temporanea
+ Correzione con CHOOpenAPS OfflineTipo di eventoAltroGlucometroSensore
- Carboidrati
+ CHOInsulina
- Tempo assorb. Carboidrati
- Fraziona
+ Tempo CHO
+ FrazioneDurataPercentualeAssolutoNote
- Data Evento
+ Data eventoProfiloInserito da
- Tipo Glicemia
+ Tipo glicemiaNessun profilo ancora caricato da NS
- Basale Temporanea
- Bolo Esteso
+ Basale temporanea
+ Bolo estesoVersione Nightscout:
- Mancante
+ Mancanti %1$dgPreferenze esportateEsporta impostazioni suImporta impostazioni daImpostazioni importateFile non trovato
- Esportare impostazioni
- Importare impostazioni
- Max U/h che una Basale Temporanea può impostare
+ Esporta impostazioni
+ Importa impostazioni
+ Max U/h a cui limitare una basale temporaneaQuesto valore è chiamato max basale nel contesto OpenAPS
- Max IOB da Basale che OpenAPS può erogare [U]
- Questo valore è chiamato Max IOB nel contesto OpenAPS\nIndica l\'insulina massima in [U] che APS può erogare contemporaneamente.
- RESPINGI
+ Max IOB da basale a cui limitare OpenAPS [U]
+ Questo valore è chiamato Max IOB nel contesto OpenAPS\nIndica l\'insulina massima in [U] che APS può erogare in contemporanea.
+ RIMUOVIDanaRConnessioneConnesso
@@ -243,52 +237,64 @@
Contratto di licenza per l\'utenteNON DEVE ESSERE UTILIZZATO PER PRENDERE DECISIONI MEDICHE. NON ESISTE ALCUNA GARANZIA PER IL PROGRAMMA, NELLA MISURA CONSENTITA DALLA LEGGE APPLICABILE. TRANNE QUANDO DIVERSAMENTE INDICATO PER ISCRITTO, I DETENTORI DEL COPYRIGHT E/O ALTRE PARTI FORNISCONO IL PROGRAMMA \"COSÌ COM\'È\" SENZA GARANZIA DI ALCUN TIPO, ESPLICITA O IMPLICITA, INCLUSE, MA NON LIMITATAMENTE A, GARANZIE IMPLICITE DI COMMERCIABILITÀ E IDONEITÀ PER UN SCOPO PARTICOLARE. L\'INTERO RISCHIO RIGUARDO LA QUALITÀ E LE PRESTAZIONI DEL PROGRAMMA È TUO. SE IL PROGRAMMA DOVESSE RISULTARE DIFETTOSO, TI ASSUMI IL COSTO DI TUTTE LE NECESSARIE MANUTENZIONI, RIPARAZIONI O CORREZIONI.COMPRENDO E ACCETTO
- Salvare
+ SalvaNessun adattatore bluetooth trovatoDispositivo selezionato non trovato
- Errore connessione Microinfusore
- IOB Microinfusore
+ Errore connessione microinfusore
+ IOB microinfusoreUnità giornaliere
- Ultimo Bolo
+ Ultimo bolo%1$.1fh faDati di input non validiValore non impostato correttamente
- Ricaricare Profilo
- Visualizzare Profilo
- Attuato
+ Ricarica profilo
+ Visualizza profilo
+ AttivatoCommentoOKPer centoAssoluto
- Cancellare Basale Temporanea
+ Cancellare basale temporaneaComunicazioni SMSIn attesa del risultatoNumeri di telefono consentiti+XXXXXXXXXX;+YYYYYYYYYY
- Per erogare il bolo di %1$.2fU rispondere col codice %2$s
- Per inviare la calibrazione %1$.2f rispondere col codice %2$s
+ Per erogare il bolo di %1$.2fU rispondi col codice %2$s
+ Per erogare il bolo pasto di %1$.2fU rispondi col codice %2$s
+ Per impostare il Temp-Target %1$s rispondi con il codice %2$s
+ Per cancellare il Temp-Target rispondi col codice %1$s
+ Per disabilitare il Servizio di Controllo Remoto tramite SMS rispondi col codice %1$s.\n\nRicorda che potrai riattivarlo solo in maniera diretta dallo smartphone master in cui è installato AAPS.
+ Servizio di Controllo Remoto tramite SMS stoppato. Per riattivarlo, usa lo smartphone master in cui è installato AAPS.
+ Per inviare la calibrazione %1$.2f rispondi col codice %2$sBolo fallito
+ Numero minimo di minuti che devono trascorrere tra un bolo remoto e il successivo
+ Quanti minuti devono trascorrere, almeno, tra un bolo e il successivo
+ Per la tua sicurezza, per modificare questa preferenza hai bisogno di aggiungere almeno 2 numeri di telefono.Bolo di %1$.2fU erogato con successoSto per erogare %1$.2fUBolo di %1$.2fU erogato con successo
+ Bolo pasto di %1$.2fU erogato con successo
+ Target %1$s per %2$d minuti
+ Target %1$s per %2$d minuti impostato con successo
+ Temp-Target cancellato con successoErogazione di %1$.2fU
- Consentire comandi remoti tramite SMS
+ Consenti comandi remoti tramite SMSDitoSensoreManuale
- Target Temporaneo
- Cancellare Target Temporaneo
+ Target temporaneo
+ Cancella target temporaneoImpostazioni profilo DanaRDIA [h]Durata Azione dell\'InsulinaImpossibile aggiornare il profilo basale
- Ricaricare
+ RicaricaCaricamentoBolo EBolo DSBolo DE
- Errore
- ricaricare
+ errore
+ ricaricaora basaleglicemiacarboidrato
@@ -302,12 +308,12 @@
Insulina giornalieraErroriGlicemia
- Ricaricare
- Sospendere
+ Ricarica
+ SospensioneIn connessione per %1$d s
- Password Microinfusore
- Password micro Errata!
- Il Micro è occupato
+ Password microinfusore
+ Password micro errata!
+ Il micro è occupatoErogatoStoppatoBolo stoppato
@@ -317,21 +323,6 @@
STOP PREMUTOIn attesa del microSto per erogare %1$.2fU
- Configurazione della visualizzazione e del monitoraggio, analisi basali e rapporti
- Verificare che la Glicemia sia disponibile su Nightscout e che i dati sull\'insulina del micro siano in fase di caricamento
- Avvio in Loop Aperto
- Eseguire l\'applicazione in modalità Loop Aperto per alcuni giorni. Approvare manualmente il maggior numero possibile di basali temporanee suggerite prestando attenzione alla sicurezza. Impostare e utilizzare i target temporanei, anche quelli predefiniti (ad esempio per l\'attività fisica o il trattamento dell\'ipoglicemia con carboidrati)
- Comprensione tuo Loop Aperto, incluse le relative raccomandazioni sulle basali temporanee
- Sulla base di tale esperienza, decidere quale dovrebbe essere il valore di \'max basale\' e impostarlo sul microinfusore e nelle preferenze
- Avvio della chiusura del Loop con Low Glucose Suspend
- Eseguire l\'applicazione in Loop Chiuso con max IOB = 0 per pochi giorni senza troppi eventi LGS
- Regolazione del Loop Chiuso, aumentando max IOB al di sopra di 0 e abbassando gradualmente i target glicemici
- Eseguire l\'applicazione per alcuni giorni e almeno una notte senza allarmi di glicemia bassa, prima di abbassare il target glicemico
- Adattare basali e rapporti se necessario, quindi attivare auto-sens
- 1 settimana di looping diurno con dichiarazione regolare dei carboidrati, eseguito con successo
- Abilitazione funzioni aggiuntive per l\'uso diurno, ad esempio AMA (advanced meal assist - assistenza avanzata del pasto)
- Abilitazione funzioni aggiuntive per l\'uso diurno, come SMB
- È necessario leggere il wiki e aumentare maxIOB affinché le azioni di SMB funzionino adeguatamente! Un buon inizio è maxIOB = media bolo posto + 3 x max basale giornalieraHai raggiunto il limite consentitoNessun profilo selezionatoIl Loop è stato disabilitato
@@ -342,43 +333,46 @@
Il valore %1$s è fuori limite massimoIl comando da remoto non è permessoBolo remoto non disponibile. Riprova più tardi.
- Per avviare la basale %1$.2fU/h per %2$d min rispondere col codice %3$s
- Per passare al profilo %1$s %2$d%% rispondere col codice %3$s
- Per avviare il bolo esteso %1$.2fU/h per %2$d min rispondere col codice %3$s
- Per avviare la basale %1$d%% per %2$d min rispondere col codice %3$s
- Per sospendere il Loop per %1$d minuti rispondere col codice %2$s
- Basale Temporanea %1$.2fU/h per %2$d min avviata con successo
+ Per avviare la basale %1$.2fU/h per %2$d min rispondi col codice %3$s
+ Per passare al profilo %1$s %2$d%% rispondi col codice %3$s
+ Per avviare il bolo esteso %1$.2fU/h per %2$d min rispondi col codice %3$s
+ Per inserire %1$dg a %2$s rispondi col codice %3$s
+ Per avviare la basale %1$d%% per %2$d min rispondi col codice %3$s
+ Per sospendere il loop per %1$d minuti rispondi col codice %2$s
+ Basale temporanea %1$.2fU/h per %2$d min avviata con successoBolo esteso %1$.2fU/h per %2$d min avviato con successo
- Basale Temporanea %1$d%% per %2$d min avviata con successo
- Avvio Basale Temporanea fallito
- Avvio Bolo esteso fallito
- Per interrompere la Basale Temporanea rispondere col codice %1$s
- Per interrompere il bolo esteso rispondere col codice %1$s
- Basale Temporanea cancellata
+ CHO %1$dg inseriti con successo
+ Inserimento di %1$dg di CHO fallito
+ Basale temporanea %1$d%% per %2$d min avviata con successo
+ Avvio basale temporanea fallito
+ Avvio bolo esteso fallito
+ Per stoppare la basale temporanea rispondi col codice %1$s
+ Per stoppare il bolo esteso rispondi col codice %1$s
+ Basale temporanea cancellataBolo esteso cancellato
- Cancellazione Basale Temporanea fallita
+ Cancellazione basale temporanea fallitaCancellazione bolo esteso fallitaComando sconosciuto o risposta errata
- QuickWizard
- Impostazioni QuickWizard
- Testo pulsante:
- Carboidrati:
+ Calcolatore Rapido
+ Impostazioni Calcolatore Rapido
+ Testo:
+ CHO:Valido:
- Aggiungere
- Modificare
- Rimuovere
+ Aggiungi
+ Modifica
+ RimuoviPastoCorrezioneAzioniAndroidAPS avviato
- NS: solo upload (sincronizzazione disabilitata)
+ NS: solo upload (sincron. disabilitata)NS: solo upload. Non ha effetto su SGV a meno che non sia selezionata una fonte locale come xDrip. Non ha effetto sui Profili durante l\'utilizzo dei profili NS.Micro non inizializzato!Micro non inizializzato, profilo non impostato!
- Caricare/Riempire
+ Carica/RiempiAssicurati che la quantità corrisponda alla specifica del tuo set di infusione!Altro
- Quantità standard di insulina per la funzione Caricare/Riempire.
+ Quantità standard di insulina per Carica/Riempi.Tasto 1Tasto 2Tasto 3
@@ -386,28 +380,28 @@
mg/dlmmol/lDIA:
- Intervallo Target:
+ Intervallo target:Intervallo di visualizzazioneLimite alto e basso per i grafici nella sezione Panoramica e sullo SmartwatchLimite BASSOLimite ALTOSmartwatch
- Inviare di nuovo tutti i dati
- Aprire impostazioni sullo smartwatch
- Errore Micro
- Livello Batteria Basso
- Arresto Micro
- Batteria del micro Scarica
+ Invia di nuovo tutti i dati
+ Apri impostazioni sullo smartwatch
+ Errore micro
+ Livello batteria basso
+ Arresto micro
+ Batteria del micro scaricaDanaR KoreanVelocità basale:
- Impostazione Profilo Basale fallita
- Profilo Basale aggiornato nel Micro
- Disabilitare la modalità EasyUI nel micro
- Abilitare bolo esteso sul micro
- Cambiare la modalità da U/d in U/h nel micro
- Valore basale inferiore al minimo, Profilo non impostato!
+ Impostazione profilo basale fallita
+ Profilo basale aggiornato nel micro
+ Disabilita la modalità EasyUI nel micro
+ Abilita bolo esteso sul micro
+ Cambia la modalità da U/d a U/h nel micro
+ Valore basale inferiore al minimo. Profilo non impostato!Glicemia:
- Ultima Glicemia:
+ Ultima glicemia:MDIMM640gNotifica in corso
@@ -419,15 +413,15 @@
Delta medio ridottoDelta medio estesoMatrice di %1$d elementi.\nValore attuale:
- Dati Autosens
+ Dati autosensScript debug
- Usare la funzione Autosens
- Ricaricare eventi da NS
- Eliminare trattamenti nel futuro
- Pasto Imminente
+ Usa la funzione Autosens
+ Ricarica eventi da NS
+ Elimina trattamenti nel futuro
+ Pasto a breveIpoglicemiaAttività
- Rimuovere campo:
+ Rimuovi record:Statistiche DanaRTDD cumulativoTDD esponenzialmente ponderato
@@ -439,40 +433,40 @@
# GiorniPesoProbabilmente inaccurato se si usano i boli per il caricamento/riempimento al posto dell\'apposita funzione!
- Dati Vecchi, premere \"RICARICA\"
- Basale originale Totale
+ Dati vecchi, premi \"RICARICA\"
+ Basale originale totaleTBB * 2Inizializzazione...
- ACT
+ AZNCONFLOOP
- SP
+ PSOAPS
- LP
+ PLDANAHOME
- VPUMP
- NSPROFILE
- TREAT
- CP
- OBJ
- WEAR
+ MICROV
+ PROFILONS
+ TRATT
+ PT
+ OBT
+ SMWASMS
- Abbreviare i titoli delle schede
- Utilizzare sempre il delta medio ridotto anziché il delta semplice
+ Abbrevia i titoli delle schede
+ Utilizza sempre il delta medio ridottoUtile quando i dati provenienti da sorgenti non filtrate come xDrip diventano \"rumorosi\" (instabili).
- Impostazioni Avanzate
+ Impostazioni avanzateModello:%1$02X Protocollo:%2$02X Codice:%3$02XProfilo[Valore predefinito: 3] Questo è un parametro di sicurezza chiave in OpenAPS. Ciò che fa è limitare le tue basali a essere 3 volte, al più, la tua velocità basale massima. Probabilmente non avrai bisogno di cambiare questo valore, ma dovresti essere consapevole di cosa significa il gruppo di parametri \"3x max giornaliera; 4x corrente\" e per quali motivi di sicurezza siano stati impostati tali valori.[Valore predefinito: 4] Questo è un ulteriore parametro di sicurezza chiave in OpenAPS. La tua basale temporanea, indipendentemente dalla basale massima impostata sul micro, non può mai essere più alta di questo valore moltiplicato per tua basale corrente in ogni specifico momento. Questo serve a impedire alle persone di addentrarsi in \"territori pericolosi\" impostando basali massime eccessivamente alte prima di aver capito come funziona l\'algoritmo. Ancora una volta, il valore predefinito è 4x; la maggior parte delle persone non avrà bisogno di modificare questo valore e avrà, invece, maggiori probabilità di dover regolare le altre impostazioni.
- [Valore predefinito: 1.2]\nQuesto è un moltiplicatore di sicurezza per autosens (e presto autotune) per impostare un limite massimo del 20%% (col valore predefinito) su quanto alto può essere il rapporto di autosens, che a sua volta determina quanto in alto autosens può regolare la basale, quanto in basso può regolare ISF (la sensibilità all\'insulina) e quanto in basso può impostare il Target Glicemico.
- [Valore predefinito: 0.7]\nUn altro limite di sicurezza di autosens, imposta un blocco a quanto in basso autosens può regolare le basali e a quanto in alto può regolare ISF e i Target Glicemici.
+ [Valore predefinito: 1.2]\nQuesto è un moltiplicatore di sicurezza per autosens (e presto autotune) per impostare un limite massimo del 20%% (col valore predefinito) su quanto alto può essere il rapporto di autosens, che a sua volta determina quanto in alto autosens può regolare le basali, quanto in basso può regolare ISF e quanto in basso può impostare il target glicemico.
+ [Valore predefinito: 0.7]\nUn altro limite di sicurezza di autosens, imposta un blocco a quanto in basso autosens può regolare le basali e a quanto in alto può regolare ISF e i target glicemici.Autosens regola anche i target
- [Valore predefinito: vero]\nViene utilizzato per consentire ad autosens di regolare i Target Glicemici, in aggiunta a ISF e basali.
- [Valore predefinito: 2]\nBolus snooze è attivato dopo un bolo pasto per fare in modo che il Loop non imposti basali temporanee basse quando hai appena mangiato. AndroidAPS non imposterà velocità basali troppo basse nel periodo corrispondente a DIA (durata azione dell\'insulina) diviso il parametro bolus snooze - divisore DIA. Con DIA di 3 ore \"bolus snooze\" durerà 1.5 ore (3/2).
- [Valore predefinito: 3.0 (AMA) o 8.0 (SMB)]. Questa è un\'impostazione per l\'impatto di assorbimento predefinito dei carboidrati in 5 minuti. L\'impostazione predefinita è una previsione di 3mg/dl/5min. Ha effetto sulla velocità di decadimento dei COB (carboidrati attivi) e su quanto il loro assorbimento incide nella previsione dell’andamento glicemico, quando la Glicemia sta scendendo più del previsto o non sta salendo quanto previsto.
- Attenzione!\nNormalmente non dovresti modificare questi valori. FAI CLICK QUI e leggi il testo e assicuratevi di AVERLO CAPITO prima di cambiare uno di questi valori.
+ [Valore predefinito: vero]\nViene utilizzato per consentire ad autosens di regolare i target glicemici, in aggiunta a ISF e basali.
+ [Valore predefinito: 2]\nBolus snooze è attivato dopo un bolo pasto per fare in modo che il loop non imposti basali temporanee basse quando hai appena mangiato. AndroidAPS non imposterà velocità basali troppo basse nel periodo corrispondente a DIA diviso il parametro bolus snooze - divisore DIA. Con DIA di 3 ore \"bolus snooze\" durerà 1.5 ore (3/2).
+ [Valore predefinito: 3.0 (AMA) o 8.0 (SMB)]. Questa è un\'impostazione per l\'impatto di assorbimento predefinito dei carboidrati in 5 minuti. L\'impostazione predefinita è una previsione di 3mg/dl/5min. Ha effetto sulla velocità di decadimento dei COB (carboidrati attivi) e su quanto il loro assorbimento incide nella previsione dell’andamento glicemico, quando la glicemia sta scendendo più del previsto o non sta salendo quanto previsto.
+ Attenzione!\nNormalmente non dovresti modificare questi valori. FAI CLICK QUI e leggi il testo e assicurati di AVERLO CAPITO prima di cambiare uno di questi valori.Sono consentite solo cifre numeriche.Sono consentite solo cifre numeriche nel range %1$s - %2$s.Il campo non deve essere vuoto
@@ -484,120 +478,120 @@
Calibrazione inviata a xDripCalibrazione inviata. La ricezione deve essere abilitata in xDrip.xDrip non sta ricevendo calibrazioni
- Micro Sospeso
- Ricezione Stato Micro
- Impostazione Basale Temporanea
- Stop Basale Temporanea
+ Micro sospeso
+ Ricezione stato micro
+ Impostazione basale temporanea
+ Stop basale temporaneaImpostazione bolo estesoStop bolo estesoAggiornamento velocità basaliDisconnessioneEsecuzione
- Impostazioni Micro virtuale
- Caricare stato in NS
+ Impostazioni micro virtuale
+ Carica stato in NSPassword ErrataPassword per le impostazioni
- Sbloccare impostazioni
+ Sblocca impostazioniSi avvicina il limite giornaliero di insulinaNSClientNSCIURL:Autoscorrimento
- Riavviare
+ RiavvioNSClient
- Nightscout URL
- Inserisci il tuo URL Nightscout
- NS API secret
- NS API secret
- Inserire NS API secret (minimo 12 caratteri)
- Erogare adesso
- Cancellare la coda
- Visualizzare la coda
+ URL di Nightscout
+ Inserisci il tuo URL di Nightscout
+ API secret di NS
+ API secret di NS
+ Inserisci l\'API secret di NS (minimo 12 caratteri)
+ Invia ora
+ Cancella coda
+ Mostra codaCoda:Stato:
- In Pausa
- Cancellare il log
- NSCLIENT non ha il permesso di scrittura. API secret Errato?
- Impostazioni Smartwatch
- Mostrare IOB dettagliato
- Dividere IOB tra boli e IOB da basale, sulla watchface dello smartwatch
- non riuscito - controllare il telefono
+ In pausa
+ Cancella log
+ NSCLIENT non ha il permesso di scrittura. API secret errato?
+ Impostazioni smartwatch
+ Mostra IOB dettagliato
+ Dividi IOB in bolo e basale sulla watchface
+ non riuscito - controlla il telefonoNon disponibileEtà del pazienteBambinoAdolescenteAdultoAdulto insulino-resistente
- Selezionare l\'età del paziente per impostare i limiti di sicurezza
+ Seleziona l\'età del paziente per impostare i limiti di sicurezzaGlimpPer un buon funzionamento, %1$s ha bisogno di essere nella whitelist della funzione \"ottimizzazione batteria\" di AndroidLoop sospesoSospeso (%1$d m)Superbolo (%1$d m)
- Sospendere loop
- Sospendere loop per 1h
- Sospendere loop per 2h
- Sospendere loop per 3h
- Sospendere loop per 10h
- Sospendere loop per %1$d min
- Disconnettere Micro per 15 min
- Disconnettere Micro per 30 min
- Disconnettere Micro per 1 h
- Disconnettere Micro per 2 h
- Disconnettere Micro per 3 h
- Riprendere
- Riconnettere Micro
+ Sospendi loop
+ Sospendi loop per 1h
+ Sospendi loop per 2h
+ Sospendi loop per 3h
+ Sospendi loop per 10h
+ Sospendi loop per %1$d min
+ Disconnetti micro per 15 min
+ Disconnetti micro per 30 min
+ Disconnetti micro per 1 h
+ Disconnetti micro per 2 h
+ Disconnetti micro per 3 h
+ Riprendi
+ Riconnetti microDurata errataLoop sospesoLoop ripreso
- Trend 15min
+ Trend di 15minCOB
- Super bolo
- Registrare l\'avvio dell\'app in NS
+ Superbolo
+ Registra l\'avvio dell\'app in NSUscita dall\'applicazione per applicare le impostazioni.DanaRv2InsulinaQuale tipo di insulina stai usando?
- Insulina Fast Acting (ultrarapida)
+ Insulina Fast ActingNovorapid, Novolog, HumalogFiaspINS
- Abilitare Super Bolo nel Calcolatore
- Abilitare la funzionalità Super Bolo nel Calcolatore. Non abilitare fino a quando non impari ciò che realmente fa. PUÒ CAUSARE SOVRADOSAGGIO DI INSULINA SE USATO IMPROPRIAMENTE!
- Mostrare \"indicatori di stato\" sulla schermata iniziale
- Mostrare \"indicatori di stato\" estesi sulla schermata iniziale
- Abilitare indicatori di stato estesi per \"età\" cannula, insulina, sensore, serbatoio e livello batteria sulla schermata iniziale.
+ Abilita superbolo nel calcolatore
+ Abilita la funzionalità superbolo nel calcolatore. Non abilitare fino a quando non impari ciò che realmente fa. PUÒ CAUSARE SOVRADOSAGGIO DI INSULINA SE USATO IMPROPRIAMENTE!
+ Mostra indicatori di stato sulla home
+ Mostra indicatori estesi sulla home
+ Abilita indicatori di stato estesi per \"età\" cannula, insulina, sensore, serbatoio e livello batteria sulla schermata iniziale.Soglia di avviso livello serbatoio [U]
- Soglia critica livello serbatoio [U]
- Soglia di avviso livello batteria [%%]
- Soglia critica livello batteria [%%]
+ Soglia livello serbatoio critico [U]
+ Soglia di avviso livello batteria [%]
+ Soglia livello batteria critico [%]IOBCOBFirmwareUltima connessione
- Stato Bluetooth
- Riguardo a
+ Stato bluetooth
+ Informazioni suAutorizzazione SMS mancante
- Autorizzazione Stato telefono mancante
+ Autorizzazione stato telefono mancanteStato xDrip (smartwatch)xDrip Statusline (smartwatch)xds
- Mostrare BGI
- Aggiungere BGI alla statusline
+ Mostra BGI
+ Aggiungi BGI alla statuslineNessun caricamento in NSTutti i dati inviati a NS vengono rifiutati. AAPS è connesso a NS, ma non vengono apportate modifiche
- Incremento Basale
- Incremento Bolo
- Bolo Esteso
+ Incremento basale
+ Incremento bolo
+ Bolo estesoTempTarget
- Cancella Bolo Esteso
+ Cancella bolo estesoEtà sensoreEtà cannulaEtà insulinaoreTipo basaleProfilo non valido !!!
- Cambio Profilo
+ Cambio profiloEtà batteria microCambio batteria microOpzioni allarme
@@ -607,8 +601,8 @@
Molto bassoDati non aggiornatiDati non aggiornati da molto tempo
- Soglia Dati non aggiornati [min]
- Soglia Dati non aggiornati da molto tempo [min]
+ Soglia dati non aggiornati [min]
+ Soglia dati non aggiornati da molto tempo [min]Intervallo per autosens [h]Quantità di ore al passato per il rilevamento della sensibilità (il tempo di assorbimento dei carboidrati è escluso)Micro
@@ -627,62 +621,62 @@
SAGEIAGECAGE
- PBAGE
+ MBAGEOAPSUPLDBASEXT
- Mantenere lo schermo acceso
- Impedire ad Android di disattivare lo schermo. Consumerà molta energia quando non è collegato alla presa di corrente.
- Attivando la funzione Autosense, ricordare di dichiarare tutti i carboidrati assunti. Altrimenti le deviazioni di glicemia dovute ai carboidrati saranno identificate erroneamente come variazione di sensibilità !!
+ Mantieni lo schermo acceso
+ Evita che Android disattivi lo schermo. Consumerà molta energia quando non è collegato alla presa di corrente.
+ Attivando la funzione Autosense, ricorda di dichiarare tutti i carboidrati assunti. Altrimenti le deviazioni di glicemia dovute ai carboidrati saranno identificate erroneamente come variazione di sensibilità !!Sensibilità WeightedAverageOKAnnullaNon tutti i profili caricati!Valori non memorizzati!
- Abilitare le trasmissioni ad altre app (come xDrip). Non abilitare se hai installato più di un\'istanza di AAPS o NSClient!
- Abilitare le trasmissioni locali.
+ Abilita le trasmissioni ad altre app (come xDrip). Non abilitare se hai installato più di un\'istanza di AAPS o NSClient!
+ Abilita le trasmissioni locali.ATTIVITÀ & FEEDBACK
- CARBOIDRATI & BOLO
+ CHO & BOLOCGM & OPENAPSMICROValore basale [U/h]Durata [min]OpenAPS SMBSMB
- Abilitare UAM
- Abilitare SMB
- Utilizzare Super Micro Boli al posto della basale temporanea per un\'azione più veloce
- Rilevazione dei Pasti Non Annunciati
+ Abilita UAM
+ Abilita SMB
+ Utilizza Super Micro Boli al posto della basale temporanea per un\'azione più veloce
+ Rilevazione dei pasti Non AnnunciatiIOB Curve Peak TimePeak Time [min]Free-Peak OrefRapid-Acting OrefUltra-Rapid OrefDIA di %1$f troppo breve - al suo posto, utilizzo %2$f.
- Attivare profilo
+ Attiva profiloDataNON VALIDOIn attesa di associare il microAssociazione OK
- Time Out associazione micro
+ Time out associazione microASSOCIAZIONENessun dispositivo trovato finoraSerbatoio vuoto
- Avviso misurazione di glicemia
+ Avviso misurazione glicemiaLivello insulina rimanenteDanaRSDanaMicro selezionato
- Associare nuovo micro
+ Associa nuovo microVelocità bolo
- Impostare incremento basale a 0.01 U/h
+ Imposta incremento basale a 0.01 U/hNumero serialePercentuale
- Cambio orario
+ Time shiftTemp-Target predefiniti
- target \"pasto imminente\" - durata
- target \"pasto imminente\"
+ target \"pasto a breve\" - durata
+ target \"pasto a breve\"target \"attività\" - duratatarget \"attività\"target \"ipoglicemia\" - durata
@@ -693,19 +687,20 @@
Ricezione stato basale temporaneaRicezione stato microRicezione ora micro
- riutilizzare
+ riutilizzoControlli da smartwatch
- Impostare Temp-Target e inserire Trattamenti dallo smartwatch.
- Time Out Connessione
+ Imposta Temp-Target e inserisci Trattamenti dallo smartwatch.
+ Time out connessioneCibogmh
+ g]]>kJ
- En
- Pr
- Fat
+ Enr
+ Prt
+ Grs]]>Attesa per la fine del bolo. Rimangono %1$d sec.Evento di elaborazione
@@ -713,65 +708,66 @@
Il comando verrà eseguito oraDriver del micro correttoMicro irraggiungibile
- Letture Glicemia mancanti
- Utilizzare le notifiche di sistema per avvisi e notifiche
+ Letture glicemia mancanti
+ Usa le notifiche di sistema per gli avvisiAllarmi locali
- Allarme se non si ricevono dati Glicemia
+ Allarme se non si ricevono dati glicemiaAllarme se il micro non è raggiungibileSoglia micro irraggiungibile [min]
- Allarme Urgente
+ Allarme urgenteINFOBluetoothBT Watchdog
- Spegnere il bluetooth del telefono per qualche secondo se non è possibile alcuna connessione al micro. Questo può essere utile su alcuni telefoni.
- Eversense App (modificata)
- Caricare dati Glicemia su NS
- Impostazioni caricamento Glicemia
- Visualizzare delta dettagliato
- Visualizzare delta con una cifra decimale in più
- Max minuti di basale ai quali limitare SMB
+ Spegne il bluetooth del telefono per qualche secondo se non è possibile alcuna connessione al micro. Questo può essere utile su alcuni telefoni.
+ Eversense app (modificata)
+ Carica dati glicemia su NS
+ Impostazioni caricamento glicemia
+ Mostra delta dettagliato
+ Mostra delta con una cifra decimale in più
+ Max minuti SMB
+ Max minuti di basale a cui limitare SMBFirmware del micro non supportato
- Inviare dati Glicemia a xDrip+
- In xDrip+ selezionare origine dati 640g/Eversense
+ Invia dati glicemia a xDrip+
+ In xDrip+ seleziona origine dati 640g/EversenseGlicemia NSClientValore basale sostituito dal minimo valore supportato: %1$sValore basale sostituito dal massimo valore supportato: %1$s
- Calcolo Glicemia
+ Calcolo glicemiaCalcolo IOB da boloCalcolo IOB da basale
- Calcolo Trend
- Calcolo Super Bolo
+ Calcolo trend
+ Calcolo superboloSìNo
- Solo Positivo
- Solo Negativo
+ Solo positivo
+ Solo negativoCalcolo COB
- Calcolo Target Temporaneo
+ Calcolo target temporaneoLoop abilitatoAPS selezionatoNSClient ha il permesso di scrittura
- Modalità Chiusa attivata
+ Modalità chiusa abilitataMax IOB impostata correttamenteGlicemia disponibile da sorgente selezionataValori basali non allineati alle ore: %1$sProfilo non valido: %1$sProgrammazione micro per erogazione
- Ricaricare
+ RicaricaStatoAttivitàNessuna connessione per %1$d min%1$d%% (%2$d min restanti)Inizializzazione
- Sospeso a causa di errore
+ Sospeso a causa di un erroreSospeso dall\'utenteIn esecuzioneCancellazione TBRImpostazione TBR (%1$d%% / %2$d min)
- Erogazione Bolo (%1$.1f U)
+ Erogazione bolo (%1$.1f U)AggiornamentoOperazione richiesta non supportata dal micro
- Utilizzo non sicuro: sono attivi boli estesi o multiwave. Il Loop è stato messo in modalità di sola sospensione dell\'erogazione di insulina in caso di valori bassi, per 6 ore. In modalità Loop sono supportati solo boli normali
- Utilizzo non sicuro: il micro utilizza un profilo basale diverso dal primo in elenco tra le sue impostazioni. Il Loop è stato disabilitato. Selezionare sul microinfusore il profilo basale numero 1.
+ Utilizzo non sicuro: sono attivi boli estesi o multiwave. Il loop è stato messo in modalità di sola sospensione dell\'erogazione di insulina in caso di valori bassi, per 6 ore. In modalità loop sono supportati solo boli normali
+ Utilizzo non sicuro: il micro utilizza un profilo della velocità basale diverso dal primo in elenco tra le sue impostazioni. Il loop è stato disabilitato. Selezionare sul microinfusore il profilo basale numero 1.Un bolo con la stessa quantità è stato richiesto negli ultimi due minuti. Questo non è consentito al fine di evitare boli doppi accidentali e a protezione di eventuali \"bug\".AdessoLettura storico micro
@@ -787,118 +783,116 @@
AttenzioneAvviso TBR CANCELLATO confermatoIl micro potrebbe non essere raggiungibile. Nessun bolo erogato
- Erogazione bolo fallita. Sembra che nessun bolo sia stato erogato. Per sicurezza, controllare il micro per evitare un doppio bolo e se è tutto ok, erogarlo di nuovo. Come protezione da eventuali \"bug\", i boli non vengono ripetuti automaticamente.
- Solo la quantità di %1$.2f U del bolo richiesto di %2$.2f U è stata erogata a causa di un errore. Controllare il micro per verificare quanto accaduto e intraprendere le azioni necessarie.
+ Erogazione bolo fallita. Sembra che nessun bolo sia stato erogato. Per sicurezza, controlla il micro per evitare un doppio bolo e se è tutto ok, erogalo di nuovo. Come protezione da eventuali \"bug\", i boli non vengono ripetuti automaticamente.
+ Solo la quantità di %1$.2f U del bolo richiesto di %2$.2f U è stata erogata a causa di un errore. Controlla il micro per verificare quanto accaduto e intraprendi le azioni necessarie.Erogazione del bolo e verifica dello storico del micro fallite, si prega di controllare il micro. Se è stato erogato un bolo, sarà aggiunto ai trattamenti durante la successiva connessione al micro.Insulina nel serbatoio insufficiente per erogare il boloErrore erogazione bolo estesoSightfa%1$.2f h
- Abilitare SMB sempre
- Abilitare SMB sempre, indipendentemente dai boli. Possibile solo con sorgente glicemie con un buon filtraggio dei dati, come G5
- Abilitare SMB dopo i carboidrati
- Abilitare SMB per 6h dopo i carboidrati, anche con 0 COB. Possibile solo con sorgente glicemie con un buon filtraggio dei dati, come G5
- Abilitare SMB con COB
- Abilitare SMB quando COB è attivo (ci sono carboidrati non assorbiti).
- Abilitare SMB con temp-target
- Abilitare SMB quando è attivo un temp-target (pasto imminente, attività)
- Abilitare SMB con temp-target \"alti\"
- Abilitare SMB quando è attivo un temp-target \"alto\"
- Lasciare in esecuzione / consentire la Basale Temporanea
+ Abilita SMB sempre
+ Abilita SMB sempre, indipendentemente dai boli. Possibile solo con sorgente glicemia con un buon filtraggio dei dati, come G5
+ Abilita SMB dopo i CHO
+ Abilita SMB per 6h dopo i carboidrati, anche con 0 COB. Possibile solo con sorgente glicemia con un buon filtraggio dei dati, come G5
+ Abilita SMB con COB
+ Abilita SMB quando COB è attivo (ci sono carboidrati non assorbiti).
+ Abilita SMB con target temporanei
+ Abilita SMB quando è attivo un target temporaneo (pasto a breve, attività)
+ Abilita SMB con target temporanei \"alti\"
+ Abilita SMB quando è attivo un target temporaneo \"alto\"
+ Lascia eseguire la basale temporaneaMutoInsulina
- Carboidrati
+ CHOTasti
- Inviare una calibrazione a xDrip+ o aprire la finestra di calibrazione del G5
- Aprire xDrip+, il pulsante indietro torna ad AAPS
+ Invia una calibrazione a xDrip+ o apre la finestra di calibrazione del G5
+ Apre xDrip+, il tasto indietro torna ad AAPSNumero di carboidrati da aggiungere quando si preme il tastoQuantità di insulina da aggiungere quando si preme il tasto
- Impossibile avviare applicazione CGM. Assicurarsi che sia installata.
+ Impossibile avviare l\'applicazione CGM. Assicurati che sia installata.CGM
- Rivedi storico
- Notificare SMB
- Mostrare SMB sullo smartwatch come un bolo standard.
- Creare avvisi da errori
- Creare avviso su Nightscout per finestre di errore e allarmi locali (anche visualizzabile nella sezione Portale sotto la voce Trattamenti)
- Visualizzare le predizioni sulla watchface.
+ Storico
+ Notifica SMB
+ Mostra SMB sullo smartwatch come un bolo standard.
+ Crea avvisi da errori
+ Crea avviso su Nightscout per finestre di errore e allarmi locali (visualizzabile anche nella sezione Portale sotto la voce Trattamenti)
+ Mostra le predizioni sulla watchface.Predizioni
- Scelta dei Dati
+ Scelta dei datiInvio a fabric.io
- Consentire la segnalazione automatica degli errori e l\'invio dei dati di utilizzo delle funzioni dell\'app agli sviluppatori tramite il servizio fabric.io.
+ Consenti la segnalazione automatica degli errori e l\'invio dei dati di utilizzo delle funzioni dell\'app agli sviluppatori tramite il servizio fabric.io.Aggiorna la tua app Dexcom ad una versione supportataApp Dexcom non installata.
- Avviare TT Attività
- Avviare TT Pasto Imminente
+ Avvia TT Attività
+ Avvia TT Pasto a breveTTNo bolo, solo recordCategoriaSottocategoria
- Il bolo sarà solo memorizzato
- Riempimento automatico Glicemie mancanti da NS
+ Il bolo sarà solo registrato
+ Riempimento automatico glicemie mancanti da NSSMB impostato dal microAttivitàSensibilitàDeviazioni
- Carboidrato attivi (COB)
- Insulina attiva (IOB)
+ CHO attivi
+ Insulina attivaBasaliNessuna azione selezionata, non succederà nulla
- Avviare TT Ipoglicemia
- Versione sviluppatore in esecuzione. Loop Chiuso disabilitato.
+ Avvia TT Ipoglicemia
+ Versione sviluppatore in esecuzione. Loop chiuso disabilitato.Engineering mode abilitataEngineering mode non abilitata e non su \'release branch\'%1$.2f U/hLettura profilo basaleLo storico del micro è cambiato dopo il calcolo del bolo. Il bolo non è stato erogato. Ricalcolare se un bolo è ancora necessario.
- Bolo erogato con successo, ma impossibile aggiungere la voce ai Trattamenti. Questo può accadere se due piccoli boli della stessa quantità sono stati somministrati negli ultimi due minuti. Verificare lo storico del micro e le voci della sezione Trattamenti e utilizzare la sezione Portale per aggiungere eventuali voci mancanti. Assicurarsi di non aggiungere voci con lo stesso orario e con la stessa quantità.
+ Bolo erogato con successo, ma impossibile aggiungere la voce ai trattamenti. Questo può accadere se due piccoli boli della stessa quantità sono stati somministrati negli ultimi due minuti. Verifica lo storico del micro e le voci della sezione Trattamenti e utilizza la sezione Portale per aggiungere eventuali voci mancanti. Assicurati di non aggiungere voci con lo stesso orario e con la stessa quantità.Rifiuto basale temporanea \"alta\" in quanto il calcolo non ha considerato i cambiamenti recenti allo storico del microAggiornamento stato micro
- La velocità basale nel micro è cambiata e verrà presto aggiornata
+ La velocità basale nel micro è cambiata e verrà aggiornata a breveVelocità basale cambiata sul micro, ma la sua lettura è fallitaControllo delle modifiche allo storico
- Sono stati importati più boli con la stessa quantità nello stesso minuto. Solo un record può essere aggiunto ai Trattamenti. Controllare il micro e aggiungere manualmente un record di bolo utilizzando la sezione Portale. Assicurarsi di creare un bolo con un orario non utilizzato da nessun altro bolo.
+ Sono appena stati importati più boli con la stessa quantità nello stesso minuto. Solo un record può essere aggiunto ai trattamenti. Controlla il micro e aggiungi manualmente un record di bolo utilizzando la sezione Portale. Assicurati di creare un bolo con un orario non utilizzato da nessun altro bolo.\n\nhttp://www.androidaps.org\nhttp://www.androidaps.de (de)\n\nfacebook:\nhttp://facebook.androidaps.org\nhttp://facebook.androidaps.de (de)
- L\'ultimo bolo è più vecchio di 24 ore o ha una data nel futuro. Controllare che la data sul micro sia impostata correttamente.
- L\'ora/la data del bolo erogato sul micro sembra errata, IOB probabilmente non è corretto. Controllare l\'ora e/o la data del micro.
- Nessun cambio profilo eseguito. Effettuare un cambio profilo o premere \"Attivare Profilo\" nella sezione Profilo Locale.
- Conteggio Bolo
+ L\'ultimo bolo è più vecchio di 24 ore o ha una data nel futuro. Controlla che la data sul micro sia impostata correttamente.
+ L\'ora/la data del bolo erogato sul micro sembra errata, IOB probabilmente non è corretto. Controlla l\'ora e/o la data del micro.
+ Nessun cambio profilo. Effettua un cambio profilo o premi \"Attiva profilo\" nella sezione Profilo locale.
+ Conteggio boloConteggio TBR
- Obiettivo %1$d non avviato
- Obiettivo %1$d non terminatoMicro non in grado di impostare la basale temporaneaNessuna velocità basale valida letta dal micro
- Modalità Loop Chiuso disabilitata nelle preferenze
+ Modalità loop chiuso disabilitata nelle preferenzeAutosens disabilitato nelle preferenzeSMB disabilitato nelle preferenzeUAM disabilitato nelle preferenzeUAM disabilitato perché il plugin di sensibilità Oref1, dal quale UAM dipende, non è abilitato
- Limitazione max velocità basale a %1$.2f U/h. Causa: %2$s
+ Limitazione max velocità basale a %1$.2f U/h a causa di: %2$slimite microdeve essere un valore positivo
- moltiplicatore - max basale
- moltiplicatore - max basale giornaliera
+ moltiplicatore max basale
+ moltiplicatore max basale giornalieraUn bolo è stato erogato negli ultimi 3 minuti, SMB ignoratoBasale impostata correttamente
- Limito max tasso percentuale a %1$d%% - Causa: %2$s
- Limito il bolo a %1$.1f U - Causa: %2$s
- Limito il bolo esteso a %1$.1f U - Causa: %2$s
- Limito max IOB a %1$.1f U - Causa: %2$s
- Limito i carboidrati a %1$d g Causa: %2$s
- Limito IOB a %1$.1f U - Causa: %2$s
+ Limitazione max tasso percentuale a %1$d%% a causa di: %2$s
+ Limitazione bolo a %1$.1f U a causa di: %2$s
+ Limitazione bolo esteso a %1$.1f U a causa di: %2$s
+ Limitazione max IOB a %1$.1f U a causa di: %2$s
+ Limitazione carboidrati a %1$d g a causa di: %2$s
+ Limitazione IOB a %1$.1f U a causa di: %2$svalore max nelle preferenzelimite fissoutilizzo non sicuroLettura stato fallita
- Registrare cambio posizione cannula
- Registrare cambio serbatoio insulina
- Le funzioni \"SMB sempre\" e \"SMB dopo carboidrati\" sono disabilitate perché la sorgente dati della Glicemia non supporta il filtraggio avanzato
- SMB non consentito in modalità Loop Aperto
+ Registra cambio posizione cannula
+ Registra cambio serbatoio insulina
+ Le funzioni \"SMB sempre\" e \"SMB dopo i CHO\" sono disabilitate perché l\'attuale sorgente delle glicemie non supporta il filtraggio avanzato
+ SMB non consentito in modalità loop apertoCiboresetIn attesa della sincronizzazione dell\'ora (%1$d sec)Disconnesso (%1$d m)
- Max IOB totale oltre la quale OpenAPS non può andare [U]
+ Max IOB totale a cui limitare OpenAPS [U]Questo valore è chiamato Max IOB nel contesto OpenAPS\nOpenAPS non aggiungerà ulteriore insulina se IOB corrente è maggiore di questo valoreMicro stoppatoMicro avviato
@@ -906,24 +900,24 @@
Max tempo assorbimento pasto [h]Tempo entro il quale ogni pasto si considera assorbito. Eventuali carboidrati rimanenti verranno tagliati fuori.Tempo
- Mostrare campo note nelle finestre trattamento
+ Finestre tratt.nto: mostra campo noteAvantiIndietroConfigurazione guidataFINE
- Selezionare la tua lingua
+ Seleziona la tua linguaChiesto: %1$.2fU Erogato: %2$.2fU Codice errore: %3$sPrimo incremento di insulinaSecondo incremento di insulinaTerzo incremento di insulina
- Primo incremento di carboidrati
- Secondo incremento di carboidrati
- Terzo incremento di carboidrati
+ Primo incremento di CHO
+ Secondo incremento di CHO
+ Terzo incremento di CHOCGMUsa solo connessione WiFiWiFi SSIDSolo se in carica
- Impostazioni Connessione
+ Impostazioni connessioneSSID ammessi (separati da punto e virgola)Consenti connessione in roamingMax rapporto autosens
@@ -936,104 +930,103 @@
Definizione microBolo: Step=%1$s\nBolo Esteso: [Step=%2$s, Durata=%3$smin-%4$sh]\nBasale: Step=%5$s\nTBR: %6$s (di %7$s), Durata=%8$smin-%9$sh\n%10$s* Sono supportati solo valori discreti, non intervalli di valori, come incrementi per basale/bolo nel micro virtuale.
- Riempimento automatico Glicemie
- Impostazioni Wizard
- Calcoli inclusi nel risultato della procedura guidata:
- Impostazioni visualizzazione
+ Riempimento automatico glicemie
+ Impostazioni Calcolatore
+ Calcoli inclusi nel risultato del Calcolatore:
+ Impostazioni di visualizzazioneImpostazioni generali
- Abilitare NSClient
+ Abilita NSClientBenvenuto nella configurazione guidata. Ti seguirò durante tutto il processo.\nSetup MicroLettura statoLe modifiche devono essere fatte in NS
- Saltare configurazione guidata
- Premere il pulsante in basso per permettere ad AndroidAPS di suggerire/fare modifiche alla basale
- Configurare il plugin APS
- Configurare il plugin di Sensibilità
- Il plugin di Sensibilità è utilizzato per il rilevamento della sensibilità all\'insulina e il calcolo di COB. Per ulteriori informazioni visitare:
+ Salta configurazione guidata
+ Premi il tasto in basso per permettere ad AndroidAPS di suggerire/fare modifiche alla basale
+ Configura il plugin APS
+ Configura il plugin di Sensibilità
+ Il plugin di Sensibilità è utilizzato per il rilevamento della sensibilità all\'insulina e il calcolo di COB. Per ulteriori informazioni visita:https://github.com/MilosKozak/AndroidAPS/wiki/Sensitivity-detection-and-COBNSClient gestisce la connessione a Nightscout. Puoi saltare questa parte ora, ma non sarai in grado di superare gli obiettivi fino a quando non ne porterai a termine la configurazione.Ricorda: i nuovi profili di insulina richiedono una DIA di almeno 5h. DIA di 5 - 6h sui nuovi profili sono uguali a DIA di 3h sui vecchi profili di insulina.
- Configurare sorgente Glicemie
- Selezionare il tipo di profilo. Se il paziente è un bambino dovresti utilizzare il profilo di NS. Se non c\'è nessuno a seguirti su Nightscout probabilmente preferirai il profilo locale. Ricorda che stai solo selezionando la sorgente del profilo. Per utilizzarlo devi attivarlo tramite l\'esecuzione del comando \"Cambio Profilo\"
- Selezionare uno degli algoritmi disponibili. Sono ordinati dal più vecchio al più recente. L\'algoritmo più recente è solitamente più potente, incisivo e \"aggressivo\". Pertanto, se sei un nuovo utente, probabilmente potresti/dovresti iniziare con AMA e non con l\'ultimo. Non dimenticare di leggere la documentazione di OpenAPS e di configurarlo prima dell\'uso.
- Inizia il tuo primo obiettivo
+ Configura sorgente glicemia
+ Seleziona il tipo di profilo. Se il paziente è un bambino dovresti utilizzare il profilo di NS. Se non c\'è nessuno a seguirti su Nightscout probabilmente preferirai il profilo locale. Ricorda che stai solo selezionando la sorgente del profilo. Per utilizzarlo devi attivarlo tramite l\'esecuzione del comando \"Cambio profilo\"
+ Seleziona uno degli algoritmi disponibili. Sono ordinati dal più vecchio al più recente. L\'algoritmo più recente è solitamente più potente e più aggressivo. Pertanto, se sei un nuovo utente, probabilmente dovresti iniziare con AMA e non con l\'ultimo. Non dimenticare di leggere la documentazione di OpenAPS e di configurarlo prima dell\'uso.
+ Avvia il tuo primo obiettivoPermessoChiedi il permesso
- L\'applicazione richiede l\'accesso alla posizione per eseguire lo scan Bluetooth
+ L\'applicazione richiede l\'accesso alla posizione per eseguire lo scan bluetoothL\'applicazione richiede l\'accesso alla memoria per salvare i file di logRichiesta
- Configura il plugin insulina
- Uscita
- Opzioni Utente
+ Configura il plugin Insulina
+ Esci
+ Opzioni utenteFormato dell\'ora
- Pulsante di scorrimento
- Suono alla pressione del pulsante
+ Tasto di scorrimento
+ Suono alla pressione del tastoAllarmeSuonoVibrazioneEntrambiLCD acceso [s]Retroilluminazione accesa [s]
- Unità Glucosio
+ Unità glucosioSpegnimento(ore)Livello serbatoio basso (Unità)
- Salvare opzioni nel micro
+ Salva opzioni nel microOnOff
- Aprire navigazione
- Chiudere navigazione
- Preferenze Plugin
+ Apri navigazione
+ Chiudi navigazione
+ Preferenze pluginCompletato, ben fatto!Non ancora completatoTempo trascorso
- %1$d. ObiettivoPoctech
- Ricevere valori Glicemia da app Poctech
- Ricevere valori Glicemia da app Tomato (dispositivo MiaoMiao)
+ Ricevi valori glicemia da app Poctech
+ Ricevi valori glicemia da app Tomato (dispositivo MiaoMiao)Temp-Target \"alto\" aumenta la sensibilità
- = 100]]>
+ = 100]]>Temp-Target \"basso\" riduce la sensibilità
-
- Configurazione micro non valida, controllare la documentazione e verificare che il menu Quick Info sia denominato QUICK INFO utilizzando \"360 configuration software\".
+
+ Configurazione micro non valida, controlla la documentazione e verifica che il menu Quick Info sia denominato QUICK INFO utilizzando \"360 configuration software\".PersonalizzatoGrande differenza d\'orario
- Grande differenza d\'orario:\nL\'orario nel micro differisce per più di 1h e 30m. \nRegolare l\'ora manualmente e assicurarsi che la lettura dello storico del micro non causi comportamenti imprevisti.\nSe possibile, cancellare la cronologia del micro prima di cambiare l\'orario oppure disabilitare il Loop Chiuso per un tempo corrispondente alla tua DIA.
- Rimuovere gli eventi \"AndroidAPS avviato\"
+ Grande differenza d\'orario:\nL\'orario nel micro differisce per più di 1h e 30m. \nRegola l\'ora manualmente e assicurati che la lettura dello storico dal micro non causi comportamenti imprevisti.\nSe possibile, cancella la cronologia del micro prima di cambiare l\'orario oppure disabilita il loop chiuso per un tempo corrispondente al tuo valore DIA.
+ Rimuovi gli eventi \"AndroidAPS avviato\"Trovate impostazioni salvate
- Attenzione: se attivi e connetti un micro, AndroidAPS copierà le impostazioni della basale dal profilo al micro, sovrascrivendo la velocità basale memorizzata sul micro. Assicurati di avere la giusta impostazione della basale in AndroidAPS. Se non sei sicuro o non vuoi sovrascrivere le impostazioni della basale sul micro, premi Annulla e ricollega il micro in un altro momento.
+ Attenzione: se attivi e connetti un micro, AndroidAPS copierà le impostazioni della basale dal profilo al micro, sovrascrivendo la velocità basale esistente memorizzata sul micro. Assicurati di avere la giusta impostazione della basale in AndroidAPS. Se non sei sicuro o non vuoi sovrascrivere le impostazioni della basale sul micro, premi annulla e ripeti il processo in un altro momento.Dati trattamento incompleti
- Impostazioni Manutenzione
+ Impostazioni manutenzioneEmail
- Nessun log da inviare
+ Numero di log da inviareManutenzione
- MAINT
+ MANUTFornisce numerose funzioni per la manutenzione (ad es. invio log, eliminazione log).
- Inviare i log via Email
- Eliminare i log
- Un trattamento (insulina: %1$.2f, carboidrati: %2$d, a: %3$s) non può essere aggiunto ai trattamenti. Controllare e aggiungere il record necessario.
+ Invia log via Email
+ Elimina log
+ Un trattamento (insulina: %1$.2f, carboidrati: %2$d, a: %3$s) non può essere aggiunto ai trattamenti. Controlla e aggiungi il record necessario.eCarbs: %1$d g (%2$d h), ritardo: %3$d mNessun dato autosens disponibileImpostazioni Log
- Ripristinare impostazioni predefinite
- Malfunzionamento NSClient. Considerare il riavvio di NS e NSClient.
+ Ripristina valori predefiniti
+ Malfunzionamento NSClient. Considera il riavvio di NS e NSClient.ASVersione %1$s disponibile
- Differenza di fuso orario
+ OffsetModalità APS preferitaTotaleCalcConnessione
- Inviare agli sviluppatori i file log di oggi e di questo momento. Situazione inaspettata.
+ Invia agli sviluppatori i file log di oggi e di questo momento. Situazione inaspettata.Violazione bolo massimoErrore comandoErrore velocitàViolazione limite insulinaRichiesta minima di modifica [%]
- Il Loop Aperto mostrerà una nuova richiesta di modifica solo se la modifica è maggiore di questo valore in %. Il valore predefinito è 20%
+ Il loop aperto mostrerà una nuova richiesta di modifica solo se la modifica è maggiore di questo valore in %. Il valore predefinito è 20%Associa il micro con il tuo telefono!Ricerca dispositivi…
- Attendere…
+ Attendi…Associazione completataI codici mostrati su questo dispositivo e sul micro combaciano?Associazione Insight
@@ -1045,14 +1038,14 @@
ConfermaMutoAvviso microinfusore
- Registrare cambi posizione cannula
- Registrare cambi serbatoio
- Registrare cambi catetere
- Registrare cambi batteria
- Registrare cambi modalità di funzionamento
- Registrare avvisi
- Abilitare emulazione TBR
- Usare i bolli estesi invece dei TBR per aggirare il limite del 250%%
+ Registra cambi posizione cannula
+ Registra cambi serbatoio
+ Registra cambi catetere
+ Registra cambi batteria
+ Registra cambi modalità di funzionamento
+ Registra avvisi
+ Abilita emulazione TBR
+ Usa i bolli estesi invece dei TBR per aggirare il limite del 250%%Ritardo disconnessione [s]Numero serialeVersione software di rilascio
@@ -1061,31 +1054,31 @@
Versione MD tel processor softwareVersione Safety processor softwareVersione BT info page
- Indirizzo Bluetooth
+ Indirizzo bluetoothAppendice ID sistemaData di produzione
- Eliminare associazione
+ Elimina associazioneInformazioni associazione
- Avviare micro
- Stoppare micro
+ Avvia micro
+ Stoppa microModalità operativaStato
- TDD Boli
- TDD Basale
- TDD Totale
+ TDD da bolo
+ TDD da basale
+ TDD totaleRecuperoNon associatoUltima connessioneAvviatoStoppato%1$d%% per %2$d / %3$d min
- Bolo Esteso
- Bolo Multiwave
+ Bolo esteso
+ Bolo multiwave%1$.2f / %2$.2f U per %3$d min
- Abilitare notifica di fine TBR\n(impostazione micro)
- Disabilitare notifica di fine TBR\n(impostazione micro)
- Ricaricare
- Integrazione micro Accu-Chek Insight
+ Abilita notifica di fine TBR\n(impostazione micro)
+ Disabilita notifica di fine TBR\n(impostazione micro)
+ Ricarica
+ Integrazione microinfusore Accu-Chek InsightNon inseritoUltima conn: %1$d min faTBR: %1$d%% per %2$d / %3$d min
@@ -1097,7 +1090,7 @@
Durata massima recupero [s]Durata minima recupero [s]Durata recupero
- Timeout durante la comunicazione - riavviare il bluetooth
+ Timeout durante la comunicazione - riavvia il bluetoothDomSabVen
@@ -1106,16 +1099,16 @@
MarLunAutomation task definiti dall\'utente
- Inserire un nome task.
- Specificare almeno un trigger.
- Specificare almeno un\'azione.
+ Inserisci un nome task.
+ Specifica almeno un trigger.
+ Specifica almeno un\'azione.Già abilitatoGià disabilitatoGià sospeso
- Riprendere il Loop
+ Riprendi il loopNon sospeso
- Avviare temp-target
- Stoppare temp-target
+ Avvia temp-target
+ Stoppa temp-targetè inferiore aè uguale o inferiore aè uguale a
@@ -1132,9 +1125,9 @@
OrXorA %1$s
- Usare posizione di rete
- Usare posizione GPS
- Usare posizione passiva
+ Usa posizione di rete
+ Usa posizione GPS
+ Usa posizione passivaServizio di localizzazioneAutoAutomazione
@@ -1142,8 +1135,8 @@
U/hg/U/U
- Registrare cambio sensore in NS
- Creare evento \"Cambio Sensore\" in NS all\'avvio del sensore
+ Registra cambio sensore in NS
+ Crea evento \"Cambio Sensore\" in NS all\'avvio del sensoreTomato (MiaoMiao)Tomatosecondo
@@ -1165,16 +1158,16 @@
Usa server integrativi (test)TidepoolTDP
- Caricare dati in Tidepool
- Caricare dati CGM
- Caricare trattamenti (insulina, carboidrati)
- Caricare basali temporanee
- Caricare cambi profilo, target temporanei
- Caricare test Glicemia
+ Carica dati in Tidepool
+ Carica dati CGM
+ Carica trattamenti (insulina, carboidrati)
+ Carica basali temporanee
+ Carica cambi profilo, target temporanei
+ Carica test glicemiaCambio all\'ora legale in 24h o meno
- Cambio all\'ora legale avvenuto meno di 3 ore fa - Loop Chiuso disabilitato
+ Cambio all\'ora legale avvenuto meno di 3 ore fa - Loop chiuso disabilitatovincolo di archiviazione interna
- Liberare almeno %1$d MB dalla memoria interna! Loop disabilitato!
+ Libera almeno %1$d MB dalla memoria interna! Loop disabilitato!Formato erratoCodice errato. Comando annullato.Non configurato
@@ -1199,25 +1192,25 @@
Nuova versione disponibile da %1$d giorni! Ritorno a LGS trascorsi 60 giorni, disattivazione del loop dopo 90 giorni2h%1$.2fU
- Dexcom App (modificata)
+ Dexcom app (modificata)DXCM
- Ricevere valori Glicemia dall\'app Dexcom modificata.
+ Ricevi valori glicemia dall\'app Dexcom modificata.NotificaNotifica: %1$sMsg:Percentuale profiloPercentuale [%]:
- Avviare profilo %1$d%% per %2$d min
- Avviare profilo %1$d%%
+ Avvia profilo %1$d%% per %2$d min
+ Avvia profilo %1$d%%esistenon esiste
- Temp target %1$s
+ Temp-Target %1$sWiFi SSID %1$s %2$sAutosens %1$s %2$s %%Autosens %%3$s %1$s %2$s
- Differenza Glicemia
- Differenza Glicemia [%1$s]
+ Differenza glicemia
+ Differenza glicemia [%1$s]Posizione correntePosizioneLat:
@@ -1225,14 +1218,14 @@
Dist [m]:Nome:La posizione è %1$s
- Ultimo Bolo
+ Ultimo boloOra ultimo bolo %1$s %2$s min faCOBCOB %1$s %2$.0f
- Nome Task
+ Nome taskMODIFICA
- Scegliere un tipo di azione:
- Scegliere un tipo di trigger:
+ Scegli un tipo di azione:
+ Scegli un tipo di trigger:Trigger:RIMUOVIPresupposti:
@@ -1246,20 +1239,22 @@
Tipo microFrequenza microRitardo prima che il Bolo sia avviato (s)
- Max Bolo su Micro (U)
- Max Basale su Micro (U/h)
+ Max bolo su micro (U)
+ Max basale su micro (U/h)Codifica MedtronicUS & Canada (916 MHz)Globale (868 Mhz)Codifica Software 4b6bCodifica Hardware 4b6bRisveglio e Sintonizzazione
- Cancellare Blocco Bolo
+ Cancella blocco boloReset Configurazione RileyLink
- Tipo batteria (Power View)
+ Tipo batteria (Power view)Non selezionato (Simple view)Alcalina (Extended view)Litio (Extended view)
+ NiZn (Extended view)
+ Debug Bolo/TrattamentiSCANSTOP
@@ -1267,9 +1262,9 @@
Scansione RileyLinkBluetooth Low Energy non supportato.Bluetooth disabilitato.
- La Posizione è disabilitata
+ La posizione è disabilitataAffinché la ricerca bluetooth funzioni sui nuovi dispositivi, la localizzazione deve essere abilitata, ma può essere disabilitata dopo l\'associazione. AAPS non tiene traccia della tua posizione.
- Abilitare
+ AbilitaNoScansioneScansione terminata
@@ -1284,7 +1279,7 @@
Indirizzo configuratoDispositivo connessoStato connessione
- Errore Connessione
+ Errore connessioneDispositivoTipo dispositivoModello dispositivo
@@ -1292,7 +1287,7 @@
Ultimo contatto dispositivoRL Firmware
- Inizializzazione Bluetooth…
+ Inizializzazione bluetooth…Errore BluetoothBluetooth prontoNon avviato
@@ -1305,7 +1300,7 @@
Il dispositivo non è RileyLinkRileyLink non raggiungibileBluetooth disabilitato
- Nessun adattatore Bluetooth
+ Nessun adattatore bluetoothSintonizzazione fallitaMicro irraggiungibilePod irraggiungibile
@@ -1326,9 +1321,9 @@
I profili basali non sono abilitati nel microinfusore.Il profilo basale impostato nel micro non è corretto (deve essere STD).Tipo TBR errato impostato nel micro (deve essere Assoluto).
- Max Bolo errato impostato nel micro (deve essere %1$.2f).
- Max Basale errata impostata nel micro (deve essere %1$.2f).
- Operazione non possibile.\n\n Devi prima configurare il Micro Medtronic.
+ Max bolo errato impostato nel micro (deve essere %1$.2f).
+ Max basale errata impostata nel micro (deve essere %1$.2f).
+ Operazione non possibile.\n\n Devi prima configurare il micro Medtronic.È stata richiesta una modifica d\'orario di oltre 24h.Basali
@@ -1337,7 +1332,7 @@
StatisticheSconosciutiTutto
- Storico del Micro Medtronic
+ Storico del micro MedtronicMai connessoRisveglio
@@ -1348,66 +1343,55 @@
AttivoIn sospensione
- Hai cancellato il bolo, dopo che era già stato impostato sul Microinfusore. Dal momento che il micro Medtronic non supporta la cancellazione, avrai bisogno di cancellare il bolo manualmente. Metti il micro in modalità Sospensione e poi fallo Ripartire (se vuoi ancora cancellare il bolo). L\'applicazione rileverà le modifiche al prossimo aggiornamento (in meno di 5 minuti).
+ Hai cancellato il bolo, dopo che era già stato impostato sul microinfusore. Dal momento che il micro Medtronic non supporta la cancellazione, avrai bisogno di cancellare il bolo manualmente. Metti il micro in modalità sospensione e poi fallo ripartire (se vuoi ancora cancellare il bolo). L\'applicazione rileverà le modifiche al prossimo aggiornamento (in meno di 5 minuti).Impossibile leggere il TBR corrente.Impossibile cancellare il TBR corrente. Arresto dell\'operazione.
- Impostazione del profilo fallita, i seguenti modelli hanno un tasso basale troppo grande: %1$s
- Il Bolo non può essere erogato.
+ Impostazione del profilo fallita. A causa dei seguenti pattern, hai una velocità basale troppo grande: %1$s
+ Il bolo non può essere erogato.Il bolo non può essere erogato perché la quantità di insulina disponibile (%1$.2f) è inferiore al bolo richiesto (%2$.2f).Il TBR non può essere impostato.Impossibile cancellare il TBR corrente.Il profilo basale non può essere impostato.Il profilo basale è lo stesso, non sarà impostato di nuovo.
- Ottieni Storico - Pagina %1$d (%2$d/16)
- Ottieni Storico - Pagina %1$d
- Ottieni Orario Micro
- Ottieni Impostazioni
- Ottieni Modello Micro
- Ottieni Profilo Basale
- Imposta Profilo Basale
- Ottieni Basale Temporanea
- Imposta Basale Temporanea
- Imposta Bolo
+ Ottieni storico - Pagina %1$d (%2$d/16)
+ Ottieni storico - Pagina %1$d
+ Ottieni orario micro
+ Ottieni impostazioni
+ Ottieni modello micro
+ Ottieni profilo basale
+ Imposta profilo basale
+ Ottieni basale temporanea
+ Imposta basale temporanea
+ Imposta bolo
+ Cambia profilo in
+ Cambia profilo in %1$s
+ Ultima connessione al micro
+ Ultima connessione al micro [minuti fa]
+ Ultima connessione al micro %1$s %2$s min fa
+ Invia SMS: %1$s
+ Invia SMS a tutti i numeri nelle preferenze
+ Invia SMS con testo%2$+.2fU]]>Vincolo Bolo applicato: %2$.2fU a %3$.2fU]]>!!!!! Rilevato assorbimento lento dei carboidrati: %2$d%% del tempo. Ricontrolla il tuo calcolo. COB potrebbero essere sovrastimati e potrebbe essere somministrata più insulina !!!!!]]>%1$.0f / %2$d U
- Erogare questa parte del risultato del bolus wizard [%]
- Bolus wizard esegue il calcolo, ma solo questa parte dell\'insulina calcolata è erogata. Utile con algoritmo SMB.
+ Eroga parte del risultato del calcolatore [%]
+ Il calcolatore esegue il calcolo, ma solo questa parte dell\'insulina calcolata è erogata. Utile con algoritmo SMB.Caricamento ...
- Snooze
- Compiuto: %1$s
- Imparare a controllare AndroidAPS
- Eseguire varie azioni in AndroidAPS
- Impostare il profilo \"90%\" per 10 min (premere a lungo sul nome profilo nella sezione Panoramica)
- Simulare la doccia. Disconnettere il micro per 1h (premere a lungo su Loop Aperto)
- ... e riconnettere allo stesso modo
- Creare un temp-target personalizzato con una durata di 10 min (premere a lungo sul tuo target corrente)
- Nel Configuratore attivare il plugin Azioni, renderlo visibile e visualizzarne i contenuti tramite il menu in alto
- Visualizzare il contenuto del plugin Loop
- Usare la funzione di ridimensionamento premendo a lungo sul grafico delle glicemie
- Entrare
- Inserire il codice ottenuto dagli sviluppatori per aggirare il resto degli obiettivi
- Codice accettato
- Codice non valido
- Dare prova della tua conoscenza
- Studiare e rispondere correttamente alle domande
- Risposta disabilitata per: %1$s
- Risposta sbagliata!
- Prossimo non completato
+ Posticipa
+ Intervallo di tempo
+ Il tempo è compreso tra %1$s e %2$s
+ Tra Chiudi
- Codice richiesta: %1$s
- (segnare tutte le risposte corrette)
-
- %1$d giorno
- %1$d giorni
-
-
- %1$d ora
- %1$d ore
-
-
- %1$d minuto
- %1$d minuti
-
+ Aumento del valore max basale perché l\'impostazione è inferiore alla tua basale massima nel profilo
+ Corpo del messaggio non valido
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Calcolatore
+ min
+ %1$dg
+ On
+ Off
diff --git a/app/src/main/res/values-iw-rIL/objectives.xml b/app/src/main/res/values-iw-rIL/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-iw-rIL/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-iw-rIL/strings.xml b/app/src/main/res/values-iw-rIL/strings.xml
index d01b8a31e5..d4508abe7a 100644
--- a/app/src/main/res/values-iw-rIL/strings.xml
+++ b/app/src/main/res/values-iw-rIL/strings.xml
@@ -5,7 +5,6 @@
-
רענן טיפול מ-Nightscoutבבקשה אתחל את הסמרטפון שלך או תרענן את אפלקצית AndroidAPS בהגדרות המערכת
אחרת AndroidAPS לא יוכל לבצע רישום (חשוב לעקוב אחר ולוודא כי האלגוריתמים פועלים כראוי)!
diff --git a/app/src/main/res/values-ja-rJP/objectives.xml b/app/src/main/res/values-ja-rJP/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-ja-rJP/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-ja-rJP/strings.xml b/app/src/main/res/values-ja-rJP/strings.xml
index 7879323748..df88c88e20 100644
--- a/app/src/main/res/values-ja-rJP/strings.xml
+++ b/app/src/main/res/values-ja-rJP/strings.xml
@@ -5,7 +5,6 @@
-
diff --git a/app/src/main/res/values-ko-rKR/objectives.xml b/app/src/main/res/values-ko-rKR/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-ko-rKR/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-ko-rKR/strings.xml b/app/src/main/res/values-ko-rKR/strings.xml
index a0b91c3eee..b88368882e 100644
--- a/app/src/main/res/values-ko-rKR/strings.xml
+++ b/app/src/main/res/values-ko-rKR/strings.xml
@@ -5,7 +5,6 @@
-
관리 안전설정최대 허용 Bolus [U]최대 허용 탄수화물 [g]
@@ -57,9 +56,6 @@
WearOS 워치를 이용하여 AndroidAPS를 모니터하고 제어합니다.xDrip+ 워치페이스에서 Loop정보 보여주기SMS 전송을 이용하여 AndroidAPS를 원격 제어합니다.
- 뒤로
- 시작
- 확인단위인슐린활동시간(DIA):인슐린 대 탄수화물 비율(IC):
@@ -177,9 +173,6 @@
지원하지 않는 NSClient 버전입니다지원하지 않는 Nightscout 버전입니다NSClient 가 설치되지 않았습니다. 기록이 삭제됩니다!
- NS에서 혈당데이터가 확인 가능합니다.
- NS에서 펌프상태가 확인 가능합니다.
- 수동 주입제한으로 인해 LOOP가 사용불가합니다.Basal IOBBolus 제한이 적용되었습니다
@@ -222,7 +215,6 @@
임시Basal확장 BolusNightscout 버전:
- 누락설정이 저장되었습니다다음 위치에 설정을 저장하시겠습니까다음 위치에서 설정을 불러오시겠습니까
@@ -317,8 +309,6 @@
정지 누름펌프를 기다리는 중%1$.2fU을 주입합니다
- 표시설정과 모니터설정을 완료하고, Basal과 비율을 분석한다.
- 나이트스카우트에서 혈당 데이터가 잘 들어오는지, 펌프데이터가 업로드 되는지 확인한다.허용된 제한값에 도달하였습니다프로파일이 선택되지 않았습니다Loop가 중지되었습니다.
@@ -554,8 +544,6 @@
홈화면에 상태 표시등 보여주기주사기량 경고 기준값[U]주사기량 위험 기준값[U]
- 배터리량 경고 기준값[%%]
- 배터리량 위험 기준값[%%]IOBCOB펌웨어
@@ -848,8 +836,6 @@
프로파일변경 누락. 로컬 프로파일에서 프로파일 변경을 하거나 \"프로파일 활성화하기\"를 누르세요.Bolus 수임시기초주입 수
- 목표%1$d이 시작되지 않았습니다.
- 목표%1$d이 완료되지 않았습니다.이 펌프 임시Basal을 지원하지 않습니다.펌프에서 유효한 Basal양을 읽을 수 없습니다.설정에서 Closed Loop 모드가 비활성화되었습니다.
@@ -971,7 +957,6 @@
훌륭합니다. 완료되었습니다!아직 완료되지 않았습니다.경과 시간
- %1$d. 목표PoctechPoctech 앱에서 혈당값 받기혈당값이 Tomato앱(MiaoMaio장치) 으로부터 수신되었습니다.
@@ -1155,8 +1140,6 @@
임시 Basal 업로드프로파일변경, 임시목표 업로드혈당 테스트 업로드
- 24시간 이내 썸머타임 변경
- 썸머타임 변경이 3시간 미만입니다 - Closed Loop 비활성됨내부 저장 용량 제한내부 저장 공간을 최소 %1$d MB 이상 비우세요! Loop가 비활성화되었습니다!잘못된 형식
@@ -1358,13 +1341,4 @@
Bolus 마법사는 계산을 수행하지만 계산된 인슐린의 이 부분만 주입됩니다. SMB 알고리즘에 유용합니다.불러오는 중…스누즈
-
- %1$d 일
-
-
- %1$d 시간
-
-
- %1$d 분
-
diff --git a/app/src/main/res/values-lt-rLT/exam.xml b/app/src/main/res/values-lt-rLT/exam.xml
index 70489fbc5e..634982d1fc 100644
--- a/app/src/main/res/values-lt-rLT/exam.xml
+++ b/app/src/main/res/values-lt-rLT/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Koks atsakymas apie IVT yra teisingas?
+ Tema: Insulino veikimo trukmė
+ Mažiausia reikšmė - 3 valandos.
+ Mažiausia reikšmė - 5 valandos.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ Jis yra lygus IVT parametrui, kuris naudojamas pompoje.
+ Jūs turite nustatyti jūsų individualias vertes (bet ne mažiau kaip 5 valandas).
+ Tema: Hipo Laikinas tikslas
+ Kokia yra pagrindinė priežastis nustatyti hipo laikiną tikslą?
+ Užkirsti kelią kristi gliukozės kiekiui kraujyje, kai jau veikia nulinė laikina bazė.
+ Apriboti AAPS, kad nebūtų suleista per daug insulino po glikemijos kilimo, kurį sukelia greiti angliavandeniai, suvartoti hipoglikemijai suvaldyti.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Kuris profilis gali būti naudojamas ir sukonfigūruotas neprisijungus?
+ Tema: Vietinis Profilis
+ NS Profilis gali būti naudojamas, bet nekonfigūruojamas.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Tema: Atsijungimas nuo Pompos
+ Ką reikėtų daryti, kai atjungiama pompa?
+ Spustelėkite Atjungti pompą, kad AAPS žinotų, kad insulinas nėra leidžiamas.
+ Paspauskite Sustabdyti ciklą, kad AAPS sustabdytų ciklą, kai pompa yra atjungta.
+ Nieko nekeiskite AAPS, tiesiog atjunkite pompą.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Tema: AndroidAPS nustatymai
+ Kokie geriausi veiksmai išsaugant nustatymų atsarginę kopiją?
+ Eksportavimas į vidinę atmintį per Serviso meniu.
+ Išsaugokite eksportuotą failą tokiose vietose kaip el. paštas, Dropbox, Google drive…
+ Eksportuokite juos iš karto po AAPS instaliavimo.
+ Atlikę nustatymų pakeitimus, juos eksportuokite.
+ Eksportuokite juos įvykdę tikslą.
+ Eksportuokite juos, kai atliksite pradinius nustatymus.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Tema: Triukšmingi NGJ Rodmenys
+ Ką reikėtų daryti, jei sensoriaus duomenys yra triukšmingi - besiblaškantys?
+ Nieko, Ciklas pats susitvarkys.
+ Išjungti ciklą, kad išvengtumėte insulino perdozavimo.
+ Pakeisti NGJ sensorių.
+ Išjungti telefoną.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Įsitikinkite, kad sensoriaus programėlė išlygina KG duomenis.
+ Tema: Mankšta
+ Kaip padėti sistemai susidoroti su fizine veikla?
+ Laikino tikslo funkcijos naudojimas.
+ Perjungti profilį į žemesnį nei 100%.
+ Perjungti profilį į aukštesnį nei 100%.
+ Sustabdyti ciklą.
+ Nustatyti aktyvumo laikiną tikslą prieš fizinį aktyvumą.
+ Laikinojo tikslo nustatymas po veiklos pradžios duoda prastesnius rezultatus, nei tuo atveju, jei jis buvo nustatytas iš anksto.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Tema: Ciklas išjungtas/sustabdytas
+ Ar man leidžiamas insulinas, kai ciklas yra išjungtas / pristabdytas?
+ Taip, bazinis insulinas ir toliau leidžiamas.
+ Ne, insulino tiekimas sustabdytas.
+ Tema: Bazės, JIF, ir IA testavimas
+ Kada turėčiau patvirtinti bazės, JIF ir IA reikšmes?
+ Prieš pradedant naudoti AAPS.
+ Kai dažnai kartojasi hipoglikemija.
+ Kai dažnai kartojasi hiperglikemija.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Tema: Būtinos sąlygos
+ Ko man reikia?
+ Patikrinti profilio duomenis (valandines bazes, IA, JIF, IVT).
+ Kompiuterio APK sukūrimui.
+ Tinkamo telefono.
+ Automobilio.
+ Nightscout, tikslų įveikimui.
+ Tidepool paskyros.
+ Google paskyros.
+ Github paskyros.
+ Android kūrimo patirties.
+ MiniMed 670G pompos.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Išmaniojo laikrodžio.
+ Palaikomo NGJ.
+ Tema: AndroidAPS atnaujinimas
+ Kuris teiginys teisingas?
+ Jums reikia turėti įdiegtą Git.
+ Atnaujinkite, kai tik bus išleista nauja versija ir tam turėsite pakankamai laiko.
+ Turite naudoti tuos pačius parašo raktus.
+ Niekada neatnaujinkite, jei sistema veikia gerai.
+ Paprašykite savo draugo naujo APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Tema: Gedimų Šalinimas
+ Kur ieškoti pagalbos?
+ Prisijungti prie AndroidAPS Facebook grupėje.
+ Skaityti AndroidAPS dokumentaciją.
+ Apsilankyti AndroidAPS Gitter kanale.
+ Apsilankyti AndroidAPS Google palaikymo tarnyboje
+ Pasitarti su savo endokrinologu.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Tema: Insulino įskiepiai
+ Kokio tipo insuliną galiu naudoti su Ultra-Rapid-Oref moduliu?
+ Fiasp®
+ NovoRapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Tema: Jautrumo įskiepiai
+ Kuris jautrumo algoritmas turi reguliuojamą laiko intervalą?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Koks jautrumo įskiepis turi būti naudojamas su NDM?
+ Tema: Angliavandenių įvedimo klaidos
+ Ką reikia daryti, jei įrašyti neteisingi angliavandeniai?
+ Skirtuke Terapija ištrinti neteisingus angliavandenių įrašus. Įvesti naujus angliavandenius.
+ Pridėti netikrą insulino dozę naudojantis Užpildymo funkcija
+ Tema: Maistas su riebalais ir baltymais
+ Ką darysite, jei maiste yra daug riebalų ar baltymų?
+ Perskaičiuosite riebalus ir baltymus į angliavandenius ir naudokitės \"Ištęstų angliavandenių\" funkcija.
+ Perskaičiuosite riebalus ir baltymus į angliavandenius ir įvesite į boluso skaičiuoklę.
+ Naudosite ištęsto boluso funkciją padengti riebalus ir baltymus.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Tema: Nuotolinis Stebėjimas
+ Kaip galite stebėti vaiko AAPS nuotoliniu būdu?
+ Naudojantis Nightscout svetaine.
+ Dexcom Follow, jei naudojate originalią Dexcom programėlę (tik glikemijos duomenys).
+ Dexcom Follow, jei naudojate xDrip.
+ xDrip sekėjo režimu.
+ Loop app iPhone telefone.
+ Spike iPhone telefone.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Tema: Jautrumo Insulinui Faktorius
+ Didesnis IVT lemia mažesnį insulino tiekimą, kai AAPS koreguoja aukštą glikemiją.
+ Mažesnis IVT lemia mažesnį insulino tiekimą, kai AAPS koreguoja aukštą glikemiją.
+ IVT reikšmės pakeitimas neturi įtakos AAPS leidžiamo insulino kiekiui koreguojant aukštą glikemiją.
+ Nustatymuose turite įvesti JIF.
+ Jei profilyje pakeisite JIF vertę, Ciklas į pokytį iškart atsižvelgs.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Tema: IA santykis
+ Didesnis insulino ir angliavandenių IA santykis reiškia, kad mažiau insulino reikia padengti tam tikram angliavandenių kiekiui.
+ Mažesnis insulino ir angliavandenių IA santykis reiškia, kad mažiau insulino reikia padengti tam tikram angliavandenių kiekiui.
+ Jei turite 0 AAO (aktyvių angliavandenių organizme), pakeitus IA, glikemija bus koreguojama kitokiu insulino kiekiu.
+ IA vertė skirsis priklausomai nuo to, ar duonos vienetui skaičiuojate 10g, ar 12g angliavandenių.
+ IA reiškia: kiek vienas vienetas insulino dengia angliavandenių (gramais).
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Tema: Profilio keitimas
+ Kai profilio keitime nustatote 90%…
+ Bazė bus 10% aukštesnė.
+ Bazė bus 10% žemesnė.
+ IA reikšmė bus 10% didesnė.
+ IA reikšmė bus 10% mažesnė.
+ JIF reikšmė bus 10% didesnė.
+ JIF reikšmė bus 10% mažesnė.
+ Jums bus viso suleista 10% mažiau insulino.
+ Tikslas bus 10% aukštesnis.
+ Tikslas bus 10% žemesnis.
+ Tik apatinis tikslas bus 10% žemesnis.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Jei atsibundate 1 valanda anksčiau nei įprastai, kaip turėtumėte pranešti AAPS apie savo tvarkaraščio pasikeitimą?
+ Perjunkite profilį su laiko poslinkiu +1
+ Perjunkite profilį su laiko poslinkiu -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Perjunkite profilį su laiko poslinkiu +60
+ Perjunkite profilį su laiko poslinkiu -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Tema: Pagalba su valandinėmis bazėmis
+ Kur kreiptis, jei jums reikia pagalbos nustatant valandines bazes ir pan.?
+ Į Jūsų endokrinologą ir diabetologą
+ Google
+ Facebook
+ Kiti vaistai
+ AAPS sumažina valandinę bazę, siekiant padidinti glikemiją. Dėl vaistų iš SGLT2 inhibitorių grupės (Gliflozinas) naudojimo, numatomas glikemijos padidėjimas gali būti neteisingai parodytas ir tokiu būdu gali sukelti pavojingą insulino trūkumą (DKA - ketoacidozę).
+ \n Prekių ženklų pavadinimai apima: „Invokana®“, „Forxiga®“, „Jardiance®“, „Steglatro®“, „Suglat®“, „Apleway®“, „Deberza®“, „Synjardy®“, „Vokanamet®“, „Xigduo®“. \n\n Pažadu nenaudoti tokių vaistų, naudojant AAPS, arba prieš vartodamas juos, atjungsiu ciklą.
+
diff --git a/app/src/main/res/values-lt-rLT/objectives.xml b/app/src/main/res/values-lt-rLT/objectives.xml
new file mode 100644
index 0000000000..95034771a6
--- /dev/null
+++ b/app/src/main/res/values-lt-rLT/objectives.xml
@@ -0,0 +1,73 @@
+
+
+
+ Atgal
+ Pradėti
+ Patikrinti
+ %1$d. tikslas
+ %1$d tikslas nepradėtas
+ %1$d tikslas nepasiektas
+ Nustatymai vizualizacijai, monitoringui ir bazės verčių bei koeficientų analizei
+ Įsitikinkite, kad gliukozės duomenys rodomi Nightscout, o pompos insulino duomenys yra įkelti
+ Aktyvuojamas atviras ciklas
+ Keletą dienų praleiskite atvirojo ciklo (Open Loop) režime, rankiniu būdu tvirtindami kuo daugiau siūlomų bazės pakeitimų. Nustatykite ir naudokite laikinus bei numatytuosiuos tikslus (pvz.: fiziniam aktyvumui ir hipo korekcijai angliavandeniais)
+ Perpraskite atvirojo ciklo veikimą bei laikinos bazės rekomendacijas
+ Remdamiesi šia patirtimi, nuspręskite, koks turėtų būti maksimalus bazės dydis bei įveskite jį pompoje ir programos Nustatymuose
+ Pradėkite uždaro ciklo (Closed Loop) režimą su pompos stabdymu esant žemai gliukozei
+ Keletą dienų praleiskite uždaro ciklo režime su kuo mažiau hipoglikemijų, kai AIO = 0
+ Koreguokite savo uždarąjį ciklą po truputį didindami maks AIO ir mažindami tikslinę glikemijos reikšmę
+ Praleiskite keletą dienų ir bent vieną naktį be hipoglikemijos aliarmų
+ Jei reikia, paderinkite valandines bazės vertes bei pagrindinius parametrus ir įgalinkite Autosens funkciją
+ 1 savaitę praleiskite sėkmingai naudodami uždarąjį ciklą dienos metu ir įvesdami visus valgomus angliavandenius
+ Dienos metu aktyvuokite papildomas funkcijas, tokias kaip pažangioji maisto skaičiuoklė (AMA Advanced Meal Assist)
+ Dienos metu aktyvuokite papildomas funkcijas, tokias kaip SMB (Super Mikro Bolusas)
+ Norėdami, kad SMB veiktų gerai, turite perskaityti dokumentaciją ir padidinti max AIO! Pradžiai patartina skaičiuoti taip: maxAIO=(didžiausia valandinė bazė x 3) + vidutinis bolusas
+ KG matoma NS
+ NS matomas pompos statusas
+ Įvesti rankiniu būdu
+ Įvykdyta: %1$s
+ Išmokite kaip valdyti AndroidAPS
+ Atlikite įvairius veiksmus AndroidAPS
+ Nustatykite profilį 90% 10 min (ilgai paspauskite profilio pavadinimą Apžvalgos skiltyje)
+ Imituokite maudynes duše. Atjunkite pompą 1 valandai (ilgai paspauskite Atviras Ciklas)
+ ... ir iš naujo prisijunkite tuo pačiu būdu
+ Nustatykite 10 min trukmės laikiną tikslą (ilgai spausti ant dabartinio tikslo)
+ Konfigūracijoje įjunkite Veiksmų įskiepį, nustatykite jį matomą ir jo turinio rodymą viršutiniame meniu
+ Parodyti Ciklo įskiepio turinį
+ Panaudokite vaizdo dydžio keitimo funkciją ilgai spaudžiant ant glikemijos kreivės
+ Įeiti
+ Kodas priimtas
+ Neteisingas kodas
+ Patvirtinkite savo žinias
+ Išnagrinėkite ir atsakykite į klausimus teisingai
+ Atsakymas sustabdytas: %1$s
+ Neteisingas atsakymas!
+ Kitas neužbaigtas
+ Paprašyti kodo: %1$s
+ (pasirinkite visus teisingus atsakymus)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Neprisijungta prie interneto
+ Nepavyko nuskaityti laiko
+ Tikslo reikalavimai neįvykdyti
+
+ %1$d diena
+ %1$d dienos(-ų)
+ %1$d dienos(-ų)
+ %1$d dienos(-ų)
+
+
+ %1$d valanda
+ %1$d valandos(-ų)
+ %1$d valandos(-ų)
+ %1$d valandos(-ų)
+
+
+ %1$d minutė
+ %1$d minutės(-čių)
+ %1$d minutės(-čių)
+ %1$d minutės(-čių)
+
+
diff --git a/app/src/main/res/values-lt-rLT/strings.xml b/app/src/main/res/values-lt-rLT/strings.xml
index 982c8841f8..0d52246cec 100644
--- a/app/src/main/res/values-lt-rLT/strings.xml
+++ b/app/src/main/res/values-lt-rLT/strings.xml
@@ -5,7 +5,6 @@
-
Terapijos saugumasMaksimalus leistinas bolusas [U]Maks. leistini angliavandeniai [g]
@@ -57,9 +56,6 @@
Stebėti ir kontroliuoti AndroidAPS naudojant WearOS laikrodį.Rodyti Ciklo informaciją laikrodyje, xDrip+ pradžios ekrane.Nuotolinis AndroidAPS valdymas naudojant SMS komandas.
- Atgal
- Pradėti
- PatikrintiVienetaiIVT (Insulino Veikimo Trukmė)IA (insulino/angliavandenių santykis)
@@ -68,7 +64,7 @@
TikslasNenustatytas profilisInsulinas:
- Angliavandeniai:
+ AV:AIO:AIO:Visas AIO:
@@ -79,10 +75,10 @@
AIO:Visas AIO:Insulinas
- Angliavandeniai
+ AVKGLT
- Angliavandeniai
+ AVKorekcijavvBolusų AIO
@@ -102,6 +98,7 @@
ProfilisMaisto duomenysRezultatas
+ Rezultatas: %1$s %2$sNėra gliukozės duomenųPakeitimai nereikalingiUžklausa
@@ -161,7 +158,7 @@
Bolusas:Valandinė bazėValandinė bazė:
- Angliavandeniai
+ AVPakeiskite įvestus duomenis!Nustatyti naują ištęstą bolusą:KG šaltinis
@@ -177,9 +174,6 @@
Nepalaikoma NSClient versijaNepalaikoma Nightscout versijaNeįdiegtas NSClient. Įrašai prarasti!
- KG matoma NS
- Pompos statusas matomas NS
- Įvesti rankiniu būduCIKLAS NEAKTYVUS DĖL APRIBOJIMŲBazės AIOPritaikytas boluso apribojimas
@@ -208,7 +202,7 @@
SensoriusAngliavandeniaiInsulinas
- Angliavandenių laikas
+ AV laikasIšskaidytiTrukmėProcentai
@@ -222,7 +216,7 @@
Laikina bazėIštęstas bolusasNightscout versija:
- Trūksta
+ Trūksta %1$dgNustatymai eksportuotiEksportuoti nustatymusImportuoti nustatymus iš
@@ -317,8 +311,6 @@
Paspausta STOPLaukiama ryšio su pompaBus suleista %1$.2fvv
- Nustatymai vizualizacijai, monitoringui ir bazės verčių bei koeficientų analizei
- Įsitikinkite, kad gliukozės duomenys rodomi Nightscout, o pompos insulino duomenys yra įkeltiPasiekėte leistiną ribąNepasirinktas profilisCiklas buvo išjungtas
@@ -349,7 +341,7 @@
Greitasis patarėjasGreitojo patarėjo nustatymaiMygtuko tekstas:
- Angliavandeniai:
+ AV:Galioja:PridėtiRedaguoti
@@ -521,10 +513,12 @@
Ciklas sustabdytasSustabdyta (%1$d m)Superbolusas (%1$d m)
+ Sustabdyti cikląSustabdyti ciklą 1 valSustabdyti ciklą 2 valSustabdyti ciklą 3 valSustabdyti ciklą 10 val
+ Sustabdyti ciklą %1$d minAtjungti pompą 15 minAtjungti pompą 30 minAtjungti pompą 1 val
@@ -550,10 +544,12 @@
Įgalinti superbolusus skaičiuoklėjeĮgalina superbolusų naudojimą insulino skaičiuoklėje. Nenaudokite, kol nesuprantate, ką superbolus funkcija atlieka. NAUDODAMI AKLAI GALITE PERDOZUOTI INSULINO!Pradžios ekrane rodyti spalvotus indikatorius
+ Pradžios ekrane rodyti papildomus šviesos indikatorius
+ Pradžios ekrane rodyti papildomus šviesos indikatorius adatos, insulino, sensoriaus naudojimo trukmei bei baterijos įkrovimo lygiui.Įspėjimo apie žemą rezervuaro lygį riba [U]Įspėjimo apie kritiškai žemą rezervuaro lygį riba [U]
- Įspėjimo apie žemą baterijos įkrovimo lygį riba [%%]
- Įspėjimo apie kritiškai žemą baterijos įkrovimo lygį riba [%%]
+ Įspėjimo apie žemą baterijos įkrovimo lygį riba [%]
+ Įspėjimo apie kritiškai žemą baterijos įkrovimo lygį riba [%]AIOAAOPrograminė įranga
@@ -623,6 +619,7 @@
AtšauktiNe visi profiliai įkelti!Reikšmės neišsaugotos!
+ Įgalinti perdavimą į kitas programas (pvz., „XDrip“). Neįgalinkite, jei įdiegta daugiau nei vienas AAPS arba NSClient egzempliorius!Įgalinti lokalų duomenų perdavimą.AKTYVUMAS & ATGALINIS RYŠYSANGLIAVANDENIAI & BOLUSAS
@@ -776,6 +773,7 @@
Ištęstinio boluso suleidimo klaidaSightprieš
+ %1$.2f hLeisti SMB visadaLeisti SMB visada, nepriklausomai nuo bolusų. Įmanoma tik naudojant patikimų, filtruotų KG duomenų šaltinį, pvz.: Dexcom G5Leisti SMB po angliavandenių įvedimo
@@ -789,7 +787,7 @@
Paleisti laikinąją bazęNutildytiInsulinas
- Angliavandeniai
+ AVMygtukaiSiunčia kalibravimą į xDrip+ arba atidaro G5 kalibravimo dialogąAtidaro xDrip+, o mygtukas ATGAL gražina į AAPS
@@ -808,6 +806,7 @@
Duomenų perdavimas kūrėjamsLeisti automatinį pranešimų apie programos trikdžius ir funkcijų naudojimo duomenų siuntimą kūrėjams, naudojant fabric.io servisą.Atnaujinkite savo Dexcom programėlės versiją
+ Dexcom app neįdiegta.Pradėti Aktyvumo LTPradėti Netrukus valgysiu LTLT
@@ -817,6 +816,7 @@
Bolusas bus tik įrašytasAutomatiškai atstatyti trūkstamus KG duomenis iš NSSMB nustatyta iš pompos
+ AktyvumasJautrumas insulinuiNuokrypiaiAktyvūs angliavandeniai
@@ -827,6 +827,7 @@
Naudojama neužbaigta versija. Uždaras ciklas neaktyvus.Inžinerinis režimas įjungtasInžinerinis režimas negalimas vartotojo atšakoje
+ %1$.2f vv/valNuskaitomas bazės profilisSkaičiuojant bolusą pasikeitė pompos istorija. Bolusas nesuleistas. Prašome perskaičiuoti, jei boluso vis dar reikia.Bolusas sėkmingai suleistas, tačiau įrašas žurnale neįvestas. Taip gali nutikti, jei du vienodi nedideli bolusai suleisti per pastarąsias 2 min. Patikrinkite pompos istoriją ir įrašų žurnalą bei naudodamiesi Careportal įveskite trūkstamus įrašus. Patikrinkite, ar įvedamas įrašas neturi tokios pat laiko žymos ir insulino kiekio, kaip jau egzistuojantis.
@@ -842,8 +843,6 @@
Neatliktas profilio keitimas. Prašome atlikti profilio keitimą arba paspausti \"Aktyvuoti profilį\" Vietinio profilio (VP) skiltyje.Bolusų skaičiusLBD skaičius
- %1$d tikslas nepradėtas
- %1$d tikslas nepasiektasPompa negali nustatyti laikinos bazėsJokio tinkamo bazės kiekio nenuskaityta iš pomposUždaro ciklo būsena išjungta nustatymuose
@@ -930,6 +929,7 @@
Konfigūruoti Jautrumo nustatymo įskiepįJautrumo įskiepis yra naudojamas jautrumo aptikimui ir AAO skaičiavimams. Daugiau informacijos:https://github.com/MilosKozak/AndroidAPS/wiki/Sensitivity-detection-and-COB
+ NSClient palaiko ryšį su Nightscout. Jūs galite praleisti šią dalį dabar, bet negalėsite baigti mokymosi programos, kol nenustatysite ryšio su NS.Atminkite: DKS profiliams reikia IVT bent 5 val. IVT = 5 - 6 val DKS profilyje atitinka IVT = 3 val sename (pompos terapijos) insulino profilyje.Sukonfigūruoti KG šaltinįPrašome pasirinkti profilį. Jei pacientas yra vaikas, turite naudoti NS profilį. Jei niekas neseka jūsų Nightscout platformoje, tada geriau pasirinkti Vietinį profilį. Atminkite, kad čia Jūs tik pasirenkate profilio šaltinį. Norėdami jį aktyvuoti, turite atlikti Profilio keitimą
@@ -964,7 +964,6 @@
Užbaigta, puiku!Dar nebaigtaPraėjo laiko
- %1$d. tikslas PoctechGauti KG vertes iš Poctech programėlėsGauti KG vertes iš Tomato programėlės (MiaoMiao)
@@ -989,7 +988,7 @@
Siųsti įrašus el. paštuIštrinti įrašusĮrašas (insulinas: %1$.2f, angl.: %2$d, ties: %3$s) negali būti pridėtas. Prašome patikrinti ir rankiniu būdu atitinkamai įtraukti įrašą.
- eAngl.: %1$d g (%2$d h), atidėjimas: %3$d m
+ iAV.: %1$d g (%2$d h), atidėjimas: %3$d mNėra autosens duomenųĮrašų nustatymaiAtkurti numatytuosius
@@ -1075,7 +1074,48 @@
Min. atkūrimo trukmė [s]Atkūrimo trukmėRyšio užmezgimui skirtas laikas baigėsi - iš naujo nustatykite bluetooth
+ Sek
+ Šeš
+ Pen
+ Ket
+ Tre
+ An
+ Pir
+ Vartotojo nustatytos automatizavimo užduotys
+ Įveskite užduoties pavadinimą.
+ Nurodykite mažiausiai vieną sąlygą.
+ Nurodykite mažiausiai vieną veiksmą.
+ Jau įjungta
+ Jau išjungta
+ Jau sustabdyta
+ Atnaujinti ciklą
+ Nesustabdyta
+ Nustatykite laikiną tikslą
+ Sustabdykite laikiną tikslą
+ mažesnis nei
+ lygus arba mažesnis nei
+ yra lygus
+ yra lygus arba didesnis nei
+ didesnis nei
+ negalimas
+ nežinoma
+ Glikemija nepasiekiama
+ Glikemija %1$s %2$.0f %3$s
+ Glikemija %1$s %2$.1f %3$s
+ Profilis %1$s%2$d
+ AIO %1$s %2$.1f
+ Ir
+ Arba
+ Išskyrus arba
+ %1$s
+ Naudoti tinklo vietovę
+ Naudoti GPS vietovę
+ Naudoti pasyviąją vietovę
+ Vietovės paslaugos
+ Auto
+ Automatiškai== ∑ %1$s vv
+ Vv/valg/vv/vvRegistruoti sensoriaus keitimą NS
@@ -1085,55 +1125,250 @@
sekundėminutėvalanda
+ diena
+ savaitėsekundėsminutėsvalandos
+ dienų
+ savaičiųJūsų Tidepool vartotojo vardas, įprastai jūsų el. pašto adresasVartotojo vardas
- Laiko persukimas įvyks po 24 val ar mažiau
- Laikas persuktas prieš mažiau nei 3 val - Uždaras ciklas deaktyvuotas
+ Jūsų Tidepool prisijungimo slaptažodis
+ Prisijungimo slaptažodis
+ Patikrinti Tidepool prisijungimą
+ Jei įjungta, duomenys bus perduoti https://int-app.tidepool.org, vietoje https://app.tidepool.org/
+ Naudoti integracijos (test) serverius
+ Tidepool
+ TDP
+ Perduoda duomenis į Tidepool
+ Perduoti NGJ duomenis
+ Įkelti terapijas (insulinas, angliavandeniai)
+ Perkelti laikiną bazę
+ Perduoti profilio pokyčius, laikinas bazes
+ Perduoti KG testusvidinės saugyklos apribojimasAtlaisvinkite ne mažiau kaip %1$d MB iš vidinės atminties! Ciklas išjungtas!Neteisingas formatasNeteisingas kodas. Komanda atšaukta.NesukonfigūruotaProfilio perjungimas sukurtas
+ Pasikartojantis laikas
+ Kiekvienas
+ Niekada
+ %1$dmins
+ Sąlyga:
+ Veiksmas:
+ AIO [U]:
+ Gliukozė [%1$s]:
+ IŠTRINTI
+ PRIDĖTI
+ KOPIJUOTI
+ Pridėti naująVersijos tikrintuvas
+ Parašo tikrinimas
+ Nustatyta, kad naudojate neteisingą versiją. Ciklas išjungtas!sena versijalabai sena versijaNauja versija pasiekiama mažiausiai %1$d dienų! Po 60 d. grįšite prie stabdymo prie žemo, po 90 d. ciklas bus išjungtas.
+ 2 val
+ %1$.2fV
+ Dexcom programėlė (modifikuota)
+ DXCM
+ Gauti kraujo gliukozės reikšmes iš modifikuotos Dexcom programėlės.
+ Pranešimas
+ Įspėjimas: %1$s
+ Pranešimas:
+ Profilio procentas
+ Procentais [%]:
+ Pradėti profilį %1$d%% %2$d min
+ Pradėti profilį %1$d%%
+ egzistuoja
+ neegzistuoja
+ Laikinas tikslas %1$s
+ WiFi SSID %1$s %2$s
+ Autosens %1$s %2$s %%
+ Autosens %
+ %3$s %1$s %2$s
+ KG skirtumas
+ KG skirtumas [%1$s]
+ Dabartinė vieta
+ Vieta
+ Platuma:
+ Ilguma:
+ Atstumas [m]:
+ Vardas:
+ Vietovė %1$s
+ Paskutinis bolusas
+ Paskutinis Bolusas prieš %1$s %2$s min
+ AAO
+ AAO %1$s %2$.0f
+ Užduoties pavadinimas
+ Keisti
+ Pasirinkite veiksmo tipą:
+ Pasirinkite sąlygos tipą:
+ Sąlygos:
+ PAŠALINTI
+ Išankstinės sąlygos:
+ Pompa ir/ar jos valdiklis nepalaiko operacijos.
+ Pompa dar nepalaiko operacijos.
+ Integracija su Medronic pompa reikalauja RileyLink įrenginio ir specialaus pompos modelio
+ Pompos serijos Nr.
+ Pompos tipas
+ Pompos dažnis
+ Užlaikymas prieš Boluso suleidimą (s)
+ Max Bolusas pompoje (vv)
+ Maks val. bazė pompoje (vv/val)
+ Medronic kodavimas
+ US & Kanada (916 MHz)
+ Pasaulinis (868 Mhz)
+ Programinis kodavimas 4b6b
+ Įrangos kodavimas 4b6b
+ Pažadinti ir nustatyti
+ Išvalyti Boluso bloką
+ Išvalyti RileyLink nustatymus
+ Baterijos tipas (galios vaizdas)
+ Nepasirinkta (paprastas vaizdas)
+ Šarminė (išplėstinis vaizdas)
+ Ličio (išplėstinis vaizdas)
+ SKENAVIMAS
+ STOP
+ Parinkta
+ RileyLink skanavimas
+ Bluetooth Low Energy nepalaikoma.
+ Bluetooth neįjungta.
+ Vietovės nustatymas neįjungtas
+ Vietos nustatymo paslauga turi būti įjungta, kad Bluetooth aptikimas veiktų naujesniuose įrenginiuose. AAPS neseka Jūsų lokacijos, o vietos nustatymo paslauga gali būti išjungta po sėkmingo įrenginių suporavimo.
+ Įjungti
+ Ne
+ Skanuojama
+ Skanavimas baigtas
+ Skanavimo klaida: %1$dParametraiIstorija
+ RileyLink statusas
+ Pompos statusasRileyLink parametrai
+ RileyLink
+ Nustatytas adresas
+ Prijungtas įrenginys
+ Ryšio būsena
+ Prisijungimo klaida
+ Įrenginys
+ Įrenginio tipas
+ Įrenginio modelis
+ Paskutinis naudotas dažnis
+ Paskutinis įrenginio kontaktas
+ RL Programinė įranga
+ Inicijuojamas Bluetooth…
+ Bluetooth klaida
+ Bluetooth paruošta
+ Nepradėta
+ RileyLink inicijavimas…
+ RileyLink klaida
+ RileyLink ir Pompos suderinimas
+ Sujungimo su pompa problema
+ Prisijungta
+ Įrenginys nėra RileyLink
+ RileyLink nepasiekiama
+ Bluetooth išjungtas
+ Nėra Bluetooth adapterio
+ TuneUp klaida
+ Pompa nepasiekiama
+ Pod nepasiekiamas
+ Nenustatyta
+ Pompa Medtronic
+ Omnipod
+ Klaidos
+ Serijos Nr. nenustatytas.
+ Serijos Nr. neteisingas.
+ Nenustatytas pompos tipas.
+ Nepalaikomas pompos tipas.
+ Nenustatytas pompos dažnis.
+ Nepalaikomas pompos dažnis.
+ RileyLink adresas neteisingas.
+ Aptiktas pompos tipas neatitinka nustatymų.
+ Pompoje neįjungtas bazės profilis.
+ Pompoje nustatytas neteisingas bazės profilis (turi būti STD).
+ Pompoje nustatytas neteisingas laikinos bazės tipas (turi būti absoliutus).
+ Pompoje nustatytas neteisingas Max Bolusas (turi būti %1$.2f).
+ Pompoje nustatyta neteisinga Maks val. bazė (turi būti %1$.2f).
+ Operacija negalima. \n\n Pirmiausia turite sukonfigūruoti Medronic pompą prieš atliekant šią operaciją.
+ Laiko pokytis didesnis nei 24 val.
+ Valandinės bazės
+ Nustatymai
+ Pranešimai
+ Statistika
+ Nežinoma
+ Visi
+ Medronic pompos istorija
+ Niekada nebuvo sujungta
+ Pažadinimas
+ Ryšio klaida
+ Ryšiui skirtas laikas baigėsi
+ Pompa nepasiekiama
+ Neteisinga konfigūracija
+ Aktyvi
+ Užmigusi
+ Atšaukėte Bolusą, kuris jau buvo nustatytas pompoje. Medronic pompa nepalaiko šio atšaukimo, todėl turite jį atšaukti rankiniu būdu. Sustabdykite pompą ir vėl ją paleiskite (jei vis dar norite atšaukti Bolusą). Aplikacija perims pokyčius su kitu atnaujinimu (per mažiau nei 5 minutes).
+ Negalima sužinoti dabartinės laikinos bazės.
+ Negalima atšaukti dabartinės laikinos bazės. Operacija stabdoma.
+ Profilio nustatymas nepavyko dėl per didelės nustatytos bazės: %1$s
+ Bolusas nesuleistas.
+ Bolusas nesuleistas, nes turimas insulino kiekis (%1$.2f) yra mažesnis, nei nustatytas Bolusas (%2$.2f).
+ Laikina bazė nenustatyta.
+ Negalima atšaukti dabartinės laikinos bazės.
+ Bazės profilis nenustatytas.
+ Bazės profilis toks pat, todėl nenustatomas pakartotinai.
+ Gauti istoriją - Lapas %1$d (%2$d/16)
+ Gauti istoriją - Lapas %1$d
+ Gauti pompos laikąGauti parametrus
-
- %1$d diena
- %1$d diena
- %1$d dienų
- %1$d dienos(-ų)
-
-
- %1$d valanda
- %1$d valandos
- %1$d valandų
- %1$d valandų
-
-
- %1$d minutė
- %1$d minutė(s)
- %1$d minučių
- %1$d minutės(-čių)
-
+ Gauti pompos modelį
+ Gauti bazės profilį
+ Nustatyti bazės profilį
+ Gauti laikiną bazę
+ Nustatyti laikiną bazę
+ Nustatyti bolusą
+ Pakeisti profilį
+ Pakeisti profilį %1$s
+ Paskutinis prisijungimas prie pompos
+ Paskutinis prijungimas prie pompos [min]
+ Paskutinis prijungimas prie pompos prieš %1$s%2$s min.
+ Siųsti SMS: %1$s
+ Siųsti SMS visais nurodytais numeriais
+ Išsiųsti SMS žinutę su tekstu
+ %2$+.2fU]]>
+ Pritaikyti boluso apribojimai: %2$.2fU to %3$.2fU]]>
+ !!!!! Nustatytas lėtas angliavandenių įsisavinimas: %2$d%% laiko. Dar karą patikrinkite savo skaičiavimus. AAO gali būti pervertinti, todėl gali būti suleista per daug insulino!!!!!]]>
+ %1$.0f / %2$d vv
+ Suleisti šią boluso skaičiuoklės rezultato dalį [%]
+ Boluso skaičiuoklė atlieka skaičiavimus, tačiau tik dalis apskaičiuoto insulino yra suleidžiama. Naudinga kartu su SMB algoritmu.
+ Kraunama...
+ Snausti
+ Laiko intervalas
+ Laikas yra tarp %1$s ir %2$s
+ Tarp
+ Uždaryti
+ Didinama maksimali valandinės bazės reikšmė, nes nustatytoji reikšmė yra mažesnė nei profilio maksimali val. bazės reikšmė
+ Neteisingas pranešimas
+ %1$s JIF: %2$.1f
+ %1$.0fg IA: %2$.1f
+ %1$.1fg IA: %2$.1f
+ %1$d%%
+ Boluso patarėjas
+ min.
+ %1$dg
diff --git a/app/src/main/res/values-nl-rNL/exam.xml b/app/src/main/res/values-nl-rNL/exam.xml
index 70489fbc5e..489aec894a 100644
--- a/app/src/main/res/values-nl-rNL/exam.xml
+++ b/app/src/main/res/values-nl-rNL/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Wat is waar over DIA?
+ Thema: duur van de Insuline-actie
+ De minimumwaarde is 3 uur.
+ De minimumwaarde is 5 uur.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Configuration/Config-Builder.html#insuline
+ De betekenis is gelijk aan die van de DIA-parameter die in uw pomp wordt gebruikt.
+ U moet uw eigen waarde bepalen (maar niet minder dan 5 uur).
+ Thema: Hypo Tijdelijk Streefdoel
+ Wat is de primaire reden om een hypo TT in te stellen?
+ Voorkomen dat BG te laag wordt als er een tijdelijk basaal van 0 (nul-temp) wordt uitgevoerd.
+ Om te voorkomen dat AAPS te veel insuline toedient na een stijging veroorzaakt door snelwerkende koolhydraten gebruikt voor de behandeling van een lage BG.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/temptarget.html
+ Welk profiel kan offline worden gebruikt en geconfigureerd?
+ Thema: offline profiel
+ NS-Profiel kan worden gebruikt, maar niet geconfigureerd.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Configuration/Config-Builder.html#profiel
+ Onderwerp: Ontkoppelen van de Pomp
+ Wat moet er gebeuren bij het loskoppelen van de pomp?
+ Klik op \'pomp ontkoppelen\' zodat AAPS weet dat er geen insuline wordt afgeleverd.
+ Klik op \'lus onderbreken\' zodat AAPS stopt met loopen terwijl de pomp is losgekoppeld.
+ Verander niets in AAPS, koppel de pomp gewoon af.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#overige-instellingen
+ Onderwerp: AndroidAPS Instellingen
+ Welke dingen kun je het beste doen om een back-up van uw instellingen te maken?
+ Exporteer de instellingen vanuit het menu Onderhoud.
+ Sla het geëxporteerde bestand op in een andere locatie zoals e-mail, Dropbox, Google-station…
+ Exporteer deze direct na de installatie van AAPS.
+ Exporteer ze na het wijzigen van instellingen.
+ Exporteer ze na het voltooien van een doel.
+ Exporteer deze nadat u de eerste instellingen heeft afgemaakt.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#welke-spullen-moet-ik bij-me-hebben-voor-noodgevallen
+ Onderwerp: Ruis in CGM-Uitlezingen
+ Wat moet er gebeuren als CGM-gegevens ruis vertonen?
+ Niets, AAPS zal het oplossen.
+ Schakel de Loop uit om overdosering te voorkomen.
+ Vervang de CGM-sensor.
+ Schakel de telefoon uit.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#filteren-van-bloed-glucose-waardes
+ Zorg dat uw CGM-app de BG-gegevens vloeiend maakt.
+ Onderwerp: Inspanning
+ Hoe kunt u het systeem helpen zich aan te passen bij sporten?
+ Met behulp van de tijdelijk streefdoel functie.
+ Pas het profiel %% aan naar een waarde onder de 100%.
+ Pas het profiel %% aan naar een waarde boven de 100%.
+ Stop de Loop.
+ Stel een tijdelijk streefdoel in voorafgaand aan het starten met sporten.
+ Het instellen van een tijdelijk streefdoel nadat u met sporten bent gestart, leidt tot slechtere resultaten dan wanneer u dit enige tijd voorafgaand aan het sporten had ingesteld.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/temptarget.html#activiteit-tijdelijk-streefdoel
+ Onderwerp: Uitgeschakelde/onderbroken loop
+ Ontvang ik insuline wanneer de lus is uitgeschakeld/onderbroken?
+ Ja, de basale insuline wordt nog steeds geleverd.
+ Nee, de levering van insuline is gestopt.
+ Onderwerp: Basaal, ISF en IC-tests
+ Wanneer moet ik de basaal, ISF, en KH-waarden uittesten?
+ Voordat ik begin te loopen.
+ Wanneer je vaak een lage BG hebt.
+ Wanneer je vaak een hoge BG hebt.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#androidaps-instellingen
+ Onderwerp: Vereisten
+ Wat heb ik nodig?
+ Goed geteste profielgegevens (Basaal, KH ratio, ISF, DIA).
+ Een computer om een APK te maken.
+ Een geschikte telefoon.
+ Een auto.
+ Nightscout om de doelstellingen te halen.
+ Een Tidepool account.
+ Een Google account.
+ Een Github account.
+ Ervaring met Android ontwikkeling.
+ Een MiniMed 670G pomp.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Module/module.html
+ Een Smartwatch.
+ Een geschikte CGM.
+ Onderwerp: Bijwerken van AndroidAPS
+ Wat is waar?
+ Je moet Git geïnstalleerd hebben.
+ Update zodra nieuwe versie wordt vrijgegeven en je genoeg tijd hebt om het te doen.
+ Gebruik dezelfde ondertekeningssleutels.
+ Doe nooit een update als het systeem goed werkt.
+ Vraag uw vriend om de nieuwe APK.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Installing-AndroidAPS/Update-to-new-version.html#bijwerken-naar-een-nieuwe-versie
+ Onderwerp: Problemen oplossen
+ Waar kun je hulp vinden?
+ Wordt lid van de AndroidAPS Facebook-groep.
+ Lees de volledige AndroidAPS documentatie (kies voor Nederlands in het menu)
+ Bezoek de AndroidAPS Gitter Room.
+ Bezoek AndroidAPS Google-ondersteuning
+ Praat met je endocrinoloog.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Installing-AndroidAPS/Update-to-new-version.html#problemen-oplossen
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Onderwerp: Insuline Plugins
+ Welk merk insuline kan worden gebruikt met de \'Ultra-Rapid-Oref\' plugin?
+ Fiasp®
+ NovoRapid ®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Configuration/Config-Builder.html#insuline
+ Thema: Gevoeligheid Plugin
+ Welk gevoeligheidsalgoritme heeft een configureerbaar tijdbereik?
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Configuration/Sensitivity-detection-and-COB.html
+ Welke gevoeligheidsplugin moet worden gebruikt voor de UAM-functie?
+ Onderwerp: koolhydraten invoer fouten
+ Wat moet u doen als u een onjuiste hoeveelheid koolhydraten hebt ingevoerd?
+ In Behandelingen verwijdert u de onjuiste invoer. Voer nieuwe koolhydraten in.
+ Voeg nep insuline toe met behulp van de \'Refill\' functie
+ Onderwerp: Voedsel met Vet en Eiwit
+ Wat te doen als je eten een grote hoeveelheid vet en/of eiwitten bevat?
+ Reken vetten en eiwitten om naar koolhydraten en gebruik de functie \"Vertraagde koolhydraten (eCarbs)\".
+ Reken vetten en eiwitten om naar koolhydraten en voeg dit toe aan de boluscalculator.
+ Gebruik een uitgestelde bolus om het effect van vet en eiwitten af te dekken.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Extended-Carbs.html
+ Onderwerp: volgen op afstand
+ Hoe kun je AAPS van je kind op afstand volgen?
+ Met behulp van een Nightscout site.
+ Dexcom volgapp als u de originele Dexcom app gebruikt (alleen BG).
+ Dexcom Volg-app als u gebruik maakt van de xDrip app.
+ xDrip app in volg-modus.
+ Loop app op de iPhone.
+ Spike app op de iPhone.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Children/kinderen.html
+ Onderwerp: Insulinegevoeligheidsfactor
+ Hogere ISF-waarden leiden tot minder insulineafgifte wanneer AAPS voor hoge BG corrigeert.
+ Lagere ISF-waarden leiden tot minder insulineafgifte wanneer AAPS voor hoge BG corrigeert.
+ Het wijzigen van de ISF-waarden heeft geen effect op de hoeveelheid insuline die wordt geleverd wanneer AAPS voor hoge BG corrigeert.
+ U moet ISF invoeren in Voorkeuren.
+ Het wijzigen van de ISF-waarde in uw profiel is voldoende om de wijziging toe te passen.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#insuline-gevoeligheids-factor-insulin-sensitivity-factor-ISF-mmol-l-E-of-mg-dl-E
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Profielen.html
+ Onderwerp: De KH ratio
+ Hogere KH ratios leiden tot minder insuline afgifte voor een bepaalde hoeveelheid koolhydraten.
+ Lagere KH ratios leiden tot minder insuline afgifte voor een bepaalde hoeveelheid koolhydraten.
+ Als je 0 COB hebt zal het veranderen van KH ratio leiden tot een andere hoeveelheid insuline om jouw BG te corrigeren.
+ KH ratio zal anders zijn als je brood-eenheid telt als 10g of 12g.
+ KH ratio betekent: Hoeveel brood-eenheden gebruik je voor 1U insuline.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#Koolhydraat-ratio-KH-g-E
+ Onderwerp: Profiel wissels
+ Bij het opgeven van 90% in je profiel wissel…
+ Basalen zullen 10% hoger zijn.
+ Basalen zullen 10% lager zijn.
+ De KH ratio wordt 10% hoger.
+ De KH ratio wordt 10% lager.
+ ISF-waarde wordt 10% hoger.
+ ISF-waarde wordt 10% lager.
+ In totaal zul je ongeveer 10% minder insuline krijgen.
+ Doel zal 10% hoger zijn.
+ Doel zal 10% lager zijn.
+ Alleen de onderste target zal 10% lager zijn.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Profiles.html?highlight=profilewitch#profiel-wissel
+ Als u 1 uur eerder dan normaal wakker wordt, hoe moet u dan AAPS van deze wijziging in uw schema op de hoogte stellen?
+ Voer een profielwijziging uit met een tijdverschuiving van 1
+ Voer een profiel wissel uit met een tijdverschuiving van -1
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Usage/Profiles.html?highlight=profilewitch#tijd-verschuiving
+ Voer een profiel wissel uit met een tijdverschuiving van 60
+ Voer een profiel wissel uit met een tijdverschuiving van -60
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Module/module.html#goed-individueel-doserings-algoritme-voor-jouw-diabetesbehandeling
+ Onderwerp: Hulp met basaal waarden
+ Waar je terecht kunt voor hulp met basaal waarden etc.
+ Jouw behandelaars
+ Google
+ Facebook
+ Andere medicatie
+ AAPS vermindert BR om bloedsuiker te verhogen. Geneesmiddelen van de groep SGLT2-remmers (gliflozins) kunnen de verwachte toename in BG voorkomen en kunnen dus een gevaarlijk insulinekort (DKA) veroorzaken.
+\nGemeenschappelijke merknamen zijn: Invokana ®, Forxiga ®, Jardiance ®, Steglatro ®, Suglat ®, Apleway ®, Deberza ®, Synjardy ®, Vokanamet ®, Xigduo ®.\n\nIk beloof hierbij dat ik dergelijke geneesmiddelen niet zal nemen wanneer ik AAPS gebruik of de lus zal deactiveren voordat ik deze medicijnen gebruik.
+
diff --git a/app/src/main/res/values-nl-rNL/objectives.xml b/app/src/main/res/values-nl-rNL/objectives.xml
new file mode 100644
index 0000000000..f85af9f2c5
--- /dev/null
+++ b/app/src/main/res/values-nl-rNL/objectives.xml
@@ -0,0 +1,68 @@
+
+
+
+ Terug
+ Start
+ Verifieer
+ %1$d. Doel
+ Doel %1$d niet gestart
+ Doel %1$d niet gereed
+ Opzetten van visualisatie en monitoring en analyseren van basalen en ratio\'s
+ Verifieer dat BG beschikbaar is in Nightscout, en dat de insuline gegevens van de pomp worden geüpload
+ Starten met de Open Loop modus
+ Draai enkele dagen In Open Loop modus en voer meermaals handmatig tijdelijke basalen uit. Stel standaard en aangepaste tijdelijke streefdoelen in (bv. bij sporten of koolhydraten inname bij hypo)
+ De Open Loop begrijpen, inclusief de voorgestelde tijdelijke basalen
+ Gebaseerd op deze ervaringen, beslis wat het maximale basaal mag zijn en stel dit in op de pomp
+ Starten met de Closed Loop met bescherming tegen lage Bg
+ In closed loop draaien met een max. IOB = 0 gedurende enkele dagen met een beperkt aantal lage BG
+ Inregelen van de closed loop, verhoog de max IOB boven 0 en laat geleidelijk het streef BG dalen
+ Test enkele dagen als ook minstens 1 nacht zonder een laag BG alarm voordat je jouw streef BG verlaagt
+ Pas het basaal en de ratios aan indien nodig, activeer hierna de auto-sens optie
+ Gedurende 1 week succesvol overdag loopen met regelmatige invoer van koolhydraten
+ Activeren van extra functies overdag zoals AMA (geavanceerde maaltijdhulp, Advanced Meal Assist)
+ Activeren van extra functies overdag zoals SMB (super micro bolus)
+ Lees de wiki en verhoog maxIOB om SMB goed werkend te krijgen. Een goed begin is maxIOB=gemiddelde maaltijdbolus + 3 x max dagelijkse basaal
+ BG beschikbaar in NS
+ Pomp status beschikbaar in NS
+ Handmatige aanpassingen
+ Voltooid: %1$s
+ Leer hoe AndroidAPS te gebruiken
+ Voer verschillende acties uit in AndroidAPS
+ Stel profiel in op 90% voor 10 min (houd profielnaam lang ingedrukt op Overzicht scherm)
+ Simuleer douchen. Ontkoppel de pomp voor 1u (houd Open Loop lang ingedrukt)
+ ... en op dezelfde manier weer aankoppelen
+ Stel een aangepast tijdelijk doel in met een duur van 10 min (houd huidige doel lang ingedrukt)
+ Schakel in Configurator de Acties plugin in zodat deze zichtbaar wordt en de inhoud ervan via de menubar bovenaan kan worden ingezien
+ Inhoud van loop plugin weergeven
+ Gebruik de schaalfunctie: houd de BG grafiek lang ingedrukt
+ Enter
+ Als u eerder OpenAPS gebruikte en u NS ten minste 3 maanden aan Loop gegevens heeft kunt u een code aanvragen waarmee u de rest van de doelstellingen kunt omzeilen. U kunt de aanvraag indienen via objectives@androidaps.org, samen met de url van uw NS. Voer de code die u van de ontwikkelaars hebt ontvangen in
+ Code geaccepteerd
+ Code ongeldig
+ Bewijs je kennis
+ Bestudeer en beantwoord de vragen correct
+ Beantwoorden uitgeschakeld tot: %1$s
+ Verkeerd antwoord!
+ Volgende onvoltooide
+ Aanvraagcode: %1$s
+ (controleer alle juiste antwoorden)
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/FAQ.html#wat-te-doen-tijdens-het-douchen
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/Screenshots.html#overzicht-scherm
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/Screenshots.html#configurator
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/nl/Getting-Started/Screenshots.html#overzicht-scherm
+ Niet verbonden met het internet
+ Ophalen tijd mislukt
+ Vereisten van doel niet behaald
+
+ %1$d dag
+ %1$d dagen
+
+
+ %1$d uur
+ %1$d uren
+
+
+ %1$d minuut
+ %1$d minuten
+
+
diff --git a/app/src/main/res/values-nl-rNL/strings.xml b/app/src/main/res/values-nl-rNL/strings.xml
index 990eab1584..02c6464f33 100644
--- a/app/src/main/res/values-nl-rNL/strings.xml
+++ b/app/src/main/res/values-nl-rNL/strings.xml
@@ -5,7 +5,6 @@
-
Behandelingen veiligheidMax toegestane bolus [E]Max toegestane koolhydraten [g]
@@ -57,9 +56,6 @@
AndroidAPS controleren en bedienen met behulp van uw WearOS-horloge.Toon informatie over de Loop op jouw xDrip+ wijzerplaat.Bedien AndroidAPS op afstand met SMS commando\'s.
- Terug
- Start
- ControleerEénhedenDIAKH ratio
@@ -102,6 +98,7 @@
ProfielMaaltijd gegevensResultaat
+ Resultaat: %1$s %2$sGeen BG gegevens beschikbaarGeen aanpassing noodzakelijkVoorstel
@@ -177,9 +174,6 @@
Niet ondersteunde versie van NSClientNiet ondersteunde versie van NightscoutNSClient niet geïnstalleerd. Gegevens verloren!
- BG beschikbaar op NS
- Pomp status beschikbaar op NS
- Manuele correctiesLoop gedeactiveerd door doelen tabBasaal IOBBolus limiet ingesteld
@@ -222,7 +216,7 @@
Tijdelijk basaalVertraagde bolusNightscout versie:
- Te weinig
+ Ontbrekend %1$dgVoorkeuren geëxporteerdExporteer instellingen naarImporteer instellingen van
@@ -317,8 +311,6 @@
STOP INGEDRUKTWacht op pompEr worden %1$.2fE toegediend
- Opzetten van visualisatie en monitoring en analyzeren van basaal en ratio\'s
- Controleren van beschikbaarheid BG en insuline pomp data op NightscoutLimiet bereiktGeen profiel geselecteerdLoop was uitgeschakeld
@@ -552,10 +544,12 @@
Activeer superbolus in de wizardActiveer de superbolus functie in de wizard. Activeer deze niet tot je begrijpt wat dit doet. OVERDOSIS IS MOGELIJK BIJ BLINDELINGS GEBRUIK!Toon statusindicatoren op startscherm
+ Toon uitgebreide statusindicatoren op overzicht scherm
+ Statusindicatoren inschakelen voor cage, iage, sage, reservoir en batterijniveau op het overzicht scherm.Drempel waarschuwing reservoir niveau [E]Drempel alarm reservoir niveau [E]
- Drempel waarschuwing batterij niveau [%%]
- Drempel alarm voor batterij niveau [%%]
+ Drempel waarschuwing batterij niveau [%]
+ Drempel alarm batterij niveau [%]IOBCOBFirmware
@@ -625,6 +619,7 @@
AfbrekenNiet alle profielen zijn geladen!Waarden niet opgeslagen!
+ Schakel broadcasts in naar andere apps (zoals xDrip). Schakel niet in als je NSClient of meer dan één installatie van AAPS hebt geïnstalleerd!Activeer locaal delen.ACTIVITEIT & FEEDBACKKOOLHYDRATEN & BOLUS
@@ -848,8 +843,6 @@
Profiel wissel ontbreekt. Doe aub een profiel wissel of duw op Activeer Profiel in het Lokale profiel.Aantal bolussenAantal TBR
- Doel %1$d niet gestart
- Doel %1$d niet gereedPomp kan geen tijdelijk basaal aanvaardenGeen correcte basale snelheid van pomp kunnen lezenClosed Loop modus gedeactiveerd in de voorkeuren
@@ -971,7 +964,6 @@
Voltooid, goed gedaan!Nog niet voltooidVerstreken tijd
- %1$d. DoelPoctechOntvang BG waardes van Poctech appOntvang BG waardes van Tomato app (MiaoMiao apparaatje)
@@ -1155,8 +1147,6 @@
Tijdelijke basalen uploadenUpload profiel wisselingen, tijdelijke doelenUpload BG-tests
- Zomer/wintertijd omschakeling binnen 24 uur
- Omschakeling zomer/wintertijd minder dan 3 uur geleden - Closed Loop modus gedeactiveerdinterne opslag bijna volMaak minstens %1$d MB vrij in interne opslag! Loop is uitgeschakeld!Verkeerde invoer
@@ -1244,6 +1234,8 @@
Niet geselecteerd (Eenvoudige weergave)Alkaline (uitgebreide weergave)Lithium (uitgebreide weergave)
+ NiZn (uitgebreide weergave)
+ Bolus/Behandelingen DebuggenSCANSTOP
@@ -1282,6 +1274,7 @@
Niet gestartRileyLink initialiseren…RileyLink fout
+ Tuning van RileyLink en PompProbleem tijdens verbinden met de pompVerbonden
@@ -1351,6 +1344,15 @@
Ophalen Tijdelijke BasaalInstellen Tijdelijke BasaalInstellen Bolus
+ Wijzig profiel naar
+ Wijzig profiel in %1$s
+ Laatste verbinding met pomp
+ Laatste verbinding met pomp [minuten geleden]
+ Laatste verbinding met pomp %1$s %2$s min geleden
+ Stuur SMS: %1$s
+ Stuur SMS naar alle nummers in voorkeuren
+ Stuur SMS met tekst
+ %2$+.2fU]]>Bolus limiet bereikt: %2$.2fU naar %3$.2fU]]>!!! Trage koolhydraat absorptie gedetecteerd: %2$d%% van de tijd. Controleer je berekening nogmaals. COB kan zijn overschat waardoor er misschien meer insuline wordt afgegeven!!! zijn]]>%1$.0f / %2$d E
@@ -1358,16 +1360,19 @@
Bolus wizard voert de berekening uit maar alleen dit deel van berekende insuline wordt geleverd. Handig in combinatie met het SMB algoritme.Bezig met laden...Sluimeren
-
- %1$d dag
- %1$d dag
-
-
- %1$d uur
- %1$d uur
-
-
- %1$d minuut
- %1$d minuut
-
+ Tijdsinterval
+ Tijd ligt tussen %1$s en %2$s
+ Tussen
+ Sluiten
+ Verhogen van de maximale basaal waarde omdat de instelling lager is dan het maximum in het profiel
+ Ongeldige inhoud van het bericht
+ %1$s ISF: %2$.1f
+ %1$.0fg KH ratio: %2$.1f
+ %1$.1fg KH ratio: %2$.1f
+ %1$d%%
+ Bolus wizard
+ min
+ %1$dg
+ Aan
+ Uit
diff --git a/app/src/main/res/values-pl-rPL/exam.xml b/app/src/main/res/values-pl-rPL/exam.xml
index 70489fbc5e..cf6cb932dc 100644
--- a/app/src/main/res/values-pl-rPL/exam.xml
+++ b/app/src/main/res/values-pl-rPL/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Co jest prawdą w przypadku DIA?
+ Temat: Czas działania aktywnej insuliny
+ Wartość minimalna to 3 godziny.
+ Wartość minimalna to 5 godzin.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ Znaczenie jest takie same jak parametru DIA używanego w Twojej pompie.
+ Konieczne jest określenie indywidualnej wartości (ale nie mniej niż 5 godzin).
+ Temat: Cel tymczasowy Hipo
+ Jaki jest podstawowy powód, aby ustawić hypo TT?
+ Aby zapobiec spadkowi poziomu przy obecnie działąjącym zerowaniu bazy.
+ Aby przeciwdziałać AAPS przed podaniem zbyt dużej ilości insuliny po wzroście spowodowanym szybko działającymi węglowodanami użytymi do leczenia niskiego poziomu.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Który profil może być używany i skonfigurowany w trybie offline?
+ Temat: Profil w trybie offline
+ Profil NS może być używany, ale nie jest skonfigurowany.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Temat: Odłączanie od pompy
+ Co należy zrobić przy rozłączeniu pompy?
+ Naciśnij \"WYłącz pompę\" aby AAPS wiedział, że insulina nie jest dostarczana.
+ Naciśnij \"Wstrzymaj pętlę\"aby AAPS zatrzymał pętlę, gdy pompa jest odłączona.
+ Nie zmieniaj niczego w AAPS, po prostu odłącz pompę.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Temat: Ustawienia AndroidAPS
+ Jakie są sprawdzone procedury tworzenia kopii zapasowych ustawień?
+ Lokalnie wyeksportuj je z menu Konserwacja.
+ Zapisz wyeksportowany plik w innym miejscu, np. wyślij e-mailem, prześlij na Dropbox, dysk Google…
+ Wyeksportuj je zaraz po instalacji AAPS.
+ Wyeksportuj je po wprowadzeniu zmian.
+ Wyeksportuj je po wykonaniu zadania.
+ Wyeksportuj je po zakończeniu wstępnych ustawień.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Temat: Szumy w odczytach z CGM
+ Co powinno być wykonane gdy dane CGM są zaszumione?
+ Nic, AAPS sobie z tym poradzi.
+ Wyłącz pętlę, by unilknąć przedawkowania insuliny.
+ Wymień czujnik CGM.
+ Wyłącz telefon.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Sprawdź, czy Twój CGM wygładza dane poziomu cukru.
+ Temat: Ćwiczenia
+ Jak możesz pomóc aby system poradził sobie z ćwiczeniami?
+ Korzystanie z funkcji tymczasowego docelowego poziomu cukru.
+ Wykonaj zmianę profilu poniżej 100%.
+ Wykonaj zmianę profilu powyżej 100%.
+ Zatrzymaj pętlę.
+ Ustaw cel tymczasowy Ćwiczenia przed rozpoczęciem ćwiczeń.
+ Ustawienie celu tymczasowego Ćwiczenia po rozpoczęciu ćwiczeń prowadzi do gorszych wynikow poziomu niż przy jego wcześniejszym rozpoczęciu.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Temat: Wyłączona/Zawieszona pętla
+ Czy otrzymuję insulinę, gdy pętla jest wyłączona/zawieszona?
+ Tak, insulina bazowa nadal jest dostarczana.
+ Nie, podawanie insuliny jest zatrzymane.
+ Temat: Testowanie Bazy, ISF i IC
+ Kiedy powinienem zweryfikować wartości bazy, ISF i IC?
+ Zanim zacznę używać pętli.
+ Gdy często występują niskie poziomy cukru.
+ Gdy często występują wysokie poziomy cukru.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Temat: Wymagania wstępne
+ Czego potrzebuję?
+ Sprawdzone informacje profilowe (Basal, IC, ISF, DIA).
+ Komputer do utworzenia pliku APK.
+ Obsługiwany telefon.
+ Samochód.
+ Nightscout, aby przejść przez zadania.
+ Konto Tidepool.
+ Konto Google.
+ Konto Github.
+ Doświadczenie w rozwoju systemu Android.
+ Pompa MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Smartwatch.
+ Obsługiwany CGM.
+ Temat: Aktualizacja AndroidAPS
+ Co jest prawdą?
+ Musisz mieć zainstalowany Git.
+ Aktualizuj tak szybko jak nowe wersja zostanie opublikowana i znajdziesz czas do jej wprowadzenia.
+ Należy używać tych samych kluczy do podpisywania.
+ Nigdy nie aktualizuj, jeśli system działa dobrze.
+ Poproś swojego przyjaciela o nowy plik APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Temat: Rozwiązywanie problemów
+ Gdzie szukać pomocy?
+ Dołącz do głównej grupy AndroidAPS na Facebooku.
+ Przeczytaj dokumentację AndroidAPS.
+ Odwiedź pokój Gitter na temat AndroidAPS.
+ Odwiedź stronę pomocy technicznej AndroidAPS Google
+ Porozmawiaj ze swoim endokrynologiem/diabetologiem.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Temat: Wtyczki insuliny
+ Jakiej marki insuliny można używać z wtyczką Ultra-Rapid-Oref?
+ Fiasp®
+ NovoRapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Temat: Wtyczka wrażliwości
+ Który algorytm czułości ma konfigurowalny zakres czasu?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Jakiej wtyczki wykrywania wrażliwości należy użyć dla funkcji UAM?
+ Temat: Błędy wprowadzania węglowodanów
+ Co powinieneś zrobić, gdy wprowadziłeś niewłaściwą ilość węglowodanów?
+ W karcie Leczenie (Treatments), usuń niewłaściwy wpis węglowodanów. Wprowadź ponownie właściwą wartość.
+ Dodaj fałszywą insulinę za pomocą funkcji napełniania
+ Temat: Posiłki z tłuszczami i białkami
+ Co zrobić, jeśli twoje jedzenie zawiera dużą ilość tłuszczu i/lub białek?
+ Przelicz tłuszcz i białka na węglowodany i użyj funkcji „Rozszerzone węglowodany” eCarbs.
+ Przelicz tłuszcz i białka na węglowodany i dodaj je do kalkulacji bolusa.
+ Użyj przedłużonego bolusa, aby pokryć tłuszcz i białka.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Temat: Monitorowanie zdalne
+ Jak zdalnie monitorować AAPS swojego dziecka?
+ Korzystanie ze strony Nightscout.
+ Aplikacja Dexcom Follo, jeśli korzystasz z oryginalnej aplikacji Dexcom (tylko BG).
+ Dexcom Follow, jeśli korzystasz z aplikacji xDrip.
+ xDrip działa w trybie śledzenia (follower).
+ Aplikacja Loop na iPhone\'a.
+ Aplikacja Spike na iPhone\'a.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Temat: Współczynnik wrażliwości na insulinę
+ Wyższe wartości ISF prowadzą do mniejszej ilości podanej insuliny gdy AAPS koryguje wysoki poziom cukru.
+ Niższe wartości ISF prowadzą do mniejszej dawki insuliny gdy AAPS koryguje wysoki poziom cukru.
+ Zmiana wartości ISF nie ma wpływu na ilość insuliny dostarczanej, gdy AAPS koryguje wysoki poziom cukru.
+ Musisz wprowadzić ISF w Preferencjach.
+ Zmiana wartości ISF w profilu wystarczy, aby zastosować zmianę.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Temat: Wartość przelicznika IC
+ Wyższe wartości ICprowadzą do mniejszej ilości insuliny dostarczonej do podanej ilości węglowodanów.
+ Niższe wartości IC prowadzą do mniejszej ilości insuliny podanej do wprowadzonej ilości węglowodanów.
+ Załóżmy, że masz 0 COB. Zmiana IC doprowadzi do podania innej ilości insuliny w celu skorygowania twojej wartości BG.
+ IC będzie inny, jeśli policzysz jednostkę chleba jako 10 g lub 12 g.
+ Znaczenie IC to: Ile jednostek chleba jest pokrytych 1U insuliny.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Temat: Przełączanie profili
+ Jeśli podasz 90% podczas zmiany profilu…
+ Baza będzie o 10% wyższa.
+ Baza będzie o 10% niższa.
+ Wartość IC będzie o 10% wyższa.
+ Wartość IC będzie o 10% niższa.
+ Wartość ISF będzie o 10% wyższa.
+ Wartość ISF będzie o 10% niższa.
+ Otrzymasz w sumie około 10% mniej insuliny.
+ Cel będzie wyższy o 10%.
+ Cel będzie o 10% niższy.
+ Tylko dolny cel będzie o 10% niższy.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Jeśli obudzisz się o 1h wcześniej niż zwykle, to jak należy powiadomić AAPS o zmianie w harmonogramie?
+ Wprowadź zmianę profilu ze zmianą czasu równą 1
+ Wprowadź zmianę profilu ze zmianą czasu równą -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Wprowadź zmianę profilu ze zmianą czasu równą 60
+ Wprowadź zmianę profilu ze zmianą czasu równą -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Temat: Pomoc z dawkami podstawowymi (bazą)
+ Gdzie uzyskać pomoc w sprawie dawek podstawowych itp.
+ Twój zespół cukrzycowy
+ Google
+ Facebook
+ Inne leki
+ AAPS zmniejsza BR w celu podniesienia poziomu cukru we krwi. Leki z grupy inhibitorów SGLT2 (gliflozyny) mogą zapobiegać spodziewanemu wzrostowi stężenia glukozy we krwi, a zatem mogą powodować niebezpieczny niedobór insuliny (DKA).
+\nWspólne nazwy marek to: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®. \n\n Obiecuję, że nie będę brać takich leków podczas używania AAPS lub dezaktywuję pętlę przed użyciem tych leków.
+
diff --git a/app/src/main/res/values-pl-rPL/objectives.xml b/app/src/main/res/values-pl-rPL/objectives.xml
new file mode 100644
index 0000000000..af8c38edd9
--- /dev/null
+++ b/app/src/main/res/values-pl-rPL/objectives.xml
@@ -0,0 +1,73 @@
+
+
+
+ Wstecz
+ Start
+ Zweryfikuj
+ %1$d. Zadanie
+ Zadanie %1$d nierozpoczęte
+ Zadanie %1$d nieukończone
+ Konfiguracja wizualizacji i monitorowania, analiza dawek bazowych i współczynników
+ Sprawdź czy BG (pomiary cukru) są dostępne w Nightscout, i czy przesyłane są dane pompy insulinowej
+ Rozpoczęcie w trybie otwartej pętli (open loop)
+ Uruchom w trybie otwartej pętli przez kilka dni i ręcznie potwierdzaj kilka zmian dawki tymczasowej. Ustaw i używaj celów tymczasowych i domyślnych celów tymczasowych (np. Ćwiczenia lub Hipo)
+ Zrozumienie działania otwartej pętli, wraz z jej rekomendacjami dawek tymczasowych
+ Na podstawie tych doświadczeń zdecyduj jaka powinna być ustawiona maksymalna baza, i wprowadź ją w pompie i w ustawieniach AAPS
+ Rozpoczęcie zamknięcia pętli z zawieszeniem podawania bazy przy niskim poziomie cukru
+ Używaj przez kilka dni zamkniętej pętli (Closed Loop) z max IOB = 0 bez zbyt wielu incydentów niedocukrzeń
+ Dostrajanie zamkniętej pętli, podniesienie wartości max IOB powyżej 0 i stopniowe obniżanie docelowego poziomu cukru (BG target)
+ Używaj pętli przez kilka dni i przynajmniej jedną noc bez żadnego alarmu niskiego poziomu, przed obniżeniem docelowego poziomu cukru
+ Dostosuj bazę i wartości parametrów jeśli jest to potrzebne, i wtedy uruchom funkcję autosens
+ 1 tydzień sukcesu w działaniu pętli w ciągu dnia z regularnym wprowadzaniem spożywanych węglowodanów
+ Włączanie dodatkowych funkcji do użytku, jak AMA
+ Włączanie dodatkowych funkcji do użytku, jak SMB (Super Mikro Bolusy)
+ Musisz przeczytać wiki i zwiększyć maxIOB, aby SMB działało dobrze! Dobrym początkiem jest maxIOB = średni bolus + 3 x maks. dzienna dawka bazowa
+ BG dostępne w NS
+ Status pompy dostępny w NS
+ Ręczne zarządzanie
+ Ukończone: %1$s
+ Dowiedz się, jak kontrolować AndroidAPS
+ Wykonuj różne działania w AndroidAPS
+ Ustaw profil 90% na 10 min (Długie przytrzymanie nazwy profilu w Przegląd)
+ Symuluj prysznic. Odłącz pompę na 1 godzinę (długie naciśnięcie w otwartej pętli)
+ ... i połącz się ponownie w ten sam sposób
+ Utwórz własny cel tymczasowy z czasem trwania 10 min (przytrzymaj dłużej przycisk z Twoją nazwą profilu)
+ W konfiguracji włącz wtyczkę Akcje, zrób ją widoczną i wyświetl jej zawartość w górnym menu
+ Wyświetl zawartość wtyczki Pętla (Loop)
+ Użyj funkcji skalowania przez dłuższe przytrzymanie wykresu glikemii
+ Wprowadź
+ Kod został zaakceptowany
+ Niepoprawny kod
+ Potwierdź swoje umiejętności
+ Ucz się i odpowiadaj poprawnie na pytania
+ Odpowiadanie wyłączone na: %1$s
+ Odpowiedź nieprawidłowa!
+ Następny niedokończony
+ Kod zapytania: %1$s
+ (sprawdź wszystkie poprawne odpowiedzi)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Brak połączenia z Internetem
+ Nie udało się odzyskać
+ Wymagania celu nie zostały spełnione
+
+ %1$d dzień
+ %1$d dni
+ %1$d dni
+ %1$d dni
+
+
+ %1$d godzina
+ %1$d godziny
+ %1$d godzin
+ %1$d godziny
+
+
+ %1$d minuta
+ %1$d minut
+ %1$d minut
+ %1$d minuty
+
+
diff --git a/app/src/main/res/values-pl-rPL/strings.xml b/app/src/main/res/values-pl-rPL/strings.xml
index df693f36e6..34385a52dd 100644
--- a/app/src/main/res/values-pl-rPL/strings.xml
+++ b/app/src/main/res/values-pl-rPL/strings.xml
@@ -5,7 +5,6 @@
-
Bezpieczeństwo leczeniaMaks. dopuszczalny bolus [U]Maks. dopuszczalne węglowodany [g]
@@ -57,9 +56,6 @@
Monitoruj i kontroluj AndroidAPS, korzystając z SmartWatch WearOS.Pokaż informacje o swojej pętli na watchface xDrip+.Zdalne sterowanie AndroidAPS za pomocą poleceń SMS.
- Cofnij
- Start
- SprawdźJednostkiDIAIC
@@ -102,6 +98,7 @@
ProfilDane posiłkuRezultat
+ Wynik: %1$s %2$sBrak danych o glukozieZmiana nie wymaganaŻądanie
@@ -177,9 +174,6 @@
Niewspierana wersja NSClientNiewspierana wersja NightscoutNSClient nie zainstalowany. Zapis stracony!
- BG dostępne w NS
- Status pompy dostępny w NS
- Zmiany wykonanePĘTLA WYLĄCZONA Z UWAGI NA OGRANICZENIABazowa IOBOgraniczenia bolusa wprowadzone
@@ -222,7 +216,7 @@
BazaTymczasowaBolus PrzedłużonyWersja Nightscout:
- Brakujące
+ Brakuje %1$dgWłaściwości wyeksportowaneEksportuj ustawienia doImportuj ustawienia z
@@ -317,21 +311,6 @@
NACIŚNIĘTY STOPCzekam na pompęZamierzam dostarczyć %1$.2fU
- Konfiguracja wizualizacji i monitorowania, analiza dawek i wartości bazowych
- Sprawdź czy BG (pomiary cukru) są dostępne w Nightscout, i dane pompy insulinowej są ładowane
- Rozpoczęcie na trybie otwartej pętli (open loop)
- Działaj w trybie Otwartej Pętli przez kilka dni i ręcznie wprowadzaj wiele ustawień bazy tymczasowej. Ustaw i używaj tymczasowych i domyślnych tymczasowych celów (np. do aktywności fizycznej lub węglowodanów w leczeniu hipoglikemii)
- Zrozumienie działania otwartej pętli, wraz z jej rekomendacjami dawek tymczasowych
- Na podstawie tych doświadczeń zdecyduj jaka maksymalna baza powinna być ustawiona, i wprowadź ją w pompie i w ustawieniach AAPS
- Rozpoczęcie zamknięcia pętli z zawieszeniem podawania bazy przy niskim poziomie cukru
- Używaj zamkniętej pętli (Closed Loop) z max IOB (maksymalną dawką aktywnej insuliny) = 0 bez zbyt wielu incydentów niedocukrzeń
- Dostrajanie zamkniętej pętli, podniesienie wartości max IOB powyżej 0 i stopniowe obniżanie docelowego poziomu cukru (BG target)
- Używaj pętli przez kilka dni i przynajmniej jedną noc bez żadnego alarmu niskiego poziomu, przed obniżeniem docelowego poziomu cukru
- Dostosuj bazę i wartości parametrów, i wtedy uruchom funkcję autosens
- 1 tydzień sukcesu w działaniu pętli w ciągu dnia z regularnym wprowadzaniem spożywanych węglowodanów (węglow.)
- Uruchomienie do użytku dziennego dodatkowych funkcji, jak AMA (zaawansowany asystent posiłku)
- Uruchomienie do użytku dziennego dodatkowych funkcji, jak SMB (Super Mikro Bolusy)
- Musisz przeczytać wiki i zwiększyć maxIOB, aby SMB działało dobrze! Dobrym początkiem jest maxIOB = średni bolus + 3 x maks. dzienna dawka bazowaOsiągnąłeś dozwolony limitNie wybrano profiluPętla (Loop) została wyłączona
@@ -569,8 +548,8 @@
Włącz diody stanu dla cage, iage, sage, rezerwuar i poziom baterii na ekranie głównym.Próg ostrzeżenia o poziomie zbiornika [U]Próg ostrzeżenia o krytycznym poziomie zbiornika [U]
- Próg ostrzeżenia o poziomie baterii [%%]
- Próg ostrzeżenia o krytycznym poziomie baterii [%%]
+ Próg ostrzeżenia o poziomie baterii [%]
+ Próg ostrzeżenia o krytycznym poziomie baterii [%]IOBCOBFirmware
@@ -641,6 +620,7 @@
AnulujNie wszystkie profile zostały załadowane!Wartości nie są przechowywane!
+ Włącz rozgłaszanie do innych aplikacji (takich jak xDrip). Nie należy włączać, jeśli zainstalowana jest więcej niż jedna instancja AAPS lub NSClient!Włącz transmisję lokalnie.AKTYWNOŚĆ & REAKCJAWĘGLOW. & BOLUS
@@ -864,8 +844,6 @@
Brakuje ZmianyProfilu. Proszę wykonać ZmianęProfilu lub nacisnąć \"Aktywuj Profil\" w ProfiluLokalnymObliczenia BolusaObliczenia TBR
- Zadanie %1$d nierozpoczęte
- Zadanie %1$d nieukończonePompa nie jest zdolna do wykonywania dawek bazowych tymczasowychBrak prawidłowej dawki bazowej odczytanej z pompyTryb zamkniętej pętli wyłączony w ustawieniach
@@ -987,7 +965,6 @@
Ukończone, wspaniale!Nie ukończonoCzas jaki upłynął
- %1$d. ZadaniePoctechOdczytuj wartości BG z aplikacji PoctechOtrzymuj poziomy cukru (BG) z Apki Tomato) (urządzenie MiaoMiao)
@@ -1171,7 +1148,7 @@
Prześlij bazy tymczasowePrześlij zmiany profilu, cele tymczasowePrześlij testowe BG
- Zmiana na czas letni w ciągu 24 godzin lub krócej
+ Zmiana czasu w 24h lub mniejZmiana czasu nastąpiła mniej niż 3 godziny temu - Zamknięta pętla wyłączonalimit wielkości pamięci wewnętrznejZwolnij co najmniej %1$d MB z pamięci wewnętrznej! Pętla zatrzymana!
@@ -1260,6 +1237,8 @@
Nie wybrany (widok prosty)Alkaliczne (widok rozszerzony)Litowe (widok rozszerzony)
+ NiZn (widok rozszerzony)
+ Bolus/Leczenie - debugowanieSKANUJZATRZYMAJ
@@ -1298,6 +1277,7 @@
Nie rozpoczętoUruchamianie RileyLink…Błąd RileyLink
+ Dostrojenie RileyLink i pompyProblem z połączeniem z pompąPołączono
@@ -1367,6 +1347,15 @@
Pobierz tymczasową dawkę bazowąUstaw tymczasową dawkę bazowąUstaw bolus
+ Zmień profil na
+ Zmień profil na %1$s
+ Ostatnie połączenie z pompą
+ Ostatnie połączenie z pompą [minut temu]
+ Ostatnie połączenie z pompą %1$s %2$s min temu
+ Wyślij SMS: %1$s
+ Wyślij SMS do wszystkich numerów w preferencjach
+ Wyślij SMS z tekstem
+ %2$+.2fU]]>Wprowadzono ograniczenie bolusa: %2$.2fU to %3$.2fU]]>!!!!! Wykryto powolne wchłanianie węglowodanów: %2$d%% czasu. Sprawdź ponownie swoje obliczenia. COB mogły być przeszacowane przez co mogło być podane zbyt dużo insuliny !!!!!]]>%1$.0f / %2$d U
@@ -1374,44 +1363,19 @@
Kreator bolusa wykonuje obliczenia, ale tylko ta część obliczonej dawki insuliny jest dostarczana. Pomocne z algorytmem SMB.Wczytuję...Wycisz
- Wykonane: %1$s
- Naucz się jak zarządzać AndroidAPS
- Przeprowadź różne działania w AndroidAPS
- Ustaw profil 90% na 10 min (naciśnij dłużej nazwę profilu na ekranie głównym)
- Symuluj prysznic. Rozłącz pompę na 1 godzinę (naciśnij dłużej przycisk Otwarta Pętla na ekranie głównym)
- ... i połącz się ponownie w ten sam sposób
- Utwórz własny cel tymczasowy z czasem trwania 10 min (przyciśnij dłużej przycisk z Twoją nazwą profilu)
- W menu konfiguracji uruchom wtyczkę Akcje, zrób ją widoczną i wyświetl jej zawartość w górnym menu
- Wyświetl zawartość wtyczki Pętla (Loop)
- Użyj funkcji skalowania przez dłuższe dotknięcie wykresu glikemii
- Wprowadź
- Wprowadź kod otrzymany od programistów by pominąć resztę zadań
- Kod przyjęty
- Kod nieprawidłowy
- Potwierdź swoje umiejętności
- Ucz się i odpowiedz poprawnie na pytania
- Odpowiadanie wyłączone na: %1$s
- Nieprawidłowa odpowiedź!
- Następne nieukończone
+ Zakres czasu
+ Czas mieści się w zakresie od %1$s do %2$s
+ Pomiędzy Zamknij
- Kod żadania: %1$s
- (sprawdź wszystkie poprawne odpowiedzi)
-
- %1$d dzień
- %1$d dni
- %1$d dni
- %1$d dni
-
-
- %1$d godzina
- %1$d godzin
- %1$d godzin
- %1$d godziny
-
-
- %1$d minuta
- %1$d minut
- %1$d minut
- %1$d minut
-
+ Zwiększanie maksymalnej wartości bazowej ponieważ ustawienia są poniżej maxymalnej wartości bazy w profilu
+ Błędny tekst wiadomości
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Kalkulator bolusa
+ min
+ %1$dg
+ Włącz
+ Wyłącz
diff --git a/app/src/main/res/values-pt-rBR/exam.xml b/app/src/main/res/values-pt-rBR/exam.xml
index 70489fbc5e..6ca2e5ae4f 100644
--- a/app/src/main/res/values-pt-rBR/exam.xml
+++ b/app/src/main/res/values-pt-rBR/exam.xml
@@ -1,3 +1,169 @@
-
+
+ O que é verdade sobre o DIA?
+ Tópico: Duração da Ação de Insulina
+ O valor mínimo é de 3 horas.
+ O valor mínimo é de 5 horas.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ O significado é igual ao parâmetro DIA usado na bomba.
+ Você tem que determinar o seu valor individual (mas não menos de 5 horas).
+ Tópico: Hipo Temp-Alvo
+ O que é a razão principal para definir TT hipoglicemia?
+ Para evitar que a Glic fique baixa se já estiver em funcionamento um temp zero.
+ Para evitar o AAPS dosear demasiada insulina após uma subida rápida causada por hidratos de actuação rápida para tratar hipoglicemia.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Qual perfil pode ser usado e configurado offline?
+ Tópico: Perfil Offline
+ Perfil NS pode ser usado, mas não configurado.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Tópico: Desconectando-se da bomba
+ O que deve ser feito ao desligar a bomba?
+ Clique em \'Desligar bomba\' para que o AAPS saiba que nenhuma insulina está a ser entregue.
+ Clique em \'Suspender loop\' para que AAPS pare o looping enquanto a bomba estiver desconectada.
+ Não altere nada no AAPS, apenas desconecte a bomba.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Tópico: Configurações do AndroidAPS
+ Quais são as melhores práticas para fazer backup de suas configurações?
+ Exporte-as localmente do menu Manutenção.
+ Salve o arquivo exportado para outro local como e-mail, Dropbox, Google drive…
+ Exporte-as logo após a instalação do AAPS.
+ Exportá-los depois de fazer alterações de configuração.
+ Exportá-los depois de completar um objectivo.
+ Exporte-as quando concluir as configurações iniciais.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Tópico: Leituras do CGM imprecisas
+ O que deve ser feito se os dados do CGM são irregulares?
+ Nada, AAPS vai lidar com isso.
+ Desactivar o loop para evitar sobredosagem.
+ Substitua o sensor CGM.
+ Desligue o telefone.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Verifique que a app do CGM suaviza os dados da Glicose.
+ Tópico: Exercício
+ Como você pode ajudar o sistema a lidar com exercícios?
+ Usando o recurso de alvo-temp.
+ Faça um mudança de perfil abaixo de 100%.
+ Fazer uma mudança de perfil acima de 100%.
+ Pare o loop.
+ Definir um alvo-temp de actividade antes de iniciar o exercício.
+ Definir um alvo-temp de actividade após iniciar o exercício leva a resultados piores do que se iniciado antes.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Tópico: Loop Desactivado/Suspenso
+ Eu recebo insulina quando o loop estiver desactivado/suspenso?
+ Sim, a insulina basal continua a ser entregue.
+ Não, a entrega da insulina está parada.
+ Tópico: Testando Basal, ISF e IC
+ Quando devo validar os valores de basal, ISF e IC?
+ Antes de começar com o loop.
+ Quando ocorrer frequentemente Glic baixa.
+ Quando ocorrer frequentemente Glic alta.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Tópico: Pré-requisitos
+ O que eu preciso?
+ Informações do perfil validadas (Basal, IC, FSI, DIA).
+ Um computador para criar um APK.
+ Um telefone compatível.
+ Um carro.
+ Nightscout para passar os objetivos.
+ Uma conta do Tidepool.
+ Uma conta Google.
+ Uma conta do Github.
+ Experiência de desenvolvimento Android.
+ Uma bomba MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Um Smartwatch.
+ Um CGM compatível.
+ Tópico: Actualização do AndroidAPS
+ O que é verdade?
+ Você precisa ter o Git instalado.
+ Actualizar assim que nova versão for lançada e tiver tempo suficiente para fazer isso.
+ Você deve utilizar as mesmas chaves de assinatura.
+ Nunca atualize se o sistema estiver funcionando bem.
+ Peça ao seu amigo para a nova APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Tópico: Resolução de Problemas
+ Onde procurar ajuda?
+ Entrar no grupo AndroidAPS do Facebook.
+ Leia a documentação do AndroidAPS.
+ Visite a sala do AndroidAPS no Gitter.
+ Visite o suporte do Google para o AndroidAPS
+ Fale com seu endocrinologista.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Tópico: Plugins de Insulina
+ Qual marca de insulina pode ser usada com o plugin \'Ultra-Rapid-Oref\'?
+ Fiasp®
+ NovoRapid ®
+ Humalog ®
+ Actrapid ®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Tópico: Plugins de Sensibilidade
+ Qual algoritmo de sensibilidade tem um intervalo de tempo configurável?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Qual plugin de sensibilidade deve ser usado para o recurso UAM?
+ Tópico: Erros de Entrada de Hidratos
+ O que deve fazer se tiver feito uma entrada incorrecta de hidratos?
+ Em Tratamentos, excluir a entrada incorrecta de hidratos. Insira novos hidratos.
+ Adicionar falsa insulina usando a função de Refill
+ Tópico: Alimentos com Gordura e Proteína
+ O que fazer se sua comida contiver uma grande quantidade de gordura e/ou proteínas?
+ Recalcule gordura e proteínas para carboidrato e use o recurso \"Carbs estentido\".
+ Recalcular gordura e proteínas em carboidrato e adicioná-lo ao cálculo de bolus.
+ Use o bolus estendido para cobrir gordura e proteínas.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Tópico: Monitorização Remota
+ Como você pode monitorar AAPS da sua criança remotamente?
+ Usando o site do Nightscout.
+ Dexcom Follow app se você estiver usando o aplicativo Dexcom original(apenas Glicemia).
+ Dexcom Follow se você estiver usando o aplicativo xDrip.
+ xDrip rodando no modo follower.
+ Aplicativo Loop no iPhone.
+ Aplicativo Spike no iPhone.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Tópico: Fator de Sensibilidade de Insulina
+ Valores elevados de FSI levam a uma entrega de menos insulina quando o AAPS corrige Glic alta.
+ Valores baixos de FSI levam a uma entrega de menos insulina quando o AAPS corrige Glic alta.
+ Alterar os valores FSI não tem efeito sobre a quantidade de insulina entregue quando a AAPS corrige Glic alta.
+ Você precisa inserir o ISF nas Preferências.
+ Alterar o valor do ISF no seu perfil é o suficiente para aplicar a alteração.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Tópico: Rácio IC
+ Rácios IC mais altos levam a menos insulina entregue para uma dada quantidade de hidratos.
+ Rácios IC mais baixos levam a menos insulina entregue para uma dada quantidade de hidratos.
+ Se tiver 0 COB, alterar o rácio IC irá levar a uma quantidade diferente de insulina para corrigir um determinado valor da Glic.
+ O IC será diferente se você contar a unidade de pão como 10g ou 12g.
+ O significado do IC é: Quantos pães são cobertas por 1U de insulina.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Tópico: Alternando Perfil
+ Ao especificar 90% na mudança de perfil…
+ Os basais serão 10% maiores.
+ Os basais serão 10% menores.
+ O valor do IC será 10% maior.
+ O valor do IC será 10% menor.
+ O valor do ISF será 10% maior.
+ O valor do ISF será 10% menor.
+ Você receberá aproximadamente 10% menos insulina no total.
+ O alvo será 10% maior.
+ O alvo será 10% menor.
+ Só o alvo inferior será 10% menor.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Se acordar 1h mais cedo do que o normal, como deve notificar a AAPS da mudança no seu horário?
+ Iniciar uma mudança de perfil com uma alteração de turno de 1
+ Iniciar uma mudança de perfil com uma alteração de turno de -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Iniciar uma mudança de perfil com uma alteração de turno de 60
+ Iniciar uma mudança de perfil com uma alteração de turno de -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Tópico: Ajuda com taxas basais
+ Onde procurar ajuda para taxas basais e etc.
+ Sua equipe de diabetes
+ Google
+ Facebook
+ Outra Medicação
+ AAPS reduz Basal para aumentar o açúcar no sangue. As drogas do grupo de inibidores de SGLT2 (gliflozins) podem evitar o aumento esperado da Glic e, assim, podem produzir uma deficiência de insulina perigosa (DKA).
+\nOs nomes comuns de marca são: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nPrometo que não vou tomar tais drogas ao usar o AAPS ou vou desactivar o loop antes de usar essas drogas.
+
diff --git a/app/src/main/res/values-pt-rBR/objectives.xml b/app/src/main/res/values-pt-rBR/objectives.xml
new file mode 100644
index 0000000000..684b9bfa21
--- /dev/null
+++ b/app/src/main/res/values-pt-rBR/objectives.xml
@@ -0,0 +1,68 @@
+
+
+
+ Voltar
+ Iniciar
+ Verificar
+ %1$d. Objetivo
+ Objetivo %1$d não iniciado
+ Objetivo %1$d não concluido
+ Configurando a visualização e monitorando e analisando basais e proporções
+ Verificar se a Glicemia está disponível no Nightscout, e se os dados de insulina da bomba estão sendo transferidos
+ Iniciando em um loop aberto
+ Utilize o modo Open Loop por alguns dias e execute manualmente muitos basais temporários. Configure e use alvos temporários e padrão (por exemplo, para exercício ou tratamento hipos com carboidratos)
+ Entendendo o seu open loop, incluindo as suas recomendações de basais temporárias
+ Com base nessa experiência, decidir qual deve ser a basal máximo e configurá-lo na bomba e nas preferências
+ Começar a fechar loop com Suspensão por Glicose Baixa
+ Utilizar em close loop com IOB máx = 0 por alguns dias sem muitas situações de Suspensão por Baixa Glicose
+ Ajustar o close loop, aumentar a IOB máximo acima de 0 e reduzir gradualmente os alvos de valor glicêmico
+ Utilizar por alguns dias e pelo menos uma noite sem alarmes de Glic baixa, antes de baixar Glic
+ Ajuste as basais e os rácios, se necessário, e, em seguida, active o auto-sens
+ 1 semana de looping durante o dia com sucesso com entrada regular de hidratos de carbono
+ A activar recursos adicionais para uso durante o dia, como assistente avançado de refeição
+ Activando recursos adicionais para uso durante o dia, como SMB
+ Deverá ler a wiki e aumentar a IOB máx para que os SMBs funcionem devidamente! Inicialmente poderá considerar maxIOB=média dos bólus + 3 x a basal máxima
+ Glic disponível no NS
+ Estado da Bomba disponível no NS
+ Execução manual
+ Concluído: %1$s
+ Aprenda como controlar AndroidAPS
+ Executar diferentes acções no AndroidAPS
+ Definir perfil de 90% por 10 min (pressione longo no nome de perfil na Visão Geral)
+ Simular chuveiro. Desligar a bomba de 1h (Pressione longo em Open Loop)
+ ... e volte a ligar de volta da mesma forma
+ Crie um alvo temporário personalizado com 10 min de duração (pressione longo no seu alvo actual)
+ No Configurador active o plugiin de Acções, torne-o visível e exiba o seu conteúdo no menu superior
+ Mostrar conteúdo do plugin Loop
+ Utilizar a função de escala premindo longamente gráfico Glic
+ Inserir
+ Se era utilizador do OpenAPS antes e o seu NS tem pelo menos 3 meses de dados do loop, pode enviar um e-mail para oobjectives@androidaps.org com seu endereço de NS e pedir código para ignorar o resto dos objectivos. Digite o código obtido dos programadores
+ Código aceite
+ Código inválido
+ Prove seu conhecimento
+ Estude e responda as perguntas correctamente
+ Responder desactivado até: %1$s
+ Resposta errada!
+ Próximo inacabado
+ Pedir Código: %1$s
+ (marque todas as respostas correctas)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Não está ligado à internet
+ Falha ao recuperar tempo
+ Requisitos de objectivo não cumpridos
+
+ %1$d dia
+ %1$d dias
+
+
+ %1$d hora
+ %1$d horas
+
+
+ %1$d minuto
+ %1$d minutos
+
+
diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml
index 25a8513e39..c86394d14f 100644
--- a/app/src/main/res/values-pt-rBR/strings.xml
+++ b/app/src/main/res/values-pt-rBR/strings.xml
@@ -5,7 +5,6 @@
-
Segurança do TratamentoMáximo bolus permitido [U]Máximo de carbs permitidos [g]
@@ -57,9 +56,6 @@
Monitore e controle AndroidAPS usando seu relógio WearOS.Mostrar informações sobre o loop no watchface do xDrip+.Controlar remotamente o AndroidAPS usando comandos SMS.
- Voltar
- Iniciar
- VerificarUnidadesDIAIC
@@ -102,6 +98,7 @@
PerfilDados de refeiçãoResultado
+ Resultado: %1$s %2$ssSem dados de glicose disponíveisNenhuma alteração solicitadaSolicitar
@@ -177,9 +174,6 @@
Versão não suportada do NSClientVersão não suportada do NightscoutNSClient não instalado. Registro perdido!
- BG disponível no NS
- Status da Bomba está disponível no NS
- Execução manualLOOP DESATIVADO POR RESTRIÇÕESIOB BasalRestrição de bólus aplicada
@@ -222,7 +216,7 @@
Basal TemporáriaBólus estendidoVersão do Nightscout:
- Faltando
+ Falta %1$dgPreferências exportadasExportar configurações paraImportar configurações de
@@ -317,9 +311,6 @@
STOP PRESSIONADOAguardando a bombaVão ser administradas %1$.2fU
- Configuração da visualização e monitoramento, e análise de rácios e basals
- Verificar se a BG está disponível no Nightscout, e se os dados de insulina da bomba estão a ser carregados
- A iniciar em Open LoopAtingiu o limite autorizadoNenhum perfil selecionadoLoop foi desativado
@@ -553,10 +544,12 @@
Activar superbólus no assistenteHabilite a funcionalidade de superbolus no assistente. Não habilite até que aprenda o funcionamento. PODE CAUSAR OVERDOSE DE INSULINA SE USAR INDISCRIMINADAMENTE!Mostrar luzes de estado no ecrã principal
+ Mostrar luzes de estado estendido no ecrã principal
+ Ativar as luzes de status estendida para idade da cânula, insulina, sensor, reservatório e bateria no ecrã inicial.Limite de aviso de nível de reservatório [U]Limite crítico de nível de reservatório [U]
- Limite de aviso de nível de bateria [%%]
- Limite crítico de nível de bateria [%%]
+ Limite de aviso de nível de bateria [%]
+ Limite de crítico de nível de bateria [%]IOBCOBFirmware
@@ -626,6 +619,7 @@
CancelarNem todos perfis foram carregados!Valores não guardados!
+ Ative as transmissões para outros apps (como xDrip). Não ative se você tiver mais de uma instância de AAPS ou NSClient instalada!Activar partilha local.ATIVIDADE & FEEDBACKCARBOS & BOLUS
@@ -633,7 +627,7 @@
BOMBAValor da Basal [U/h]Duração [min]
- OpenAPS SMB
+ SMB OpenAPSSMBActivar UAMActivar SMB
@@ -686,6 +680,7 @@
gmh
+ d]]>kJEn
@@ -714,6 +709,7 @@
Configurações de upload de BGMostrar Delta detalhoMostrar delta com mais um ponto decimal
+ SMB máx. minutosLimite de minutos de basal para SMBFirmware bomba não suportadoEnviar dados Glic. para xDrip+
@@ -849,8 +845,6 @@
TrocaPerfil em falta. Por favor faça uma troca de perfil ou pressione \"Activar Perfil\" em PerfilLocal.Contagem BólusContagem TBR
- Objetivo %1$d não iniciado
- Objetivo %1$d não concluidoA bomba não é capaz de basais temporáriasNenhum valor de basal temporaria valido foi lido da bombaLoop fecchado disabilitado nas preferências
@@ -972,7 +966,6 @@
Terminado, parabéns!IncompletoTempo decorrido
- %1$d. ObjectivoPoctechReceber valores Glucose da app PoctechReceber valores de Glicose da aplicação Tomato (dispositivo MiaoMiao)
@@ -1245,6 +1238,8 @@
Não seleccionado (Visão simples)Alcalina (Visão estendida)Lithium (visão estendida)
+ NiZn (Vista Estendida)
+ Depuração de Bólus/TratamentosPROCURARPARAR
@@ -1283,6 +1278,7 @@
Não IniciadoInicialização do RileyLink…Erro no RileyLink
+ Configurando RileyLink e a BombaProblema ao ligar à BombaLigado
@@ -1352,6 +1348,15 @@
Obter Basal temporárioDefinir Basal temporárioDefinir Bólus
+ Alterar perfil para
+ Alterar perfil para %1$s
+ Última ligação à bomba
+ Última ligação à bomba [minutos atrás]
+ Última ligação à bomba %1$s %2$s min atrás
+ Enviar SMS: %1$s
+ Enviar SMS para todos os números nas preferências
+ Enviar SMS com texto
+ %2$+.2fU]]>Restrição de Bolus aplicada: %2$.2fU para %3$.2fU]]>!!!!! Absorção lenta de hidratos detectada: %2$d%% do tempo. Verifique o seu cálculo. COB pode estar sobreestimado, assim mais insulina pode ser dada !!!]]>%1$.0f / %2$d U
@@ -1359,31 +1364,19 @@
Assistente de bólus executa o cálculo, mas apenas esta parte da insulina calculada é entregue. Útil com o algoritmo SMB.A carregar ...Silenciar
- Concluído: %1$s
- Aprenda a controlar o AndroidAPS
- Executar diferentes acções no AndroidAPS
- Exibir conteúdo do plugin do Loop
- Inserir
- Digite o código obtido dos programadores para ignorar o resto dos objectivos
- Código aceite
- Código inválido
- Prove seu conhecimento
- Resposta desactivada para: %1$s
- Resposta errada!
- Próximo não concluído
+ Intervalo de tempo
+ O tempo está entre %1$s e %2$s
+ Entre Fechar
- Pedir código: %1$s
- (seleccione todas as respostas correctas)
-
- %1$d dia
- %1$d dias
-
-
- %1$d hora
- %1$d hora
-
-
- %1$d minuto
- %1$d minutos
-
+ Aumentar o valor máximo de basal porque a configuração é inferior à sua basal máxima no perfil
+ Corpo da mensagem inválido
+ %1$s FSI: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Assistente de Bólus
+ min
+ %1$dg
+ Ligado
+ Desligado
diff --git a/app/src/main/res/values-pt-rPT/exam.xml b/app/src/main/res/values-pt-rPT/exam.xml
index 70489fbc5e..9ad55b2946 100644
--- a/app/src/main/res/values-pt-rPT/exam.xml
+++ b/app/src/main/res/values-pt-rPT/exam.xml
@@ -1,3 +1,169 @@
-
+
+ O que é verdade sobre DIA?
+ Tópico: Duração da Acção de Insulina (DIA)
+ O valor mínimo é de 3 horas.
+ O valor mínimo é de 5 horas.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ O significado é igual ao parâmetro DIA usado na bomba.
+ É necessário determinar o seu valor individual (mas não menos de 5 horas).
+ Tópico: Alvo-Temp. Hipo
+ O que é a razão principal para definir TT hipoglicemia?
+ Para evitar que a Glic fique baixa se já estiver em funcionamento um temp zero.
+ Para evitar o AAPS dosear demasiada insulina após uma subida rápida causada por hidratos de actuação rápida para tratar hipoglicemia.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Qual perfil pode ser usado e configurado offline?
+ Tópico: Perfil Offline
+ Perfil NS pode ser usado, mas não configurado.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Tópico: Desligar a Bomba
+ O que deve ser feito ao desligar a bomba?
+ Clique em \'Desligar bomba\' para que o AAPS saiba que nenhuma insulina está a ser entregue.
+ Clique em \'Suspender loop\' para que AAPS pare o looping enquanto a bomba estiver desconectada.
+ Não altere nada no AAPS, apenas desconecte a bomba.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Tópico: Definições do AndroidAPS
+ Quais são as práticas recomendadas para fazer cópia de segurança das configurações?
+ Exportá-las localmente a partir do menu Manutenção.
+ Armazenar ficheiro exportado para outro local como e-mail, Dropbox, Google drive…
+ Exportá-los logo após a instalação do AAPS.
+ Exportá-los depois de fazer alterações de configuração.
+ Exportá-los depois de completar um objectivo.
+ Exportá-los quando terminar as configurações iniciais.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Tópico: Leituras Irregulares CGM
+ O que deve ser feito se os dados do CGM são irregulares?
+ Nada, AAPS vai lidar com isso.
+ Desactivar o loop para evitar sobredosagem.
+ Substituir o sensor CGM.
+ Desligue o telefone.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Verifique que a app do CGM suaviza os dados da Glicose.
+ Tópico: Exercício
+ Como você pode ajudar o sistema a lidar com exercícios?
+ Usando o recurso de alvo-temp.
+ Fazer uma mudança de perfil inferior a 100%.
+ Fazer uma mudança de perfil acima de 100%.
+ Parar o loop.
+ Definir um alvo-temp de actividade antes de iniciar o exercício.
+ Definir um alvo-temp de actividade após iniciar o exercício leva a resultados piores do que se iniciado antes.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Tópico: Loop Desactivado/Suspenso
+ Eu recebo insulina quando o loop estiver desactivado/suspenso?
+ Sim, a insulina basal continua a ser entregue.
+ Não, a entrega da insulina está parada.
+ Topic: Testar Basal, FSI e IC
+ Quando devo validar valores das basais, FSI e de IC?
+ Antes de começar com o looping.
+ Quando ocorrer frequentemente Glic baixa.
+ Quando ocorrer frequentemente Glic alta.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+ Tópico: Pré-requisitos
+ O que preciso?
+ Informações do perfil validadas (Basal, IC, FSI, DIA).
+ Um computador para criar um APK.
+ Um telefone compatível.
+ Um Carro.
+ Nightscout para passar os objectivos.
+ Uma conta Tidepool.
+ Uma conta Google.
+ Uma conta Github.
+ Experiência de desenvolvimento Android.
+ Uma bomba MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html
+ Um Smartwatch.
+ Um CGM Suportado.
+ Tópico: Actualização do AndroidAPS
+ O que é verdadeiro?
+ Você precisa ter o Git instalado.
+ Actualizar assim que nova versão for lançada e tiver tempo suficiente para fazer isso.
+ Você deve utilizar as mesmas chaves de assinatura.
+ Nunca actualize se o sistema estiver a funcionar bem.
+ Pergunte ao seu amigo pelo novo APK.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branch
+ Tópico: Resolução de Problemas
+ Onde ir para obter ajuda?
+ Adira ao grupo do Facebook AndroidAPS.
+ Leia a documentação do AndroidAPS.
+ Visite AndroidAPS Gitter Room.
+ Visite o suporte AndroidAPS Google
+ Fale com seu endócrinologista.
+ https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshooting
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Tópico: Plugins de Insulina
+ Qual marca de insulina pode ser usada com o plugin \'Ultra-Rapid-Oref\'?
+ Fiasp®
+ NovoRapid ®
+ Humalog ®
+ Actrapid ®
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
+ Tópico: Plugins de Sensibilidade
+ Qual algoritmo de sensibilidade tem um intervalo de tempo configurável?
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.html
+ Qual plugin de sensibilidade deve ser usado para o recurso UAM?
+ Tópico: Erros de Entrada de Hidratos
+ O que deve fazer se tiver feito uma entrada incorrecta de hidratos?
+ Em Tratamentos, excluir a entrada incorrecta de hidratos. Insira novos hidratos.
+ Como adicionar insulina falsa utilizando a função Recarregar
+ Tópico: Alimentos com Gordura e Proteína
+ O que fazer se a comida contém uma grande quantidade de gordura e/ou proteínas?
+ Recalcular gordura e proteínas em hidratos e usar recurso de \"Hidratos Estendidos\".
+ Recalcular gordura e proteínas em hidratos e adicionar ao cálculo de bólus.
+ Use o bólus estendido para cobrir gordura e proteínas.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
+ Tópico: Monitorização Remota
+ Como pode monitorizar AAPS do seu filho remotamente?
+ Usando um site Nightscout.
+ App Dex om Follow se estiver a usar a app original Dexcom (Glic apenas).
+ Dexcom Follow se estiver a usar a app xDrip.
+ xDrip a correr no modo seguidor.
+ App de Loop no iPhone.
+ App Spike no iPhone.
+ https://androidaps.readthedocs.io/en/latest/EN/Children/Children.html
+ Tópico: Factor de Sensibilidade de Insulina
+ Valores elevados de FSI levam a uma entrega de menos insulina quando o AAPS corrige Glic alta.
+ Valores baixos de FSI levam a uma entrega de menos insulina quando o AAPS corrige Glic alta.
+ Alterar os valores FSI não tem efeito sobre a quantidade de insulina entregue quando a AAPS corrige Glic alta.
+ É necessário inserir FSI nas Preferências.
+ A alteração do valor do FSI no seu perfil é suficiente para aplicar a mudança.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
+ Tópico: Rácio IC
+ Rácios IC mais altos levam a menos insulina entregue para uma dada quantidade de hidratos.
+ Rácios IC mais baixos levam a menos insulina entregue para uma dada quantidade de hidratos.
+ Se tiver 0 COB, alterar o rácio IC irá levar a uma quantidade diferente de insulina para corrigir um determinado valor da Glic.
+ IC será diferente se contar a unidade de pão como 10g ou 12g.
+ O significado do IC é: Quantas unidades de pão são cobertas por 1U de insulina.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
+ Tópico: Mudança De Perfil
+ Ao especificar 90% na mudança de perfil…
+ Basais são 10% superiores.
+ Basais serão 10% inferiores.
+ Valor IC será 10% superior.
+ Valor IC será 10% inferior.
+ O valor FSI será 10% mais alto.
+ O valor FSI será 10% mais baixo.
+ Você receberá aproximadamente 10% menos insulina no total.
+ Alvo será 10% superior.
+ Alvo será 10% inferior.
+ Só alvo inferior será 10% menor.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
+ Se acordar 1h mais cedo do que o normal, como deve notificar a AAPS da mudança no seu horário?
+ Iniciar uma mudança de perfil com uma alteração de turno de 1
+ Iniciar uma mudança de perfil com uma alteração de turno de -1
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
+ Iniciar uma mudança de perfil com uma alteração de turno de 60
+ Iniciar uma mudança de perfil com uma alteração de turno de -60
+ https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapy
+ Tópico: Ajuda com taxas de basal
+ Onde ir para obter ajuda com rácios da basal, etc.
+ A sua equipa da diabetes
+ Google
+ Facebook
+ Outra Medicação
+ AAPS reduz Basal para aumentar o açúcar no sangue. As drogas do grupo de inibidores de SGLT2 (gliflozins) podem evitar o aumento esperado da Glic e, assim, podem produzir uma deficiência de insulina perigosa (DKA).
+\nOs nomes comuns de marca são: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nPrometo que não vou tomar tais drogas ao usar o AAPS ou vou desactivar o loop antes de usar essas drogas.
+
diff --git a/app/src/main/res/values-pt-rPT/objectives.xml b/app/src/main/res/values-pt-rPT/objectives.xml
new file mode 100644
index 0000000000..dae6fcc431
--- /dev/null
+++ b/app/src/main/res/values-pt-rPT/objectives.xml
@@ -0,0 +1,68 @@
+
+
+
+ Voltar
+ Iniciar
+ Verificar
+ %1$d. Objectivo
+ Objetivo %1$d não iniciado
+ Objetivo %1$d não terminado
+ A configurar visualização e monitorização, e análise de rácios e basais
+ Verificar se a Glic está disponível no Nightscout, e se os dados da bomba de insulina estão a ser carregados
+ A iniciar em Open Loop
+ Utilizar em modo de Open Loop por alguns dias e dar manualmente muitas basais temporárias. Configurar e usar alvos temporários e alvos padrão temporários (por exemplo, para actividade ou tratamentos de hipo com hidratos)
+ Compreender o seu open loop, incluindo as recomendações de basais temporárias
+ Com base nessa experiência, decidir qual deve ser a basal máxima e configurá-la na bomba e nas preferências
+ Começar o close loop com Suspensão por Glicose Baixa
+ Utilizar em close loop com IOB máx = 0 por alguns dias sem muitas situações de Suspensão por Baixa Glicose
+ Ajustar o close loop, aumentar IOB máxima acima de 0 e reduzir gradualmente os alvos de Glic
+ Utilizar por alguns dias e pelo menos uma noite sem alarmes de Glic baixa, antes de baixar Glic
+ Ajuste as basais e os rácios, se necessário, e, em seguida, active o auto-sens
+ 1 semana de looping durante o dia com sucesso com entrada regular de hidratos de carbono
+ A activar recursos adicionais para uso durante o dia, como assistente avançado de refeição
+ Activando recursos adicionais para uso durante o dia, como SMB
+ Deverá ler a wiki e aumentar a IOB máx para que os SMBs funcionem devidamente! Inicialmente poderá considerar maxIOB=média dos bólus + 3 x a basal máxima
+ Glic disponível no NS
+ Estado da Bomba disponível no NS
+ Execução manual
+ Concluído: %1$s
+ Aprenda como controlar AndroidAPS
+ Executar diferentes acções no AndroidAPS
+ Definir perfil de 90% por 10 min (pressione longo no nome de perfil na Visão Geral)
+ Simular chuveiro. Desligar a bomba de 1h (Pressione longo em Open Loop)
+ ... e volte a ligar de volta da mesma forma
+ Crie um alvo temporário personalizado com 10 min de duração (pressione longo no seu alvo actual)
+ No Configurador active o plugiin de Acções, torne-o visível e exiba o seu conteúdo no menu superior
+ Mostrar conteúdo do plugin Loop
+ Utilizar a função de escala premindo longamente gráfico Glic
+ Inserir
+ Se era utilizador do OpenAPS antes e o seu NS tem pelo menos 3 meses de dados do loop, pode enviar um e-mail para oobjectives@androidaps.org com seu endereço de NS e pedir código para ignorar o resto dos objectivos. Digite o código obtido dos programadores
+ Código aceite
+ Código inválido
+ Prove seu conhecimento
+ Estude e responda as perguntas correctamente
+ Responder desactivado até: %1$s
+ Resposta errada!
+ Próximo inacabado
+ Pedir Código: %1$s
+ (marque todas as respostas correctas)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Não está ligado à internet
+ Falha ao recuperar tempo
+ Requisitos de objectivo não cumpridos
+
+ %1$d dia
+ %1$d dias
+
+
+ %1$d hora
+ %1$d horas
+
+
+ %1$d minuto
+ %1$d minutos
+
+
diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml
index a89e329f2f..892b93a1f6 100644
--- a/app/src/main/res/values-pt-rPT/strings.xml
+++ b/app/src/main/res/values-pt-rPT/strings.xml
@@ -5,7 +5,6 @@
-
Segurança de tratamentosMax bolus permitido [U]Max hidratos permitidos [g]
@@ -32,7 +31,7 @@
Estado do algoritmo em 2016Estado do algoritmo em 2017Algoritmo mais recente para usuários avançados
- Exibe o estado atual do seu loop e botões para ações mais comuns
+ Exibe o estado actual do loop e botões para acções mais comunsMostra uma notificação em curso com um breve resumo do que o seu loop está a fazerDefina um perfil que está disponível offline.Fornece o perfil definido no Nightscout
@@ -57,13 +56,10 @@
Monitorizar e controlar o AndroidAPS usando o seu relógio WearOS.Mostrar informações sobre o loop no watchface do xDrip+.Controlar remotamente o AndroidAPS usando comandos SMS.
- Anterior
- Iniciar
- VerificarUnidadesDIAIC
- ISF
+ FSIBasalAlvoSEM PERFIL DEFINIDO
@@ -102,6 +98,7 @@
PerfilDados de refeiçãoResultado
+ Resultado: %1$s %2$ssSem dados de glucose disponíveisNenhuma alteração solicitadaPedido
@@ -177,9 +174,6 @@
Versão não suportada do NSClienteVersão sem suporte do NightscoutNSCliente em falta. Perdido registo!
- Glic disponível no NS
- Status da Bomba está disponível no NS
- Execução manualLOOP DESATIVADO POR RESTRIÇÕESBasal IOBRestrição de bólus aplicada
@@ -222,7 +216,7 @@
BasalTempBólus estendidoVersão Nightscout:
- Em falta
+ Falta %1$dgPreferências exportadasExportar configurações paraImportar configurações de
@@ -302,7 +296,7 @@
Insulina diáriaErrosGlicose
- Reabastecimento
+ RecarregarSuspenderA ligar durante %1$d sSenha da bomba
@@ -317,9 +311,6 @@
STOP PRESSIONADOÀ espera da bombaVão ser administradas %1$.2fU
- Configuração da visualização e monitoramento, e análise de rácios e basals
- Verificar se a BG está disponível no Nightscout, e se os dados de insulina da bomba estão a ser carregados
- A iniciar em Open LoopAtingiu o limite autorizadoNenhum perfil seleccionadoLoop foi desactivado
@@ -553,10 +544,12 @@
Activar superbólus no assistenteHabilite a funcionalidade de superbolus no assistente. Não habilite até que aprenda o funcionamento. PODE CAUSAR OVERDOSE DE INSULINA SE USAR INDISCRIMINADAMENTE!Mostrar luzes de estado no ecrã principal
+ Mostrar luzes de estado no ecrã principal
+ Activar as luzes de estado para idade da cânula, idade da insulina, idade do sensor, reservatório e bateria no ecrã inicial.Limite de aviso de nível de reservatório [U]Limite crítico de nível de reservatório [U]
- Limite de aviso de nível de bateria [%%]
- Limite crítico de nível de bateria [%%]
+ Limite de aviso de nível de bateria [%]
+ Limite de crítico de nível de bateria [%]IOBCOBFirmware
@@ -626,6 +619,7 @@
CancelarNem todos perfis foram carregados!Valores não guardados!
+ Activar transmissões para outras aplicações (como xDrip). Não habilite se tiver mais de uma instância de AAPS ou NSClient instalado!Activar partilha local.ACTIVIDADE & FEEDBACKHIDRATOS & BÓLUS
@@ -686,6 +680,7 @@
gmh
+ d]]>kJEn
@@ -714,6 +709,7 @@
Configurações de upload de BGMostrar Delta detalhoMostrar delta com mais um ponto decimal
+ SMB máx. minutosLimite de minutos de basal para SMBFirmware bomba não suportadoEnviar dados Glic. para xDrip+
@@ -849,8 +845,6 @@
TrocaPerfil em falta. Por favor faça uma troca de perfil ou pressione \"Activar Perfil\" em PerfilLocal.Contagem BólusContagem TBR
- Objetivo %1$d não iniciado
- Objetivo %1$d não concluidoA bomba não é capaz de basais temporáriasNenhum valor de basal temporaria valido foi lido da bombaLoop fecchado disabilitado nas preferências
@@ -972,7 +966,6 @@
Terminado, parabéns!IncompletoTempo decorrido
- %1$d. ObjectivoPoctechReceber valores Glucose da app PoctechReceber valores de Glicose da aplicação Tomato (dispositivo MiaoMiao)
@@ -1245,6 +1238,8 @@
Não seleccionado (Visão simples)Alcalina (Visão estendida)Lithium (visão estendida)
+ NiZn (Vista Estendida)
+ Depuração de Bólus/TratamentosPROCURARPARAR
@@ -1353,6 +1348,14 @@
Obter Basal TemporáriaDefinir Basal TemporáriaDefinir Bólus
+ Alterar perfil para
+ Alterar perfil para %1$s
+ Última ligação à bomba
+ Última ligação à bomba [minutos atrás]
+ Última ligação à bomba %1$s %2$s min atrás
+ Enviar SMS: %1$s
+ Enviar SMS para todos os números nas preferências
+ Enviar SMS com texto%2$+.2fU]]>Restrição de Bolus aplicada: %2$.2fU para %3$.2fU]]>!!!!! Absorção lenta de hidratos detectada: %2$d%% do tempo. Verifique o seu cálculo. COB pode estar sobreestimado, assim mais insulina pode ser dada !!!]]>
@@ -1361,31 +1364,19 @@
Assistente de bólus executa o cálculo, mas apenas esta parte da insulina calculada é entregue. Útil com o algoritmo SMB.A carregar ...Silenciar
- Concluído: %1$s
- Aprenda a controlar o AndroidAPS
- Executar diferentes acções no AndroidAPS
- Exibir conteúdo do plugin do Loop
- Inserir
- Digite o código obtido dos programadores para ignorar o resto dos objectivos
- Código aceite
- Código inválido
- Prove seu conhecimento
- Resposta desactivada para: %1$s
- Resposta errada!
- Próximo não concluído
+ Intervalo de tempo
+ O tempo está entre %1$s e %2$s
+ Entre Fechar
- Pedir código: %1$s
- (seleccione todas as respostas correctas)
-
- %1$d dia
- %1$d dias
-
-
- %1$d hora
- %1$d hora
-
-
- %1$d minuto
- %1$d minutos
-
+ Aumentar o valor máximo de basal porque a configuração é inferior à sua basal máxima no perfil
+ Corpo da mensagem inválido
+ %1$s FSI: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Assistente de Bólus
+ min
+ %1$dg
+ Ligado
+ Desligado
diff --git a/app/src/main/res/values-ro-rRO/exam.xml b/app/src/main/res/values-ro-rRO/exam.xml
index 70489fbc5e..15be025f38 100644
--- a/app/src/main/res/values-ro-rRO/exam.xml
+++ b/app/src/main/res/values-ro-rRO/exam.xml
@@ -1,3 +1,48 @@
-
+
+ Care afirmații despre DIA sunt adevărate?
+ Subiect: Durata Acțiunii Insulinei
+ Valoarea minimă este de 3 ore.
+ Valoarea minimă este de 5 ore.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
+ Este vorba despre ceva ce este egal cu parametrul DIA folosit în pompa dumneavoastră.
+ Va trebui să vă determinați valoarea individuală (dar nu mai mică de 5 ore).
+ Subiect: Țintă hipo temp
+ Care este scopul principal pentru care se stabilește o bazală temporară de hipo?
+ Pentru a preveni o scădere a glicemiei dacă este deja activă o bazală zero.
+ Pentru evitarea supradozării de insulină de către AAPS, după o creștere cauzată de carbohidrați rapizi folosiți pentru tratarea unui hipo.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html
+ Ce profil se va folosi și configura offline?
+ Subiect: Profil Offline
+ Profilul NS poate fi folosit, dar nu modificat.
+ https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profile
+ Subiect: Deconectarae de la pompă
+ Ce trebuie să faceți atunci când deconectați pompa?
+ Apăsați ‘Deconectează pompa’ astfel încât AAPS să știe că nu se va putea livra insulină.
+ Apăsați ‘Suspendă bucla’ astfel încât AAPS să dezactiveze bucla atâta timp cât pompa este deconectată.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settings
+ Subiect: Setări AndroidAPS
+ Care sunt cele mai bune metode de a păstra o copie de siguranță a setărilor AndroidAPS?
+ Export pe un mediu de stocare local folosind meniul Mentenanță.
+ Stocarea fișierului exportat într-un alt loc, precum email, Dropbox, Google drive…
+ Exportarea imedia după instalarea AAPS.
+ Exportarea atunci când ați terminat setarea inițială.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-me
+ Subiect: Citiri zgomotoase ale glicemiei
+ Se va înlocui senzorul CGM.
+ Se va opri telefonul.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
+ Subiect: Exerciții fizice
+ Cum puteți ajuta sistemul să facă față exercițiilor fizice?
+ Se va face un schimb de profil de sub 100%.
+ Se va face o schimbare de profil de peste 100%.
+ Se va opri bucla.
+ https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
+ Nu, livrarea de insulină este oprită.
+ Subiect: Bazală, ISF și testare IC
+ Când ar trebui să validez bazalele, ISF și valorile IC?
+ Înainte de pornirea buclei.
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settings
+
diff --git a/app/src/main/res/values-ro-rRO/objectives.xml b/app/src/main/res/values-ro-rRO/objectives.xml
new file mode 100644
index 0000000000..0c4e5ad161
--- /dev/null
+++ b/app/src/main/res/values-ro-rRO/objectives.xml
@@ -0,0 +1,69 @@
+
+
+
+ Înapoi
+ Start
+ Verifică
+ Obiectiv %1$d
+ Obiectivul %1$d nu a fost asumat
+ Obiectivul %1$d nu a fost atins
+ Se stabilesc vizualizările și monitorizarea și se analizează bazalele și valorile ratelor
+ Verificați că vedeți glicemia în Nightscout și că datele despre insulină date de pompă sunt înregistrate în site
+ Pornire cu buclă deschisă
+ Funcționare în modul Buclă Deschisă pentru câteva zile și introducere manuală a multiplelor sugestii de bazale temporare. Se stabilesc și se folosesc ținte temporare și ținte implicite (e.g. pentru activități sau pentru carbohidrați de corecție)
+ Se va înțelege modul de lucru în buclă deschisă, inclusiv recomandările de bazale temporare
+ Pe baza experienței, se va decide care va fi bazala maximă, și se va implementa aceasta în pompă și în preferințe
+ Se va începe modul buclă închisă cu funcția Suspendare la Glicemie Mică
+ Rulează în mod buclă închisă cu max IOB = 0 pentru câteva zile, fără prea multe evenimente LGS (Suspendare la Glicemii Mici)
+ Îmbunătățirea buclei închise, mărirea valorii max IOB peste 0 și scăderea graduală a țintelor de glicemie
+ Se rulează pentru câteva zile și cel puțin o noapte fără a avea alarme de glicemie mică înainte de scăderea țintei
+ Ajustarea bazalelor și a factorilor dacă este necesar și apoi activarea auto-sens
+ O săptămână de buclă închisă încheiată cu succes în condițiile introducerii regulate a carbohidraților
+ Activarea unor facilități adiționale pentru funcționarea în timpul zilei, cum ar fi advanced meal assist
+ Se activează opțiuni pentru uzul în timpul zilei, cum ar fi SMB
+ Trebuie sa citiți wiki și să măriți maxIOB pentru a obține SMB corect! Un start bun este maxIOB=media bolusurilor + 3x maxima bazalei din zi
+ Glicemie disponibilă în NS
+ Starea pompei disponibilă în NS
+ Acțiuni manuale
+ Îndeplinit: %1$s
+ Învățați cum se controlează AndroidAPS
+ Faceți diferite acțiuni în AndroidAPS
+ Stabiliți profilul 90% pentru 10 min (apăsare prelungă a numelui profilului în Vedere de ansamblu)
+ Simularea unui duș. Deconectarea pompei pentru 1 oră (Apăsare prelungă pe Buclă deschisă)
+ ... și reconectare în același mod
+ Creați ținte temporare personalizate pentru o durată de 10 min (apăsare prelungă pe ținta curentă)
+ În Generatorul de Configurații activați facilitatea Acțiuni, făceți-o vizibilă și afișați-i conținutul folosind meniul de sus
+ Afișați conținutul facilității Buclă
+ Folosiți funcția scală prin apăsarea prelungă a graficului glicemiei
+ Introduceţi
+ Cod acceptat
+ Cod invalid
+ Dovediți-vă cunoștințele
+ Studiați și răspundeți corect la întrebări
+ Răspuns greșit!
+ Următoarea nefinalizată
+ Solicită codul: %1$s
+ (bifați toate răspunsurile corecte)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Nu există conexiune la internet
+ Nu s-a reușit preluarea timpului
+ Nu au fost îndeplinite cerințele obiectivului
+
+ %1$d zi
+ %1$d zile
+ %1$d zile
+
+
+ %1$d oră
+ %1$d ore
+ %1$d ore
+
+
+ %1$d minut
+ %1$d minute
+ %1$d minute
+
+
diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml
index 2d8add15b1..caff1bb1a7 100644
--- a/app/src/main/res/values-ro-rRO/strings.xml
+++ b/app/src/main/res/values-ro-rRO/strings.xml
@@ -5,7 +5,6 @@
-
Setări siguranță tratamentBolus maxim admis [U]Carbohidrați admiși maxim [g]
@@ -57,9 +56,6 @@
Monitorizează și controlează aplicația AndroidAPS folosind smartwatchul WearOS.Afișează informații privind starea buclei pe watchface-ul xDrip+.Controlare de la distanță a AndroidAPS folosind comenzi date prin SMS.
- Înapoi
- Start
- VerificăUnitățiDIAIC
@@ -177,9 +173,6 @@
Versiune incompatibilă de NSClientVersiune incompatibilă de NightscoutNSClient nu este instalat. Înregistrare pierdută!
- Glicemie disponibilă în NS
- Starea pompei disponibilă în NS
- Acțiuni manualeBUCLĂ DEZACTIVATĂ DATORITĂ CONSTRÂNGERILORIOB bazalăConstrângere de bolus aplicată
@@ -222,7 +215,7 @@
Bazală temporarăBolus extinsVersiune Nightscout:
- Lipsă
+ Lipsă %1$dgAm exportat preferințeleExportă setările cătreImportă setările din
@@ -317,21 +310,6 @@
STOP APĂSATSe așteaptă pompaSe va livra un bolus de %1$.2fU
- Se stabilesc vizualizările și monitorizarea și se analizează bazalele și valorile ratelor
- Verificați că vedeți glicemia în Nightscout și că datele despre insulină date de pompă sunt înregistrate în site
- Pornire cu buclă deschisă
- Funcționare în modul Buclă Deschisă pentru câteva zile și introducere manuală a multiplelor sugestii de bazale temporare. Se stabilesc și se folosesc ținte temporare și ținte implicite (e.g. pentru activități sau pentru carbohidrați de corecție)
- Se va înțelege modul de lucru în buclă deschisă, inclusiv recomandările de bazale temporare
- Pe baza experienței, se va decide care va fi bazala maximă, și se va implementa aceasta în pompă și în preferințe
- Se va începe modul buclă închisă cu funcția Suspendare la Glicemie Mică
- Rulează în mod buclă închisă cu max IOB = 0 pentru câteva zile, fără prea multe evenimente LGS (Suspendare la Glicemii Mici)
- Îmbunătățirea buclei închise, mărirea valorii max IOB peste 0 și scăderea graduală a țintelor de glicemie
- Se rulează pentru câteva zile și cel puțin o noapte fără a avea alarme de glicemie mică înainte de scăderea țintei
- Ajustarea bazalelor și a factorilor dacă este necesar și apoi activarea auto-sens
- O săptămână de buclă închisă încheiată cu succes în condițiile introducerii regulate a carbohidraților
- Activarea unor facilități adiționale pentru funcționarea în timpul zilei, cum ar fi advanced meal assist
- Se activează opțiuni pentru uzul în timpul zilei, cum ar fi SMB
- Trebuie sa citiți wiki și să măriți maxIOB pentru a obține SMB corect! Un start bun este maxIOB=media bolusurilor + 3x maxima bazalei din ziAți atins limita permisăNiciun profil selectatBucla a fost dezactivată
@@ -569,8 +547,6 @@
Activați indicatori pentru CAGE, IAGE, SAGE, nivel baterie și rezervor pe ecranul principal.Pragul de avertisment pentru insulina din rezervor [U]Pragul critic al nivelului insulinei în rezervor [U]
- Pragul de avertizare nivel baterie [%%]
- Pragul critic al nivelului baterie [%%]IOBCOBFirmware
@@ -864,8 +840,6 @@
Lipsă SchimbareProfil. Efectuați o schimbare de profil sau apăsați \"Activare profil\" în ProfilulLocal.Total bolusuriTotal RBTuri
- Obiectivul %1$d nu a fost asumat
- Obiectivul %1$d nu a fost atinsPompa nu suportă bazale temporareNu s-a citit o rată bazală validă din pompăModul buclă închisă dezactivat în preferințe
@@ -987,7 +961,6 @@
Finalizat cu succes!Încă incompletTimp scurs
- Obiectiv %1$dPoctechCitire a valorii glicemiei din aplicația PoctechÎnregistrează valorile glicemiei din aplicația Tomato (dispozitiv MiaoMIao)
@@ -1171,8 +1144,6 @@
Înregistrează bazalele temporareÎnregistrează schimbările de profil, țintele temporareÎnregistrează testările de glicemie
- Schimbare oră vară/iarnă în mai puțin de 24h
- Schimbare oră vară/iarnă în mai puțin de 3 ore - buclă dezactivatărestricție de stocare internăEliberați cel puțin %1$d MB din spațiunl de stocare al telefonlui! Buclă dezactivată!Format greșit
@@ -1298,6 +1269,7 @@
NepornitSe inițializează RileyLink…Eroare RileyLink
+ Se îmbunătățește RileyLink și pompaProbleme la conectarea cu pompaConectat
@@ -1367,6 +1339,15 @@
Preia bazala temporarăSetează bazala temporarăSetează bolusul
+ Schimbă profilul în
+ Schimbă profilul la %1$s
+ Ultima conexiune la pompă
+ Ultima conexiune la pompă [minute în urmă]
+ Ultima conexiune la pompă %1$s %2$s minute în urmă
+ Trimite SMS: %1$s
+ Trimite SMS la toate numerele prestabilite
+ Trimite SMS cu text
+ %2$+.2fU]]>Restricție de bolus aplicată: %2$.2fU la %3$.2fU]]>!!!!! A fost detectată o absorbție lentă a carbohidraților: %2$d%% din timp. Reverificați calculele. COB poate fi supraestimat, astfel că este posibilă administrarea de mai multă insulină !!!!!]]>%1$.0f / %2$d U
@@ -1374,41 +1355,17 @@
Wizard bolus face un calcul, dar numai o parte din insulina calculată este și livrată. Este mai eficient când se folosește cu algoritmul SMB.Se încarcă ...Amână
- Îndeplinit: %1$s
- Învățați cum se controlează AndroidAPS
- Faceți diferite acțiuni în AndroidAPS
- Stabiliți profilul 90% pentru 10 min (apăsare prelungă a numelui profilului în Vedere de ansamblu)
- Simularea unui duș. Deconectarea pompei pentru 1 oră (Apăsare prelungă pe Buclă deschisă)
- ... și reconectare în același mod
- Creați ținte temporare personalizate pentru o durată de 10 min (apăsare prelungă pe ținta curentă)
- În Generatorul de Configurații activați facilitatea Acțiuni, făceți-o vizibilă și afișați-i conținutul folosind meniul de sus
- Afișați conținutul facilității Buclă
- Folosiți funcția scală prin apăsarea prelungă a graficului glicemiei
- Introduceţi
- Introduceți codul obținut de la dezvoltatori pentru a sări peste restul obiectivelor
- Cod acceptat
- Cod invalid
- Dovediți-vă cunoștințele
- Studiați și răspundeți corect la întrebări
- Răspunsul este dezactivat pentru: %1$s
- Răspuns greșit!
- Următoarea nefinalizată
+ Interval de timp
+ Timpul este între %1$s și %2$s
+ Între Închide
- Solicită codul: %1$s
- (bifați toate răspunsurile corecte)
-
- %1$d zi
- %1$d zi
- %1$d zile
-
-
- %1$d oră
- %1$d oră
- %1$d ore
-
-
- %1$d minut
- %1$d minut
- %1$d minute
-
+ Se mărește valoarea bazalei maxime deoarece setarea este mai joasă decât bazala maximă din profil
+ Conținutul mesajului nu este valid
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Asistent bolusare
+ min
+ %1$dg
diff --git a/app/src/main/res/values-ru-rRU/exam.xml b/app/src/main/res/values-ru-rRU/exam.xml
index bf19dfd648..cccb9912e5 100644
--- a/app/src/main/res/values-ru-rRU/exam.xml
+++ b/app/src/main/res/values-ru-rRU/exam.xml
@@ -3,65 +3,66 @@
Что верно о длительности работы инсулина DIA?Тема: продолжительность действия инсулина DIA
- Предустановленный минимум составляет 3 часа.
- Предустановленный минимум составляет 5 часов.
+ Минимальное значение 3 часа.
+ Минимальное значение 5 часов.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
- Он равен параметру продолжительность действия инсулина DIA помпы.
+ Равно параметру продолжительность действия инсулина DIA помпы.Следует определить свое индивидуальное значение (но не менее 5 часов).Тема: Временная цель Hypo
- Почему полезно установить временную цель hypo TT?
- Предотвратить падение ГК.
- Помочь восстановиться после низкой ГК.
- Предотвратить введение микроболюса SMB после подъёма ГК от быстрых углеводов.
+ Что является основной причиной для установки временной цели TT гипо?
+ Предотвратить падение ГК, если уже запущен нулевой временный базал.
+ Чтобы AAPS не давал слишком много инсулина после роста, вызваного быстродействующими углеводами данными на купирование гипо.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.htmlКакой профиль можно применить и настроить в автономном режиме?Тема: Автономный профильПрофилем NS можно пользоваться, но не настраивать.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profileТема: Отключение от помпы
- Что делать, когда снимается помпа?
- Дайте алгоритму знать, что инсулин не подается, нажав на отключиться от помпы.
- Не менять ничего в работе алгоритма, просто снять помпу.
+ Что следует делать при отсоединении помпы?
+ Нажать «Отключить помпу», чтобы AAPS знал, что инсулин не подается.
+ Нажать \'Приостановить цикл\', чтобы AAPS перестал выполнять цикл, когда помпа отсоединена.
+ Ничего не менять в AAPS, просто отключить помпу.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settingsТема: Параметры AndroidAPSКак эффективнее сохранить свои настройки?Локально экспортировать их из меню Обслуживание.Хранить экспортированный файл в другом месте, например, отправив по электронной почте, Dropbox, Google drive…Экспортировать их сразу после установки AAPS.
- Экспортировать их после каждого изменения параметра.
+ Экспортировать их после внесения изменений в параметры.
+ Экспортировать их после завершения цели.Экспортировать их при завершении начальной настройки.https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.htmlhttps://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-meТема: Зашумленные данные мониторинга
- Что делать, если наблюдаются шумы данных?
+ Что следует делать, если данные мониторинга зашумлены?Ничего, алгоритм AAPS сам справится с этим.
- Приостановить режим замкнутого цикла, чтобы избежать избыточной дозировки.
+ Отключите цикл, чтобы избежать чрезмерной дозировки.Заменить сенсор.Выключить телефон.https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
- Проверить, сглаживаются ли данные в приложении мониторинга.
+ Убедитесь, что приложение мониторинга сглаживает данные ГК.Тема: НагрузкиКак помочь системе справиться с физическими нагрузками?
- Задать временную цель Нагрузка.
+ Использование функции временная цель TT.Задать профиль ниже 100%.Задать профиль выше 100%.Остановить цикл.Задать временную цель Нагрузка перед началом активности.
- Задайте временную цель Нагрузка после начала активности.
+ Установка временной цели TT после начала активности приводит к худшим результатам, чем если бы была задана заранее.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
- Тема: Приостановка замкнутого цикла
- Получаю ли я инсулин, когда цикл приостановлен?
- Да, обычную базу.
+ Тема: Отключение/приостановка цикла
+ Получаю ли я инсулин, когда цикл отключен/приостановлен?
+ Да, базальный инсулин продолжает подаваться.Нет, подача инсулина прекращается.Тема: Определение базальной скорости, чувствительности к инсулину ISF и соотношения инсулин- углеводы ICКогда следует определить значения базала, ISF и IC?Перед тем, как начать пользоваться AAPS.
- При регулярных гипо ГК.
- При регулярных гипер ГК.
+ При частых низких ГК.
+ При частых высоких ГК.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settingsТема: Предварительные требованияЧто необходимо?
- Задать правильный профиль (база, IC, ISF, DIA).
+ Проверенные данные профиля (базал, инс-углеводы IC, фактор чувствительности к инсулину ISF, длительность действия инсулина DIA).Компьютер для создания APK.Поддерживаемый телефон.Автомобиль.
@@ -69,7 +70,7 @@
Учетная запись Tidepool.Учетная запись Google.Учетная запись Github.
- Требуется быть разработчиком Android.
+ Опыт разработки Android.Помпа MiniMed 670G.https://androidaps.readthedocs.io/en/latest/EN/Module/module.htmlСмарт часы.
@@ -77,15 +78,15 @@
Тема: Обновление AndroidAPSЧто верно?Вы должны иметь установленный Git.
- Обновлять, как только выходит новая версия.
- Можно использовать те же ключи подписи.
+ Обновлять, как только выпускается новая версия и есть достаточно времени для этого.
+ Следует использовать те же ключи подписи.Никогда не обновлять, если система работает хорошо.Попросить новую версию APK у друга.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branchТема: Устранение неполадокКуда обращаться за помощью?Присоединиться к группе AndroidAPS на Facebook.
- Перейти на страницу документации AndroidAPS Wiki.
+ Читайте документацию AndroidAPS.Посетить чат Gitter AndroidAPS.Посетить поддержку AndroidAPS GoogleПоговорить с эндокринологом.
@@ -94,20 +95,20 @@
https://gitter.im/MilosKozak/AndroidAPS
Context | Edit Context
- Тема: Инсулин
+ Тема: Модули инсулинаКакой тип инсулина можно использовать с модулем Ultra-Rapid-Oref?Fiasp®Новорапид®Хумалог®Актрапид®https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
- Тема: Модуль Чувствительность
- Какой модуль чувствительности имеет задаваемый пользователем диапазон времени для обнаружения?
+ Тема: Модули чувствительности
+ Какой алгоритм чувствительности имеет настраиваемый диапазон времени?https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.htmlКакой модуль чувствительности должен использоваться для функции UAM?
- Тема: Неверный ввод углеводов
- Вы видите, что неправильно ввели углеводы. Ваши действия?
- Перейти в раздел лечения/назначений, удалить неправильные углеводы и ввести новые углеводы.
+ Тема: Ошибки записи углеводов
+ Что нужно делать, если сделан неправильный ввод углеводов?
+ На вкладке Лечение/назначения удалите неправильные записи углеводов. Вводите новые углеводы.Добавить фиктивный инсулин с помощью функции ЗаполнениеТема: Продукты с содержанием жиров и белковЧто делать, если ваша еда содержит большое количество жиров и/или белков?
@@ -115,27 +116,27 @@ Context | Edit ContextПересчитать жир и белки в углеводах и добавить их в калькулятор болюса.Использовать пролонгированный болюс для покрытия жиров и белков.https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
- Тема: Детский мониторинг
+ Тема: Удаленный мониторингКак можно дистанционно отслеживать AAPS вашего ребенка?С помощью сайта Nightscout.
- Приложение Dexcom Follow, если вы используете оригинальное приложение Dexcom.
+ Приложение Dexcom Follow, если вы используете оригинальное приложение Dexcom (только ГК).Dexcom Follow, если вы используете приложение xDrip.xDrip в режиме follower.Приложения Loop на iPhone.Приложения Spike на iPhone.https://androidaps.readthedocs.io/en/latest/EN/Children/Children.htmlТема: Коэффициент чувствительности к инсулину
- Повышение значения ISF приведет к снижению подачи инсулина, если пытаться снизить ГК при помощи мастера болюса.
- Понижение значения ISF приведет к снижению подачи инсулина, если пытаться снизить ГК при помощи мастера болюса.
- Изменение ISF не влияет на количество инсулина, подаваемое AAPS при попытке исправить гипергликемию.
+ Более высокие значения ISF приводят к меньшей подаче инсулина, когда AAPS исправляет высокую ГК.
+ Более низкие значения ISF приводят к меньшей подаче инсулина, когда AAPS исправляет высокую ГК.
+ Изменение значений ISF никак не влияет на количество инсулина, подаваемого AAPS при коррекции высокой ГК.Необходимо ввести ISF в Настройках.Изменение значения ISF в профиле достаточно для применения изменений.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-uhttps://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.htmlТема: Сотношение инсулин-углеводы IC
- Увеличение значения IC приведет к уменьшению подачи инсулина на то же количество углеводов.
- Уменьшение значения IC приведет к уменьшению подачи инсулина на то же количество углеводов.
- Предположим, у вас 0 углеводов COB. Изменение IC приведет к другому количеству инсулина на исправление ГК.
+ Более высокие коэффициенты инсулин-углеводы IC приводят к уменьшению инсулина на данное количество углеводов.
+ Более низкие коэффициенты инсулин-углеводы IC приводят к уменьшению инсулина на данное количество углеводов.
+ Если у вас 0 активных углеводов COB, изменение соотношения инсулин-углеводы IC приведет к иному количеству инсулина на коррекцию данной ГК.Соотношение инсулин-углеводы изменится если принимать ХЕ за 10 или 12г.Смысл соотношения инсулин-углеводы IC таков: сколько хлебных единиц покрываются одной ед. инсулина.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
@@ -152,16 +153,19 @@ Context | Edit ContextЦелевое значение ГК будет на 10% ниже.Только нижняя цель будет ниже на 10%.https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
- Я хочу переключить профиль, из-за того, что мне надо проснуться на 1 час раньше, чем обычно, чтобы совместить переход времени с переключением профиля. Какую величину я должен использовать?
- 1
- -1
+ Если вы просыпаетесь на 1ч раньше, чем обычно, как вы должны уведомлять AAPS об изменении вашего графика?
+ Выполнить переключение профиля со сдвигом времени 1
+ Выполнить переключение профиля со сдвигом времени -1https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
- 60
- -60
+ Выполнить переключение профиля со сдвигом времени 60
+ Выполнить переключение профиля со сдвигом времени -60https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapyТема: Скорость базала. СправкаКуда обращаться за помощью по скорости базала и т. д.Ваши эндокринологиGoogleFacebook
+ Другие препараты
+ ААPS понижает базал, чтобы повысить уровень сахара в крови. Препараты из группы ингибиторов SGLT2 (глифлозинов) могут предотвратить ожидаемый рост ГК и, следовательно, привести к опасной недостаточности инсулина (диабетическому кетоацитозу DKA).
+\nНаиболее распространенные коммерческие наименования:® Invokana, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\n Настоящим подтверждаю, что не буду принимать такие препараты при использовании AAPS или буду отключать AAPS перед их употреблением.
diff --git a/app/src/main/res/values-ru-rRU/objectives.xml b/app/src/main/res/values-ru-rRU/objectives.xml
new file mode 100644
index 0000000000..97fac47306
--- /dev/null
+++ b/app/src/main/res/values-ru-rRU/objectives.xml
@@ -0,0 +1,74 @@
+
+
+
+ Назад
+ Старт
+ Подтвердить
+ %1$d. Цель
+ Цель %1$d не начата
+ Цель %1$d не завершена
+ Настройка визуализации и мониторинга, анализ базала и коэффициентов
+ Убедитесь, что BG доступен в Nightscut, и данные инсулина помпы загружаются
+ Старт незамкнутого цикла
+ Начинайте работу в режиме незамкнутого цикла и ручной подстройки величины временного базала. Установите и применяйте временные цели и временные цели по умолчанию (напр. углеводы при нагрузке или купировании гипо)
+ Глубже понимаем незакольцованную систему Open Loop, включая ее рекомендации по временным базалам
+ На основе полученного опыта определияем макс величину базала и вводим ее в помпу и настройки
+ Начинаем замыкать цикл с Low Glucose Suspend (прекращением подачи инсулина на низких сахарах)
+ Работа в замкнутом цикле с макс активным инсулином IOB = 0 на протяжении нескольких дней избегая событий типа приостановка на низких ГК Low Suspend
+ Настройка замкнутого цикла с поднятием макс величины IOB выше 0 и постепенным понижением целевой ГК
+ Работа несколько дней и по кр мере одну ночь без срабатывания оповещений о низкой ГК
+ Настраиваем базал и коэффициенты с последующей активацией auto-sens
+ 1 неделя успешной дневной работы с регулярным введением углеводов
+ Активация таких доп функций для дневного времени как расширенный калькулятор болюса advanced meal assist
+ Активация таких доп функций для дневного времени как супер микро болюс SMB
+ Прочтите wiki и увеличьте maxIOB чтобы супер микро болюс SMB заработал как положено! Хорошее начало – maxIOB = средний болюс на еду + троекратный максимальный суточный базал
+ гликемия доступна в NS
+ Статус помпы доступен в NS
+ Ввод вручную
+ Выполнено: %1$s
+ Научитесь контролировать AndroidAPS
+ Выполняйте различные действия в AndroidAPS
+ Установите профиль 90% на 10 мин (Долгое нажатие на имя профиля на главном экране)
+ Имитация душа. Отключите помпу на 1ч (Долгое нажатие на Открытый цикл Open Loop)
+ ... и обратное подключение таким же способом
+ Создайте настраиваемую временную цель длительностью 10 мин. (Долгое нажатие на текущую цель)
+ В Конфигураторе активируйте модуль Действия Actions, сделав его видимым и показав содержимое верхнего меню
+ Просмотр содержимого модуля Цикл Loop
+ Применить функцию масштабирования по долгому нажатию на диаграмму ГК
+ Ввод
+ Если прежде вы были пользователем OpenAPS и имеете в NS не менее 3 месяцев данных, отправьте электронное письмо на objectives@androidaps.org с вашим адресом NS и запросом кода для обхода остальных целей. Введите код, полученный от разработчиков
+ Код принят
+ Неверный код
+ Подтвердите ваши знания
+ Изучите вопросы и дайте точные ответы
+ Ответы отключены до: %1$s
+ Неверный ответ!
+ Следующий незавершенный
+ Код запроса: %1$s
+ (отметьте все правильные ответы)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Нет подключения к Интернету
+ Не удалось загрузить время
+ Требования к цели не выполнены
+
+ %1$d день
+ %1$d дня
+ %1$d дней
+ %1$d д
+
+
+ %1$d час
+ %1$d часа
+ %1$d часов
+ %1$d ч
+
+
+ %1$d минута
+ %1$d минут(ы)
+ %1$d минут
+ %1$d мин
+
+
diff --git a/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/values-ru-rRU/strings.xml
index 65bc0f30f0..67834cd608 100644
--- a/app/src/main/res/values-ru-rRU/strings.xml
+++ b/app/src/main/res/values-ru-rRU/strings.xml
@@ -5,7 +5,6 @@
-
Безопасность терапииМакс разрешенный болюс [U] ед.макс разрешенные углеводы (г)
@@ -57,9 +56,6 @@
Мониторить и контролировать AndroidAPS при помощи часов WearOS.Показать информацию о работе алгоритма ИПЖ на экране смарт-часов xDrip+.Дистанционное управление AndroidAPS при помощи команд SMS.
- Назад
- старт
- ВерификацияединицыDIA (время действия инсулина)IC (инсулин/углеводы):
@@ -102,6 +98,7 @@
профильданные приема пищирезультат
+ Результат: %1$s %2$sданные гликемии недоступныизменения не запрошенызапрос
@@ -177,9 +174,6 @@
неподдерживаемая версия NSClientНеподдерживаемая версия Nightscoutотключите \"только передача в NS\" чтобы активировать эту опцию
- гликемия доступна в NS
- статус помпы доступен в NS
- ввод вручнуюЗЦ ОТМЕНЕН ОГРАНИЧЕНИЯМИбазал IOBприменено ограничение болюса
@@ -208,7 +202,7 @@
сенсоруглеводыинсулин
- Время действия углеводов
+ Подождать до едыразбивкаДлительность действияпроцент
@@ -222,7 +216,7 @@
ВремБазалрасширенный болюсверсия Nightscout:
- отсутствует
+ Отсутствует %1$dgнастройки экспортированыэкспортировать настройки вимпортировать настройки из
@@ -266,11 +260,23 @@
разрешенные телефонные номера+ XXXXXXXXXX; + YYYYYYYYYYЧтобы подать болюс %1$.2fU ответьте кодом %2$s
+ Чтобы подать болюс %1$.2fU ответьте кодом %2$s
+ Чтобы установить временную цель %1$s ответьте кодом %2$s
+ Чтобы отменить временную цель ответьте кодом %1$s
+ Чтобы отключить службу удаленных SMS-сообщений ответьте кодом %1$s.\n\n Имейте в виду, что вы сможете вновь активировать ее только с основного телефона AAPS.
+ Удаленная служба SMS остановлена. Для ее реактивации используйте AAPS на главном смартфоне.чтобы отправить калибровку %1$.2f ответьте кодом %2$sПодача болюса не состоялась
+ Минимальное количество минут между одним удаленным болюсом и следующим
+ Минимум минут, должных пройти между одним болюсом и следующим
+ В целях безопасности, для изменения этого параметра необходимо добавить не менее 2 телефонных номеров.Болюс %1$.2fед. подан успешноНачинается подача болюса %1$.2fед.Болюс %1$.2fед. подан успешно
+ Болюс на еду %1$.2f ед. подан успешно
+ Цель %1$s на %2$d минут
+ Цель %1$s на %2$d минут установлена успешно
+ Временная цель успешно отмененаПодается болюс %1$.2fед.разрешить команды через смспалец
@@ -304,7 +310,7 @@
гликемияПерезаправкаОстанов
- Связь установлена за %1$d сек
+ Попытка установить связь: %1$d секпароль помпыневерный пароль помпыпомпа занята
@@ -317,21 +323,6 @@
нажат стопожидание помпыНачинается подача болюса %1$.2fед.
- настройка визуализации и мониторинга, анализ базала и коэффициентов
- убедитесь что СК и данные помпы передаются в NS
- Старт незамкнутого цикла
- Начинайте работу в режиме незамкнутого цикла и ручной подстройки величины временного базала. Установите и применяйте временные цели и временные цели по умолчанию (напр. углеводы при нагрузке или купировании гипо)
- Глубже понимаем незакольцованную систему Open Loop, включая ее рекомендации по временным базалам
- На основе полученного опыта определияем макс величину базала и вводим ее в помпу и настройки
- Начинаем замыкать цикл с Low Glucose Suspend (прекращением подачи инсулина на низких сахарах)
- Работа в замкнутом цикле с макс активным инсулином IOB = 0 на протяжении нескольких дней избегая событий типа приостановка на низких ГК Low Suspend
- Настройка замкнутого цикла с поднятием макс величины IOB выше 0 и постепенным понижением целевой ГК
- Работа несколько дней и по кр мере одну ночь без срабатывания оповещений о низкой ГК
- Настраиваем базал и коэффициенты с последующей активацией auto-sens
- 1 неделя успешной дневной работы с регулярным введением углеводов
- Активация таких доп функций для дневного времени как расширенный калькулятор болюса advanced meal assist
- Активация таких доп функций для дневного времени как супер микро болюс SMB
- Прочтите wiki и увеличьте maxIOB чтобы супер микро болюс SMB заработал как положено! Хорошее начало – maxIOB = средний болюс на еду + троекратный максимальный суточный базалразрешенный предел достигнутпрофиль не выбранзцикл был деактивирован
@@ -345,10 +336,13 @@
Чтобы подать базал %1$.2fед./ч в течение %2$d мин. ответьте кодом %3$sДля переключения профиля на %1$s %2$d%% ответьте кодом %3$sДля начала подачи пролонгированного болюса %1$.2fед. за %2$d мин. ответьте кодом %3$s
+ Чтобы ввести %1$d г в %2$s ответьте кодом %3$sДля начала подачи базала %1$d%% на %2$d мин. ответьте кодом %3$sдля приостановки цикла на %1$d мин ответьте кодом %2$sврем базал %1$.2fU/h на %2$d мин начат успешноПролонгированный болюс %1$.2fед. на %2$d мин. начат успешно
+ Углеводы %1$d г введены успешно
+ Не удалось ввести %1$d г углеводовВрем. базал %1$d%% на %2$d мин. начат успешнонеуспех старта врем базалаНе удалось начать подачу пролонгированного болюса
@@ -569,8 +563,8 @@
Включить на главном экране подробные индикаторы отработанного времени для канюли помпы, инсулина, сенсора, резервуара, а также уровня заряда батареи.Порог уровня наполненности резервуара для оповещения [ед.]Порог критического уровня наполненности резервуара [U]
- Порог предупреждения о разрядке батареи [%%]
- Порог предупреждения о критическом уровне разрядки батареи [%%]
+ Порог предупреждения о разрядке батареи [%]
+ Порог предупреждения о критическом уровне разрядки батареи [%]IOB акт инсакт углевпрошивка
@@ -701,6 +695,7 @@
граммминутч
+ дн]]>кДжЭнергия
@@ -729,6 +724,7 @@
Параметры загрузки СКПоказать подробно дельтуПоказать дельту еще с одним десятичным знаком
+ Максимум минут микроболюса SMBВерхний лимит минут базала на SMBНеподдерживаемая версия прошивки помпыОтправить данные СК на xDrip+
@@ -864,8 +860,6 @@
Профиль не переключен. Пожалуйста переключите профиль или нажмите \"активировать профиль\" в LocalProfile.Отсчет болюсаОтсчет временного базала TBR
- Цель %1$d не запущена
- Цель %1$d не завершенаЭта помпа не рассчитана на подачу временного базалаНа помпе не найдены валидные записи о базалахРежим замкнутого цикла отключен в настройках
@@ -989,7 +983,6 @@ Context | Edit ContextЗавершено, отлично!Не завершеноПрошло времени
- %1$d. ЦельPoctechПолучать данные гликемии от приложения PoctechПолучать значения ГК от приложения Tomato (устройство MiaoMiao)
@@ -1174,7 +1167,7 @@ Context | Edit ContextЗагрузить переключения профиля, временные целиЗагрузить тесты ГКПереход на летнее/зимнее время через 24 часа или менее
- Переход на летнее время меньше 3 часов назад - Замкнутый цикл отключен
+ Изменение сезонного времени произошло меньше 3 часов назад-Закрытый цикл выключенограничение по объему карты памятиОсвободите по крайней мере %1$d MB из внутренней памяти! Цикл остановлен!Неверный формат
@@ -1262,6 +1255,8 @@ Context | Edit ContextНе выбрано (Простой вид)Щелочная (Подробный вид)Литиевая (Подробный вид)
+ NiZn (Подробный вид)
+ Отладка Болюс/НазначенияСКАНСТОП
@@ -1370,6 +1365,14 @@ Context | Edit ContextПолучить временный базалУстановить временный базалНастроить болюс
+ Изменить профиль на
+ Изменить профиль на %1$s
+ Последнее соединение с помпой
+ Последняя связь с помпой [ мин. назад]
+ Последняя связь с помпой %1$s %2$sмин. назад
+ Отправить SMS: %1$s
+ Отправьте SMS на все настроенные номера
+ Отправить SMS с текстом%2$+.2fед]]>Применено ограничение на болюс: %2$.2fед до %3$.2fед]]>!!!!! Обнаружено медленное всасывание углеводов: %2$d%% времени. Еще раз проверьте свои расчеты. Возможно акт углеводы COB вне диапазона и может быть подано больше инсулина!!!!!]]>
@@ -1378,44 +1381,19 @@ Context | Edit ContextМастер болюса выполняет расчет, но подана только эта часть рекомендуемого инсулина. Полезно с алгоритмом SMB.Загрузка...Отложить
- Выполнено: %1$s
- Научитесь контролировать AndroidAPS
- Выполните различные действия в AndroidAPS
- Установите профиль 90% на 10 мин (Долгое нажатие на имя профиля на Обзор)
- Имитация душа. Отключите помпу на 1ч (Долгое нажатие на Open Loop)
- ... и снова подключитесь таким же способом
- Создайте настраиваемую временную цель длительностью 10 мин. (Долгое нажатие на текущую цель)
- В Конфигураторе включите плагин Actions, сделав его видимым и показав содержимое верхнего меню
- Показывать содержимое расширения ИПЖ
- Применить функцию масштабирования по долгому нажатию на диаграмму ГК
- Ввод
- Введите код, полученный от разработчиков, чтобы обойти остальные цели
- Код принят
- Неверный код
- Подтвердите ваши знания
- Изучите вопросы и дайте точные ответы.
- Рассмотрение ответов приостановлено на: %1$s
- Неправильный ответ!
- Следующий незавершенный
+ Диапазон времени
+ Время между %1$s и %2$s
+ Между Закрыть
- Запросить код
- (проверить ответы)
-
- %1$d день
- %1$d дня
- %1$d дней
- %1$d дня
-
-
- %1$d час
- %1$d часа
- %1$d часов
- %1$d часа
-
-
- %1$d минута
- %1$d минуты
- %1$d минут
- %1$d минут
-
+ Повышаю максимальное значение базы т. к. оно меньше, чем максимальное значение в профиле
+ Недопустимое тело сообщения
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Мастер Болюса
+ мин
+ %1$d гр
+ Вкл.
+ Выкл.
diff --git a/app/src/main/res/values-sk-rSK/exam.xml b/app/src/main/res/values-sk-rSK/exam.xml
index 70489fbc5e..6bc806f51d 100644
--- a/app/src/main/res/values-sk-rSK/exam.xml
+++ b/app/src/main/res/values-sk-rSK/exam.xml
@@ -1,3 +1,169 @@
-
+
+ Čo je pravda o DIA?
+ Téma: Doba trvania účinku inzulínu
+ Minimálna hodnota je 3 hodiny.
+ Minimálna hodnota je 5 hodín.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#inzulin
+ Význam je rovnaký, ako parameter DIA používaný vo vašej pumpe.
+ Musíte určiť svoju, individuálnu hodnotu (ale nie menej ako 5 hodín).
+ Téma: Dočasný cieľ Hypo
+ Čo je hlavným dôvodom pre nastavenie dočasného cieľa Hypoglykémie?
+ Zabrániť nízkej glykémii, pokiaľ už je spustený nulový dočasný bazál.
+ Aby sa zabránilo AAPS podaniu príliš veľkého množstva inzulínu po vzostupe glykémie, spôsobenom rýchlymi sacharidmi použitými k liečbe hypoglykémie.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/temptarget.html
+ Ktorý profil je možné použiť a konfigurovať offline?
+ Téma: Offline profil
+ NS profil môže byť použitý, ale nenakonfigurovaný.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#profile
+ Téma: Odpojenie od pumpy
+ Čo je potrebné urobiť, pri odpojení pumpy?
+ Kliknite na \"Odpojiť pumpu\", aby AAPS vedelo, že nie je podávaný žiadny inzulín.
+ Kliknite na tlačítko \"Pozastaviť uzavretý okruh\", aby AAPS zastavil uzavretý okruh na dobu, kým je pumpa odpojená.
+ Nemeňte nič v AAPS, iba odpojte pumpu.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#dalsi-nastaveni
+ Téma: Nastavenie AndroidAPS
+ Aké sú odporúčané postupy pre zálohovanie Vašich nastavení?
+ Exportovať ich lokálne z menu Údržby.
+ Uložte exportovaný súbor na iné miesto, ako napr. E-mail, Dropbox, Google Drive...
+ Exportujte ich ihneď po inštalácii AAPS.
+ Exportujte ich po vykonaní zmien v nastaveniach.
+ Exportujte ich po dokončení cieľa.
+ Exportujte ich, akonáhle dokončíte úvodné nastavenia.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/ExportImportSettings.html
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#jake-vybaveni-pro-pripad-nouze-se-doporucuje-brat-s-sebou
+ Téma: Šum dát zo senzora
+ Čo je potrebné urobiť v prípade, že CGM dáta poskakujú?
+ Nič, uzavretý okruh si s tým poradí.
+ Zakážte uzavretý okruh, aby ste sa vyhli predávkovaniu inzulínom.
+ Vymeňte senzor.
+ Vypnúť telefón.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#vyhlazovani-zarusenych-dat-glykemii
+ Overte, že vaša aplikácia CGM vyhladzuje glykémie.
+ Téma: Šport a pohyb
+ Ako môžete pomôcť systému vysporiadať sa so športom a pohybom?
+ Použitie funkcie dočasný cieľ.
+ Prepnúť na profil pod 100 %.
+ Prepnúť na profil nad 100 %.
+ Zastaviť uzavretý okruh.
+ Nastaviť dočasný cieľ aktivity pred zahájením cvičenia.
+ Nastavenie dočasného cieľa aktivity až po zahájení cvičenia, vedie k horšiemu výsledku, ako v prípade, keby bol spustený dopredu.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/temptarget.html#docasny-cil-pri-pohybove-aktivite
+ Téma: Deaktivovaný/Pozastavený uzavretý okruh
+ Dostávam inzulín, keď je uzavretý okruh deaktivovaný/pozastavený?
+ Áno, bazálny inzulín je podávaný naďalej.
+ Nie, podávanie inzulínu je zastavené.
+ Téma: Testovanie bazálu, ISF a IC
+ Kedy mám overiť hodnoty bazálov, ISF a IC?
+ Predtým, ako začnem používať uzavretý okruh.
+ Pokiaľ máte často nízke glykémie.
+ Pokiaľ máte často vysoké glykémie.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#nastaveni-androidaps
+ Téma: Nevyhnutné predpoklady
+ Čo potrebujem?
+ Overené informácie o profile (Bazál, IC, ISF, DIA).
+ Počítač na vytvorenie APK.
+ Podporovaný telefón.
+ Auto.
+ Nightscout, kvôli splneniu cieľov.
+ Tidepool účet.
+ Google účet.
+ Github účet.
+ Skúsenosti s vývojom pre Android.
+ Pumpu MiniMed 670G.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Module/module.html
+ Inteligentné hodinky.
+ Podporovaný CGM.
+ Téma: Aktualizácia AndroidAPS
+ Čo je pravda?
+ Musíte mať nainštalovaný Git.
+ Aktualizujte hneď, akonáhle se uvoľní nová verzia a budete mať dostatok času na to, to urobiť.
+ Mali by ste používať rovnaké podpisové kľúče.
+ Nikdy neaktualizujte, pokiaľ systém funguje dobre.
+ Požiadajte kamaráta o novú verziu APK.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Installing-AndroidAPS/Update-to-new-version.html
+ Téma: Riešenie problémov
+ Kde hľadať pomoc?
+ Pripojte sa do facebookovej skupiny AndroidAPS.
+ Prečítajte si dokumentáciu AndroidAPS.
+ Navštívte miestnosť AndroidAPS na Gitter kanáli.
+ Navštívte Google podporu AndroidAPS
+ Porozprávajte sa so svojím diabetológom.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/index.html#poradce-pri-potizich
+ https://www.facebook.com/groups/AndroidAPSUsers/
+ https://gitter.im/MilosKozak/AndroidAPS
+ Téma: Inzulínové moduly
+ Aký druh inzulínu môže byť použitý s modulom \'Ultra-Rýchlý-Oref\'?
+ Fiasp®
+ NovoRapid®
+ Humalog®
+ Actrapid®
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#inzulin
+ Téma: Moduly citlivosti
+ Ktorý algoritmus citlivosti má konfigurovateľnú dobu detekcie?
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Configuration/Config-Builder.html#detekce-citlivosti
+ Ktorý modul citlivosti musí byť použitý pre funkciu UAM (rozpoznanie neoznámeného jedla)?
+ Téma: Chyby pri zadávaní sacharidov
+ Čo by ste mali urobiť, pokiaľ ste chybne zadali sacharidy?
+ V Ošetreniach odstráňte chybnú položku. Zadajte nové sacharidy.
+ Pridať falošný inzulín pomocou funkcie \"Plnenie/Doplňovanie\".
+ Téma: Jedlo s tukom a bielkovinami
+ Čo robiť, keď jedlo obsahuje veľké množstvo tukov a/alebo bielkovín?
+ Prepočítajte tuky a bielkoviny na sacharidy a použite funkciu „Rozložené sacharidy“.
+ Prepočítajte tuky a bielkoviny na sacharidy a pridajte ich do výpočtu bolusu.
+ Použite predĺžený bolus, aby ste pokryli tuky a bielkoviny.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Extended-Carbs.html
+ Téma: Vzdialené sledovanie
+ Ako môžete na diaľku monitorovať AAPS svojho dieťaťa?
+ Pomocou stránky Nightscout.
+ Dexcom follow aplikácia, pokiaľ používate originálnu aplikáciu Dexcom (iba hodnoty glykémie).
+ Aplikácia Dexcom Follow, pokiaľ používate aplikáciu xDrip.
+ Aplikácia xDrip v režime sledovania (Follower).
+ Aplikácia Loop na iPhone.
+ Aplikácia Spike na iPhone.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Children/Children.html
+ Téma: Citlivosť na inzulín
+ Vyššie hodnoty ISF vedú k menšej dávke inzulínu pri korigovaní vysokej glykémie.
+ Nižšie hodnoty ISF vedú k menšej dávke inzulínu pri korigovaní vysokej glykémie.
+ Zmena hodnoty ISF nemá vplyv na dávku inzulínu, keď AAPS koriguje vysokú glykémiu.
+ Musíte zadať citlivosť v Nastaveniach.
+ Zmena hodnoty citlivosti vo vašom profile stačí k tomu, aby se táto zmena použila.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#korekcni-faktor-citlivost-na-inzulin-isf-mmol-l-u-nebo-mg-dl-u
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html
+ Téma: Inzulíno-sacharidový pomer
+ Vyššie hodnoty IC vedú k menšej dávke inzulínu ku rovnakému množstvu sacharidov.
+ Nižšie hodnoty IC vedú k menšej dávke inzulínu ku rovnakému množstvu sacharidov.
+ Pokiaľ máte 0 COB, zmena inzulíno-sacharidového pomeru povedie k inému množstvu inzulínu vydanému pre korekciu glykémie.
+ Inzulíno-sacharidový pomer sa bude líšiť podľa toho, či počítate sacharidovú jednotku ako 10 g, alebo ako 12 g sacharidov.
+ Inzulíno-sacharidový pomer vyjadruje: koľko sacharidových jednotiek pokryje 1 jednotka inzulínu.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#inzulino-sacharidovy-pomer-cr-g-u
+ Téma: Prepínanie profilu
+ Keď v prepnutí profilu zadáte 90 %…
+ Bazály budú o 10 % vyššie.
+ Bazály budú o 10 % nižšie.
+ Hodnota inzulíno-sacharidového pomeru bude o 10 % vyššia.
+ Hodnota inzulíno-sacharidového pomeru bude o 10 % nižšia.
+ Hodnota citlivosti bude o 10 % vyššia.
+ Hodnota citlivosti bude o 10 % nižšia.
+ Celkovo dostanete o cca. 10 % inzulínu menej.
+ Cieľ bude o 10 % vyšší.
+ Cieľ bude o 10 % nižší.
+ Iba dolný cieľ bude o 10 % nižší.
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html?highlight=p%C5%99epnut%C3%AD%20profilu
+ Pokiaľ sa prebudíte o 1h skôr než obvykle, ako by ste mali oznámiť AAPS túto zmenu?
+ Urobte prepnutie profilu s posunom času 1
+ Urobte prepnutie profilu s posunom času -1
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Usage/Profiles.html#posun-casu
+ Urobte prepnutie profilu s posunom času 60
+ Urobte prepnutie profilu s posunom času -60
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Module/module.html#spravny-individualni-algoritmus-davkovani-pro-lecbu-vaseho-diabetu
+ Téma: Pomoc s bazálmi
+ Kam ísť pre pomoc s bazálmi a pod.
+ K Vášmu lekárovi
+ Google
+ Facebook
+ Iné Lieky
+ AAPS znižuje bazály na zvýšenie hladiny cukru v krvi. Lieky zo skupiny inhibítorov SGLT2 (gliflozíny) môžu zabrániť očakávanému zvýšeniu hodnoty glykémie a tak môžu produkovať nebezpečný nedostatok inzulínu (ketoacidózu).
+\nSpoločné značky sú: Invokana ®, Forxiga ®, Jardiance ®, Steglatro ®, Suglat ®, Apleway ®, Deberza ®, Synjardy ®, Vokanamet ®, Xigduo ®.\n\n. Týmto sľubujem, že tieto lieky neberiem pri používaní AAPS, alebo deaktivujem uzavretý okruh pred užívaním týchto liekov.
+
diff --git a/app/src/main/res/values-sk-rSK/objectives.xml b/app/src/main/res/values-sk-rSK/objectives.xml
new file mode 100644
index 0000000000..0b55a38e96
--- /dev/null
+++ b/app/src/main/res/values-sk-rSK/objectives.xml
@@ -0,0 +1,74 @@
+
+
+
+ Naspäť
+ Začiatok
+ Overenie
+ %1$d. Cieľ
+ Výukový cieľ %1$d nespustený
+ Výukový cieľ %1$d nedokončený
+ Nastaviť vizualizáciu a monitoring, analyzovať bazály a pomery
+ Skontrolovať, či sú glykémie a údaje z pumpy viditeľné v Nightscoute
+ Začať s otvoreným okruhom
+ Niekoľko dní používať otvorený okruh a ručne potvrdzovať doporučené dočasné bazály. Nastavovať a používať dočasné ciele (napr. pre šport, alebo hypo)
+ Porozumieť otvorenému okruhu, vrátane jeho doporučení ohľadne dočasných bazálov
+ Na základe predchádzajúcich skúseností rozhodnúť, aký je potrebný maximálny bazál a nastaviť ho v pumpe a v aplikácii
+ Spustiť uzavretý okruh iba zo zastavovaním pri nízkej glykémii
+ Spustiť uzavretý okruh s max IOB = 0 na niekoľko dní s minimom nutných korekcií na nízku glykémiu
+ Zapnúť uzavretý okruh, zvyšovať max IOB nad 0 a znižovať cieľovou glykémii
+ Používať uzavretý okruh niekoľko dní s aspoň jednou nocou bez alarmov na nízku glykémiu
+ Upraviť bazály a pomery, ak je to potrebné, a povoliť automatickú detekciu citlivosti na inzulín
+ Jeden týždeň úspešného používania s bežným príjmom sacharidov
+ Povolenie doplnkových funkcií pre každodenné použitie, ako napr. pokročilý asistent jedál (AMA)
+ Povoliť ďalšie funkcie pre bežné používanie ako SMB
+ Prečítať si dokumentáciu a zvýšiť maximálne IOB, aby mohlo správne fungovať SMB! Pre začiatok sa dá použiť veľkosť bežného bolusu + 3x maximálny denný bazál
+ Glykémia dostupná v NS
+ Stav pumpy dostupný v NS
+ Spustené manuálne
+ Splnené: %1$s
+ Naučte sa, ako ovládať AndroidAPS
+ Vykonávajte v AndroidAPS rôzne akcie
+ Nastavte profil na 90 % na 10 min (Dlhé stlačenie názvu profilu na obrazovke Prehľad)
+ Predstierajte, že se idete sprchovať. Odpojte pumpu na 1 h (Dlhšie pridržte tlačítko Otvorený okruh)
+ ...a rovnakým spôsobom ju znovu pripojte
+ Vytvorte vlastný dočasný cieľ s trvaním 10 min (Dlhšie pridržte aktuálny cieľ)
+ V Konfigurácii povoľte modul Akcie, aktivujte jeho zobrazenie a zobrazte jeho obsah z hornej ponuky
+ Zobrazte obsah modulu uzavretý okruh
+ Prepnite režim zobrazenia dlhým stlačením grafu glykémie
+ Zadať
+ Ak ste boli používateľom OpenAPS už predtým a Váš NS má dáta uzavretého okruhu za minimálne 3 mesiace, môžete nám zaslať E-mail na adresu objectives@androidaps.org z Vašou adresou NS a požiadať o kód na obídenie zvyšných cieľov. Zadajte kód získaný od vývojárov
+ Kód akceptovaný
+ Neplatný kód
+ Preukážte svoje znalosti
+ Preštudujte a správne odpovedajte na otázky
+ Odpovedanie zakázané do: %1$s
+ Nesprávna odpoveď!
+ Ďalšia nedokončená
+ Kód žiadosti: %1$s
+ (zaškrtnite všetky správne odpovede)
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/FAQ.html#co-delat-pri-sprchovani-a-koupani
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#hlavni-stranka
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#konfigurace
+ https://androidaps.readthedocs.io/en/latest/CROWDIN/cs/Getting-Started/Screenshots.html#hlavni-stranka
+ Nie ste pripojený k internetu
+ Vyčítanie času zlyhalo
+ Požiadavky cieľa nie sú splnené
+
+ %1$d deň
+ %1$d dní
+ %1$d dní
+ %1$d dní
+
+
+ %1$d hodina
+ %1$d hodín
+ %1$d hodín
+ %1$d hodín
+
+
+ %1$d minúta
+ %1$d minút
+ %1$d minút
+ %1$d minút
+
+
diff --git a/app/src/main/res/values-sk-rSK/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml
index d6e74001b5..bb559c8868 100644
--- a/app/src/main/res/values-sk-rSK/strings.xml
+++ b/app/src/main/res/values-sk-rSK/strings.xml
@@ -5,7 +5,6 @@
-
Bezpečnosť zadania ošetreniaMaximálny povolený bolus [JI]Maximálne povolené množstvo sacharidov [g]
@@ -57,9 +56,6 @@
Zobrazovanie stavu a riadenie AndroidAPS z hodiniek s WearOS.Zobraz informácie o uzavretom okruhu na xDrip+ watchface.Ovládaj na diaľku AndroidAPS použitím SMS príkazov.
- Naspäť
- Začiatok
- OverenieJednotkyDoba pôsobenia inzulínuInzulínovo-sacharidový pomer
@@ -102,6 +98,7 @@
ProfilDáta o jedleVýsledok
+ Výsledok: %1$s %2$sNedostupné dáta o glykémiáchNepožadovaná žiadna zmenaPožiadavka
@@ -118,12 +115,12 @@
NS ProfilJednoduchý profilDočasnýBazál
- Ošetrenie
+ OšetreniaVirtuálna pumpaStarostlivosťPumpaAkú pumpu chcete používať s AndroidAPS?
- Ošetrenie
+ OšetreniaAký modul chcete používať pre spracovanie ošetrení?ProfilAký profil má používať AndroidAPS?
@@ -177,9 +174,6 @@
Nepodporovaná verzia NS klientaNepodporovaná verzia NighscoutuNS klient nie je nainštalovaný. Záznam je stratený!
- Glykémia dostupná v NS
- Stav pumpy dostupný v NS
- Spustené manuálneUzavretý okruh deaktivovaný obmedzenímBazálny IOBAplikované obmedzenie bolusu
@@ -222,7 +216,7 @@
Dočasný bazálPredĺžený bolusVerzia Nightscoutu:
- Chýba
+ Chýba %1$dgNastavenie exportovanéExportovať nastavenia doImportovať nastavenia z
@@ -266,11 +260,23 @@
Povolené telefónne čísla+421XXXXXXXXX;+421YYYYYYYYYPre podanie bolusu %1$.2fJI odpovedz SMS kódom %2$s
+ Pre podanie bolusu k jedlu %1$.2fJI odpovedz SMS kódom %2$s
+ Pre nastavenie dočasného cieľa %1$s odpovedz SMS kódom %2$s
+ Pre zrušenie dočasného bazálu odpovedzte SMS s kódom %1$s
+ Pre vypnutie služby SMS komunikátora odpovedz SMS kódom %1$s.\n\n\Majte na pamäti, že opätovná reaktivácia je možná len priamo na AAPS master telefóne.
+ SMS komunikátor zastavený. Na jeho reaktiváciu, použite AAPS na master telefóne.Pre odoslanie kalibrácie %1$.2f odpovedz SMS kódom %2$sChyba pri aplikovaní bolusu
+ Minimálny počet minút, ktorý musí uplynúť medzi jedným vzdialeným bolusom a tým nasledujúcim
+ Aspoň koľko minút musí uplynúť, medzi jedným vzdialeným bolusom a tým nasledujúcim
+ Pre vašu bezpečnosť, musíte pridať aspoň 2 telefónne čísla, aby ste zmenili toto prednastavenie.Bolus %1$.2fJI podaný úspešnePodávanie %1$.2fJ inzulínuBolus %1$.2fJI podaný úspešne
+ Bolus %1$.2fJI podaný úspešne
+ Cieľ %1$s na %2$d minút
+ Cieľ %1$s na %2$d minút bol úspešne nastavený
+ Dočasný cieľ úspešne zrušenýPodávanie %1$.2fJIPovoliť príkazy na diaľku cez SMSPrst
@@ -317,21 +323,6 @@
STLAČENÝ STOPČakám na pumpuPodávanie %1$.2fJ inzulínu
- Nastavenie vizualizácie a monitoringu (Nightscout), analyzovať bazály a prevody
- Skontrolovať, či sú glykémie a údaje z pumpy viditeľné v Nightscoute
- Začať s otvoreným okruhom
- Niekoľko dní prevádzkovať otvorený okruh a ručne potvrdzovať doporučené dočasné bazály. Nastavovať a používať dočasné ciele (napr. pre šport, alebo hypo)
- Porozumieť otvorenému okruhu, vrátane doporučeniam ohľadne dočasných bazálov
- Na základe predchádzajúcich skúseností rozhodnúť, aký vysoký má byť maximálny bazál a nastaviť ho v pumpe a v aplikácii
- Začať s uzavretým okruhom iba s vypínaním pri nízkej glykémii
- Spustiť uzavretý okruh s max IOB = 0 na niekoľko dní s minimom nutných korekcií na nízku glykémiu
- Ladenie uzavretého okruhu, zvyšovať max IOB nad 0 a postupne znižovať cieľovú glykémiu
- Používať uzavretý okruh niekoľko dní s aspoň jednou nocou bez alarmov na nízku glykémiu, predtým ako znížiš cieľovú glykémiu
- Ak je to potrebné, uprav bazály a prevody a potom aktivuj automatickú detekciu citlivosti
- Jeden týždeň úspešne používaj uzavretý okruh so zadávaním bežného príjmu sacharidov cez deň
- Aktivuj ďalšie prídavné funkcie pre bežné používanie, ako napr. AMA (pokročilý asistent jedál)
- Aktivuj ďalšie prídavné funkcie pre bežné používanie, ako napr. SMB
- Prečítať si dokumentáciu a zvýšiť maximálne IOB, aby mohlo správne fungovať SMB! Pre začiatok sa dá použiť veľkosť bežného bolusu + 3x maximálny denný bazálDosiahnutý limitNebol vybraný žiadny profilUzavretý okruh bol deaktivovaný
@@ -345,10 +336,13 @@
Pre spustenie bazálu %1$.2fJI/h na %2$d min odpovedzte SMS s kódom %3$sPre prepnutie profilu na %1$s %2$d%% odpovedzte SMS s kódom %3$sPre spustenie predĺženého bolusu %1$.2fJI na %2$d min odpovedzte SMS s kódom %3$s
+ Pre zadanie %1$dg na %2$s odpovedz SMS kódom %3$sPre spustenie bazálu %1$d%% na %2$d min odpovedzte SMS s kódom %3$sPre pozastavenie uzavretého okruhu na %1$d minút odpovedaj SMS s kódom %2$sDočasný bazál %1$.2fJI/h spustený na %2$d minútPredĺžený bolus %1$.2fJI na %2$d min úspešne spustený
+ Sacharidy %1$dg zadané úspešne
+ Zadanie %1$dg sacharidov sa nepodariloDočasný bazál %1$d%% na %2$d minút úspešne spustenýSpustenie dočasného bazálu zlyhaloSpustenie predĺženého bolusu zlyhalo
@@ -569,8 +563,8 @@
Povoliť rozšírené indikátory stavu pre CAGE, IAGE, SAGE, Reservoir a Battery Level na domovskej obrazovke.Prah upozornenia na úroveň hladiny zásobníka [JI]Prah kritickej úrovne hladiny zásobníka [JI]
- Prah upozornenia na úroveň batérie [%%]
- Prah kritickej úrovne batérie [%%]
+ Prah upozornenia na úroveň batérie [%]
+ Prah kritickej úrovne batérie [%]IOBCOBFirmware
@@ -701,6 +695,7 @@
gmh
+ d]]>kJEn
@@ -729,6 +724,7 @@
Nastavenie nahrávania glykémieZobrazovať detailné zmenyZobrazovať rozdiel s jedným desatinným miestom naviac
+ SMB max. minútMaximálny počet minút bazálu, ku ktorým se limituje SMBNepodporovaný firmware v pumpeOdosielať glykémie do xDrip+
@@ -864,8 +860,6 @@
Prepnutie profilu chýba. Vykonajte prepnutie profilu, alebo ho aktivujte na záložke lokálneho profilu.Počet bolusovPočet dočasných bazálov
- Výukový cieľ %1$d nespustený
- Výukový cieľ %1$d nedokončenýPumpa nepodporuje dočasné bazályNenačítaný žiadny platný bazál z pumpyUzavretý okruh zakázaný v nastaveniach
@@ -987,7 +981,6 @@
Hotovo, gratulujeme!NedokončenéUplynutý čas
- %1$d. CieľPoctechZískavať glykémie z aplikácie PoctechPrijímať glykémie z aplikácie Tomato (zariadenie MiaoMiao)
@@ -1260,6 +1253,8 @@
Nevybrané (jednoduché zobrazenie)Alkalické (rozšírené zobrazenie)Líthiové (rozšírené zobrazenie)
+ NiZn (Rozšírené)
+ Bolus/Ošetrenia ladenieVYHĽADAŤZASTAVIŤ
@@ -1368,6 +1363,15 @@
Načítanie dočasného bazáluNastavovanie dočasného bazáluNastavovanie bolusu
+ Zmeniť profil na
+ Zmena profilu na %1$s
+ Posledné spojenie s pumpou
+ Posledné spojenie s pumpou [pred X minútami]
+ Posledné spojenie s pumpou pred %1$s %2$s minútami
+ Poslať SMS: %1$s
+ Odoslať SMS na všetky predvolené čísla
+ Odoslať SMS s textom
+ %2$+.2fU]]>Aplikované obmedzenie bolusu: %2$.2fJI na %3$.2fJI]]>!!!!! Detekovaná pomalá absorbcia sacharidov: %2$d%% času. Prekontrolujte kalkuláciu. COB môže byť úplne iné, môže byť podaného viac inzulínu!!!!!]]>%1$.0f / %2$d JI
@@ -1375,44 +1379,19 @@
Bolusová kalkulačka urobí výpočet, ale iba táto časť vypočítaného inzulínu je podaná. Pomáha pri SMB algoritme.Načítavanie...Stíšiť
- Splnené: %1$s
- Naučte sa, ako ovládať AndroidAPS
- Vykonávajte v AndroidAPS rôzne akcie
- Nastavte profil na 90 % na 10 min (Dlhé stlačenie názvu profilu na obrazovke Prehľad)
- Predstierajte, že se idete sprchovať. Odpojte pumpu na 1 h (Dlhšie pridržte tlačítko Otvorený okruh)
- ...a rovnakým spôsobom ju znovu pripojte
- Vytvorte vlastný dočasný cieľ s trvaním 10 min (Dlhšie pridržte aktuálny cieľ)
- V Konfigurácii povoľte modul Akcie, aktivujte jeho zobrazenie a zobrazte jeho obsah z hornej ponuky
- Zobrazte obsah modulu uzavretý okruh
- Prepnite režim zobrazenia dlhým stlačením grafu glykémie
- Zadať
- Zadajte kód, ktorý ste získali od vývojárov, aby ste obišli zostávajúce ciele
- Kód akceptovaný
- Neplatný kód
- Preukážte svoje znalosti
- Preštudujte a správne odpovedajte na otázky
- Odpovedanie zakázané do: %1$s
- Nesprávna odpoveď!
- Ďalšia nedokončená
+ Časový rozsah
+ Čas je medzi %1$s a %2$s
+ MedziZavrieť
- Kód žiadosti: %1$s
- (zaškrtnite všetky správne odpovede)
-
- %1$d deň
- %1$d dní
- %1$d dní
- %1$d dní
-
-
- %1$d hodina
- %1$d hodín
- %1$d hodín
- %1$d hodín
-
-
- %1$d minúta
- %1$d minút
- %1$d minút
- %1$d minút
-
+ Zvýšenie maximálnej hodnoty bazálu, pretože nastavenie je nižšie, než je vaša maximálna hodnota bazálu v profile
+ Neplatný obsah správy
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Bolusová kalkulačka
+ min
+ %1$dg
+ ZAP
+ VYP
diff --git a/app/src/main/res/values-sv-rSE/exam.xml b/app/src/main/res/values-sv-rSE/exam.xml
index 8070c49d7c..acf2635f62 100644
--- a/app/src/main/res/values-sv-rSE/exam.xml
+++ b/app/src/main/res/values-sv-rSE/exam.xml
@@ -3,65 +3,66 @@
Vad är sant om DIA?Ämne: Insulinduration
- Det förutbestämda minimumvärdet är 3 timmar.
- Det förutbestämda minimumvärdet är 5 timmar.
+ Minimivärdet är 3 timmar.
+ Minimivärdet är 5 timmar.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulinDet är samma som värdet Insulinduration som används i pumpen.Du måste bestämma ditt individuella värde (men inte mindre än 5 timmar).Ämne: \"Hypo\" temp mål
- Varför är det användbart att sätta in en hypo TT?
- Förhindra att BG går lågt.
- För att hjälpa till att återhämta sig från en episod med lågt BG-värde.
- För att förhindra att SMB går igång när de snabba kolhydraterna absorberas efter en hypo.
+ Vad är främsta skälet till att sätta ett \"hypo\" temp mål?
+ För att förhindra BG från att gå lågt om du redan har en nolltemp igång.
+ För att förhindra att AAPS tillför för mycket insulin efter en BG-höjning orsakad av snabbverkande kolhydrater som använts för att behandla ett lågt BG.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.htmlVilken profiltyp kan användas och konfigureras offline?Ämne: OfflineprofilNS-profil kan användas, men inte konfigureras.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profileÄmne: Koppla från pumpen
- Vad ska man göra när man kopplar bort pumpen från kroppen?
- Låt loopen veta att inget insulin levereras till din kropp genom att klicka på \"koppla från pump\".
- Ändra inget i loopen, bara ta av pumpen.
+ Vad bör göras innan du kopplar bort pumpen?
+ Klicka på \"Koppla loss pump\" så att AAPS vet att inget insulin levereras.
+ Klicka på \"pausa loopen\" så att AAPS slutar att loopa medan pumpen inte är ansluten.
+ Ändra inte på någonting i AAPS, koppla bara bort pumpen.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settingsÄmne: AndroidAPS inställningarVad är bästa praxis för att säkerhetskopiera dina inställningar?Lokalt exportera dem från underhållsmenyn.Spara den exporterade filen till ett annat ställe som e-post, Dropbox, Google Drive…Exportera dem direkt efter installationen av AAPS.
- Exportera dem efter varje ändring av en inställning.
+ Exportera dem efter att gjort ändringar i inställningarna.
+ Exportera dem efter att ha slutfört ett mål.Exportera dem när du är klar med initiala inställningar.https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.htmlhttps://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-meÄmne: Brusiga CGM-avläsningar
- Vad gör du när du ser att CGM signalen är för brusig?
- Inget, loopen tar hand om det.
- Pausa closed loop-läget för att undvika överdosering.
+ Vad bör göras om CGM-datat är brusigt?
+ Inget, AAPS tar hand om det.
+ Inaktivera loopen för att undvika överdosering.Byt CGM-sensor.Stäng av telefonen.https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
- Kolla om din CGM-app jämnar ut data.
+ Kontrollera att CGM-appen jämnar ut BG-data.Ämne: TräningHur kan du hjälpa systemet att hantera fysisk aktivitet?
- Ange ett temp-mål, t ex Träning.
+ Användning av funktionen för temp mål.Gör ett profilbyte med mindre än 100%.Gör ett profilbyte med mer än 100%.Pausa loopen.
- Ange ett temp-mål före träningspasset.
- Ange ett temp-mål efter att träningspasset börjat.
+ Ange ett \"aktivitet\" temp mål innan du börjar träna.
+ Att ställa in ett \"aktivitet\" temp mål efter träning leder till sämre resultat än om du börjar innan.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
- Ämne: Pausad eller inaktiverad loop
- Får jag insulin när loopen är pausad eller inaktiverad?
- Ja, den vanliga basaldosen.
+ Ämne: Avstängd / pausad loop
+ Får jag insulin när loopen är avstängd eller pausad?
+ Ja. Basalinsulin fortsätter att levereras.Nej, leverans av insulin är stoppad.Ämne: Basal, ISF, och IC-testningNär ska jag validera basaler, ISF-och IC-värden?Innan jag börjar loopa.
- Om jag får återkommande låga värden.
- Om jag får återkommande höga värden.
+ Om du upplever låga värden ofta.
+ Om du upplever höga värden ofta.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settingsÄmne: Krav innan startVad behöver jag?
- Fastställd korrekt profil (Basal, IC, ISF, DIA).
+ Validerad profilinformation (Basal, IC, ISF, DIA).En dator för att skapa en APK.En telefon som stöds.En bil.
@@ -69,7 +70,7 @@
Ett Tidepool-konto.Ett Google-konto.Ett Github-konto.
- Måste vara en Android-utvecklare.
+ Erfarenhet av Android-utveckling.En MiniMed 670G pump.https://androidaps.readthedocs.io/en/latest/EN/Module/module.htmlEn smart klocka.
@@ -77,35 +78,35 @@
Ämne: Uppdatering av AndroidAPSVad är sant?Du måste ha Git installerat.
- Uppdatera så snart den nya versionen har släppts.
- Du kan använda samma signera nycklar.
+ Uppdatera så snart den nya versionen har släppts och har tillräckligt med tid för att göra det.
+ Du bör använda samma signeringsnycklar.Uppdatera aldrig om systemet fungerar bra.Be din vän om den nya APK-filen.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#update-to-a-new-version-or-branchÄmne: FelsökningVar ska jag leta efter hjälp?Gå med i AndroidAPS Facebook-grupp.
- Besök AndroidAPS Wiki.
+ Läs AndroidAPS-dokumentationen.Besök AndroidAPS Gitter-rum.Besök AndroidAPS Google-supportTala med din endokrinolog.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshootinghttps://www.facebook.com/groups/AndroidAPSUsers/https://gitter.im/MilosKozak/AndroidAPS
- Ämne: Insulin
- Vilket märke av insulin kan användas med Insticksprogrammet Ultra-Rapid-Oref?
+ Ämne: Insticksmoduler för insulin
+ Vilket insulin kan användas med insulinprofilen Ultra-Rapid-Oref?Fiasp®NovoRapid ®Humalog ®Actrapid ®https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
- Ämne: Känslighetsavkänning
- Vilket insticksprogram har ett användardefinierat tidsintervall?
+ Ämne: Insticksmoduler för känslighetsavkänning
+ Vilken känslighetsalgoritm har ett konfigurerbart tidsintervall?https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.htmlVilken känslighetsplugin måste användas för att kunna använda UAM-funktionen?
- Ämne: Felaktiga KH-poster
- Du ser att du har angett fel mängd kolhydrater. Vad ska du göra?
- Gå till Treatments, ta bort felaktiga kolhydrater och mata in nya kolhydrater.
+ Ämne: Felaktig inmatning av kolhydrater
+ Vad ska du göra om du har gjort en felaktig inmatning?
+ I Behandlingar, ta bort den felaktiga posten. Ange nya kolhydrater.Lägg till en falsk bolus genom att använda påfyllningsfunktionenÄmne: Mat med fett och proteinVad ska du göra om din mat innehåller en stor mängd fett och/eller proteiner?
@@ -113,27 +114,27 @@
Räkna om fett och proteiner till kolhydrater och lägga till det i bolusberäkningen.Använd förlängd bolus för att täcka fett och protein.https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
- Ämne: Övervaka barn
+ Ämne: FjärrövervakningHur kan du övervaka AAPS för ditt barn på distans?Med hjälp av en Nightscout webbplats.
- Appen Dexcom Follow om du använder Dexcoms app på barnets mobil.
+ Appen Dexcom Follow om du använder Dexcoms app (endast BG).Dexcom Follow om du använder xDrip på barnets mobil.xDrip i följarläge.Appen Loop för iPhone.Appen Spike för iPhone.https://androidaps.readthedocs.io/en/latest/EN/Children/Children.htmlÄmne: Insulinkänslighetsfaktor (ISF)
- Ökade ISF-siffror kommer att leda till mindre tillfört insulin om du försöker sänka BG med bolusguiden.
- Minskade ISF-siffror kommer att leda till mindre tillfört insulin om du försöker sänka BG med bolusguiden.
- Förändringar i ISF påverkar inte den mängd insulin som ges av AAPS vid försök att korrigera hyperglykemi.
+ Högre ISF-värden leder till mindre insulintillförsel när AAPS korrigerar för högt BG.
+ Lägre ISF-värden leder till mindre insulintillförsel när AAPS korrigerar för högt BG.
+ Ändringar av ISF-värden påverkar inte det insulin som levereras när AAPS korrigerar för högt BG.Du måste ange ISF i Inställningar.Om du ändrar ISF-värdet i din profil är det tillräckligt för att tillämpa ändringen.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-uhttps://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
- Ämne: IC-värdet
- Ökning av IC-värdet kommer att leda till mindre insulintillförsel för samma mängd kolhydrater.
- Minskning av IC-värdet kommer att leda till mindre insulintillförsel för samma mängd kolhydrater.
- Anta att du har 0 COB. Om du ändrar IC kommer det att leda till en annan mängd insulin för att korrigera din BG-nivå.
+ Ämne: IC-kvoten
+ Högre IC-kvot leder till mindre insulin som levereras för en given mängd kolhydrater.
+ Lägre IC-kvot leder till mindre insulin som levereras för en given mängd kolhydrater.
+ Om du har 0 COB, kommer en förändring av IC-kvoten leda till en annan mängd insulin för att korrigera din BG-nivå.IC kommer att vara annorlunda om du räknar en skiva bröd som 10g eller 12g.IC-betydelsen är: Hur många skivor bröd omfattas av 1U insulin.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
@@ -145,21 +146,25 @@
kommer IC-värdet bli 10% lägre.kommer ISF-värdet bli 10% högre.kommer ISF-värdet bli 10% lägre.
- kommer du få 10% mindre insulin totalt sett.
+ Du kommer att få cirka 10% mindre insulin totalt.kommer målet justeras upp med 10%.kommer målet justeras ner med 10%.kommer endast den nedre målgränsen bli 10% lägre.https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
- Jag vill göra ett profilbyte eftersom jag var tvungen att vakna 1 timme tidigare än normalt, så det är mer logiskt att ange tidsförskjutningen via ett profilbyte. Vilken siffra ska jag använda?
- 1
- -1
+ Om du vaknar upp 1 timme tidigare än vanligt, hur ska du meddela AAPS om ändringen i ditt schema?
+ Gör ett profilbyte med en tidsförskjutning av 1
+ Gör ett profilbyte med en tidsförskjutning av -1https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
- 60
- -60
+ Gör ett profilbyte med en tidsförskjutning av 60
+ Gör ett profilbyte med en tidsförskjutning av -60https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapyÄmne: Hjälp med basaldoserVar man hittar hjälp för basaldoser m. m.Ditt diabetesteamGoogleFacebook
+ Annan medicinering
+ AAPS sänker basalen för att höja glukosmängden i blodet. Mediciner av typen SGLT2-hämmare (glifloziner) kan motverka eller förhindra den väntade glukoshöjningen vilket kan leda till akut insulinbrist och ketoacidos (DKA).
+\nVanliga märken som finns på marknaden: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\n
+Jag lovar härmed att inte ta sådana läkemedel medan jag använder AAPS eller kommer att pausa loopen innan jag tar dessa läkemedel.
diff --git a/app/src/main/res/values-sv-rSE/objectives.xml b/app/src/main/res/values-sv-rSE/objectives.xml
new file mode 100644
index 0000000000..d89538ab6e
--- /dev/null
+++ b/app/src/main/res/values-sv-rSE/objectives.xml
@@ -0,0 +1,67 @@
+
+
+
+ Tillbaka
+ Starta
+ Kontrollera
+ %1$d. Målet
+ Mål %1$d inte uppnått
+ Mål %1$d inte uppnått
+ Ställer in utseende och övervakning för att sedan kunna analysera basaler och kvoter
+ Kontrollera att BG syns i Nightscout och att insulindata från pumpen laddas upp
+ Starta med open loop
+ Kör i Open Loop-läge i några dagar och sätt ett antal temp-basaler manuellt. Konfigurera och använd temporära och förinställda temporära mål (t.ex. Träning eller Hypo)
+ Förstå din open loop och hur den föreslår temp basaler
+ Utifrån vad du nu lärt dig, besluta vilken max basal du vill ha. Ställ in det både i inställningarna i appen och i din pump
+ Börja använda closed loop med aktiverad funktion att stänga av vid lågt BG
+ Aktivera closed loop med max IOB=0 i några dagar till dess systemet inte stänger av pga lågt BG för många gånger
+ Finjustering av closed loop, med gradvis ökande max IOB och minskande målvärde för BG
+ Kör några dagar och åtminstone en natt utan larm för lågt BG innan du sänker målvärdet för BG
+ Justera basaler och kvoter om det behövs. Aktivera sedan autosens
+ 1 veckas lyckad looping dagtid, där alla måltider lagts in
+ Aktiverar extra funktioner som kan användas dagtid, såsom avancerad måltidsassistans, AMA
+ Aktiverar ytterligare funktioner för användning dagtid, t ex SMB
+ Du måste läsa på wikin och öka max IOB för att få SMB att fungera bra. En bra start är att sätta max IOB till din genomsnittliga måltidsbolus plus 3 gånger den högsta basalen du har under ett dygn
+ BG är tillängligt i Nightscout
+ Pumpstatus tillgängligt i Nightscout
+ Manuella justeringar
+ Utfört: %1$s
+ Lär dig hur du kontrollerar AndroidAPS
+ Utföra olika åtgärder i AndroidAPS
+ Ställ in profilen 90% för 10 minuter (Tryck och håll in profilens namn i Översikten)
+ Simulera dusch. Koppla från pump i 1 timme (Tryck och håll in på Open Loop i Översikten)
+ ... och återanslut på samma sätt
+ Skapa ett anpassat tillfälligt mål med 10 min varaktighet (Tryck och håll in på nuvarande BG-mål i Översikten)
+ I Konfigurationsverktyget, aktivera insticksprogrammet Åtgärder, gör det synligt och visa dess innehåll från övre menyn
+ Visa innehållet i insticksprogrammet \"Loop\"
+ Testa skala om BG-grafen genom att trycka och hålla in fingret på den
+ Enter
+ Koden godkänd
+ Koden är felaktig
+ Bevisa dina kunskaper
+ Studera och besvara frågor på rätt sätt
+ Svarsfunktionen inaktiverad till: %1$s
+ Fel svar
+ Nästa icke slutförda
+ Begärd kod: %1$s
+ (kontrollera alla korrekta svar)
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-to-do-when-taking-a-shower-or-bath
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#config-builder
+ https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/Screenshots.html#the-homescreen
+ Inte ansluten till internet
+ Fel vid hämtning av tid
+ Målets krav är inte uppfyllda
+
+ %1$d dag
+ %1$d dagar
+
+
+ %1$d tim
+ %1$d tim
+
+
+ %1$d min
+ %1$d min
+
+
diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml
index a8ec059b2a..df56089ac2 100644
--- a/app/src/main/res/values-sv-rSE/strings.xml
+++ b/app/src/main/res/values-sv-rSE/strings.xml
@@ -5,9 +5,8 @@
-
Säkerhetsbegränsningar för behandlingar
- Max tillåten bolus [E]
+ Max tillåten bolus [U]Max tillåtna KH [g]InställningarUppdatera behandlingar från Nightscout
@@ -24,8 +23,8 @@
Används för att konfigurera de aktiva insticksprogrammenInlärningsprogramVisar förutbestämda inställningar för mat i Nightscout
- Insulininställning för Humalog, Apidra och Novorapid/Novolog
- Insulininställning för Fiasp
+ Insulininställning för vanliga direktverkande insuliner som Humalog, Lispro, Apidra och Novorapid/Novolog
+ Insulininställning för ultrasnabba insuliner, t ex FiaspLåter dig ställa in tidpunkten för toppen på insulinets aktivitet. Bör bara användas av avancerade användareAktivera eller avaktivera implementationen som kör loopen.Synkroniserar dina data med Nightscout
@@ -55,12 +54,9 @@ Eversense-appen.Ladda ner BG-data från NightscoutTa emot BG-data från xDripSpara alla behandlingar som gjorts
- Följ och kontrollera din AndroidAPS med din WearOS-klocka
+ Följ och kontrollera AndroidAPS med din Wear OS-klockaVisa AAPS-information på din xDrip-urtavlaFjärrstyr AndroidAPS med SMS-kommandon.
- Backa
- Starta
- GodkännEnheterDIAIC
@@ -72,22 +68,22 @@ Eversense-appen.KH:IOB:IOB:
- Total IOB (bolus):
- Total aktivitet (5m):
+ IOB fr bolus:
+ Insulinaktivitet (5m):Dur:Tot:Ins:IOB:
- Total IOB (basal):
+ IOB fr basal:InsulinKHBGTTKH
- Korr
- E
+ Korrektion
+ UBolus IOB
- Beräkna nu
+ Utför nuVirtuell pumpProfilens basaldosTemp basal
@@ -103,6 +99,7 @@ Eversense-appen.
ProfilMåltidsdataResultat
+ Resultat: %1$s %2$sIngen BG-data tillängligIngen ändring behövsBeräknat behov
@@ -178,9 +175,6 @@ Eversense-appen.Versionen av NSClient stöds inteVersionen av Nightscout stöds inteNSClient är inte installerad. Data förlorad!
- BG är tillängligt i Nightscout
- Pumpstatus tillgängligt i Nightscout
- Manuella justeringarLOOP STOPPAD PGA BEGRÄNSNINGARIOB från basalBolusspärr aktiverad
@@ -198,7 +192,7 @@ Eversense-appen.MellanmålsbolusMåltidsbolusKorrektionsbolus
- Kombinationsbolus
+ Kombi-bolusTemp basal startTemp basal slutKH-korrektion
@@ -223,7 +217,7 @@ Eversense-appen.
Temp basalFörlängd bolusNightscoutversion:
- Saknas:
+ Saknar %1$dgInställningar exporteradeExportera inställningar tillImportera inställningar från
@@ -318,21 +312,6 @@ Eversense-appen.
Stopp nedtrycktVäntar på pumpKommer att leverera %1$.2f enheter
- Ställer in utseende och övervakning för att sedan kunna analysera basaler och kvoter
- Kontrollera att BG syns i Nightscout och att insulindata från pumpen laddas upp
- Startar med open loop
- Kör i Open Loop-läge i några dagar och sätt ett antal temp-basaler manuellt. Konfigurera och använd temporära och förinställda temporära mål (t.ex. Träning eller Hypo)
- Förstå din open loop och hur den föreslår temp basaler
- Utifrån vad du nu lärt dig, besluta vilken max basal du vill ha. Ställ in det både i inställningarna i appen och i din pump
- Börja använda closed loop med aktiverad funktion att stänga av vid lågt BG
- Aktivera closed loop med max IOB=0 i några dagar till dess systemet inte stänger av pga lågt BG för många gånger
- Finjustering av closed loop, med gradvis ökande max IOB och minskande målvärde för BG
- Kör några dagar och åtminstone en natt utan larm för lågt BG innan du sänker målvärdet för BG
- Justera basaler och kvoter om det behövs. Aktivera sedan autosens
- 1 veckas lyckad looping dagtid, där alla måltider lagts in
- Aktiverar extra funktioner som kan användas dagtid, såsom avancerad måltidsassistans, AMA
- Aktiverar ytterligare funktioner för användning dagtid, t ex SMB
- Du måste läsa på wikin och öka max IOB för att få SMB att fungera bra. En bra start är att sätta max IOB till din genomsnittliga måltidsbolus plus 3 gånger den högsta basalen du har under ett dygnDu har nått din tillåtna gränsIngen profil valdLoop stängdes av
@@ -413,7 +392,7 @@ Eversense-appen.
Minimed 640GKonstant avisering i telefonenAktuellt BG saknas!
- %1$d min sedan
+ %1$d min sedan%1$d min sedanLokal profilOpenAPS AMA
@@ -565,13 +544,13 @@ Eversense-appen.
INSAktivera superbolus i kalkylatornAktiverar superbolusfunktionen i kalkylatorn. Aktivera inte innan du förstått hur den fungerar. DEN KAN ORSAKA ÖVERDOSERING AV INSULIN OM INSIKT SAKNAS OM FUNKTIONEN!
- Visa statusindikationer på hemskärmen
- Visa statusindikatorer på hemskärmen
+ Visa \"statuslampor\" på hemskärmen
+ Visa utökade statusindikatorerAktivera statusindikatorerna för cage, iage, sage, reservoar och batterinivå på hemskärmen.Varningsnivå för reservoar [U]Akut varningsnivå för reservoar [U]
- Varningsnivå för batteri [%%]
- Akut varningsnivå för batteri [%%]
+ Varningsnivå för batteri [%]
+ Akut varningsnivå för batteri [%]IOBCOBFirmwareversion
@@ -612,7 +591,7 @@ Eversense-appen.
Akut varning efter [min]Intervall för autosens [tim]Antal timmar för beräkning av känslighet (absorptionstid för KH är exkluderad)
- P
+ PumpOpenAPSUppladdareKänslighetsavkänning
@@ -628,7 +607,7 @@ Eversense-appen.
SAGEIAGECAGE
- PBAGE
+ BAGEAPSUpld battBAS
@@ -730,6 +709,7 @@ Eversense-appen.
Uppladdningsinställningar för BGVisa detaljerad deltaVisa delta med en extra decimal
+ SMB max minuterMax antal minuter som kan bli SMBPumpens firmware stöds inteSkicka BG-data till xDrip+
@@ -838,7 +818,7 @@ Eversense-appen.
Bolusen sparas bara i loggbokenHämta saknad BG-data från NightscoutSMB satt i pump
- Aktivitet
+ Insulinaktivitet (5m)Känslighet (Sens)Avvikelser (Dev)Aktiva KH (COB)
@@ -865,8 +845,6 @@ Eversense-appen.
Profilbyte saknas. Vänligen gör ett profilbyte eller tryck Aktivera profil under Lokal Profil.Antal bolusAntal temp basaler
- Mål %1$d inte startat
- Mål %1$d inte uppnåttPumpen kan inte hantera temp basalerIngen giltig data om temp basaler fanns i pumpenClosed Loop inaktiverat i Inställningar
@@ -899,7 +877,7 @@ Eversense-appen.
ÅterställVäntar på tidssynkronisering (%1$d sek)Frånkopplad (%1$d min)
- Max IOB som OpenAPS inte kan överstiga [E]
+ Max IOB som OpenAPS inte kan överstiga [U]Det här värdet kallas Max IOB av OpenAPS. Om denna mängd insulin on board (IOB) nås, kan inte OpenAPS lägga till mer.Pump stoppadPump startad
@@ -988,7 +966,6 @@ Eversense-appen.
Klart. Bra jobbat!Inte slutfört ännuFörfluten tid
- %1$d. MålPoctechTa emot BG-data från PoctechappenTa emot BG-data från tomato app (MiaoMiao-enhet)
@@ -1081,7 +1058,7 @@ Eversense-appen.
Stoppade%1$d%% i %2$d / %3$d minFörlängd bolus
- Kombinationsbolus
+ Kombi-bolus%1$.2f / %2$.2f U i %3$d minAktivera meddelanden om avslutade tempbasaler\n(pumpinställning)Inaktivera meddelanden om avslutade tempbasaler\n(pumpinställning)
@@ -1199,7 +1176,7 @@ Eversense-appen.
väldigt gammal versionNy version tillgänglig sedan %1$d dagar! Systemet kommer att byta läge till \"stopp innan lågt\" efter 60 dagar och sluta loopa helt efter 90 dagar2 tim
- %1$.2f enheter
+ %1$.2f UDexcoms app (modifierad)DXCMTa emot BG-data från den modifierade Dexcom-appen.
@@ -1217,8 +1194,8 @@ Eversense-appen.
Autosens %1$s %2$s %%Autosens %%3$s %1$s %2$s
- Skillnad
- BG-skillnad [%1$s]
+ BG-förändring
+ BG-förändring [%1$s]Nuvarande platsPlatsLat:
@@ -1261,6 +1238,8 @@ Eversense-appen.
Ej valdAlkalisktLitium
+ NiZn (utökad vy)
+ Avlusning av Bolus/BehandlingarSÖKAVBRYT
@@ -1369,6 +1348,14 @@ Eversense-appen.
Hämta temp basalSätt temp basalLeverera bolus
+ Byt profil till
+ Byt profil till %1$s
+ Senaste anslutning till pump
+ Senaste anslutning till pump [min sedan]
+ Senaste anslutning till pump %1$s %2$s min sedan
+ Skicka SMS: %1$s
+ Skicka SMS till alla nummer i inställningar
+ Skicka SMS med text%2$+.2fU]]>Bolusbegränsning: %2$.2fU till %3$.2fU]]>Varning! Långsam KH-absorption upptäckt %2$d%% av tiden. Dubbelkolla din beräkning. COB kan vara väldigt missvisande och du riskerar få för mycket insulin!]]>
@@ -1377,38 +1364,19 @@ Eversense-appen.
Bolusguiden utför beräkningar, men endast denna del av beräknat insulin levereras. Användbar med SMB-algoritm.Laddar...Snooze
- Utfört: %1$s
- Lär dig hur du kontrollerar AndroidAPS
- Utföra olika åtgärder i AndroidAPS
- Ställ in profilen 90% för 10 minuter (Tryck och håll in profilens namn i Översikten)
- Simulera dusch. Koppla från pump i 1 timme (Tryck och håll in på Open Loop i Översikten)
- ... och återanslut på samma sätt
- Skapa ett anpassat tillfälligt mål med 10 min varaktighet (Tryck och håll in på nuvarande BG-mål i Översikten)
- I Konfigurationsverktyget, aktivera insticksprogrammet Åtgärder, gör det synligt och visa dess innehåll från övre menyn
- Visa innehållet i insticksprogrammet \"Loop\"
- Testa skala om BG-grafen genom att trycka och hålla in fingret på den
- Enter
- Ange kod som erhållits från utvecklare för att kringgå resten av målen
- Koden godkänd
- Koden är felaktig
- Bevisa dina kunskaper
- Studera och besvara frågor på rätt sätt
- Svarsfunktionen inaktiverad till: %1$s
- Fel svar!
- Nästa icke slutförda
+ Tidsintervall
+ Klockan är mellan %1$s och %2$s
+ Mellan Stäng
- Begärd kod: %1$s
- (kontrollera alla korrekta svar)
-
- %1$d dag
- %1$d dagar
-
-
- %1$d timme
- %1$d timmar
-
-
- %1$d min
- %1$d min
-
+ Ökar maximalt basaldos eftersom inställningen är lägre än din maximala basal i profilen
+ Ogiltigt innehåll i meddelande
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Kalkylator
+ min
+ %1$dg
+ På
+ Av
diff --git a/app/src/main/res/values-tr-rTR/objectives.xml b/app/src/main/res/values-tr-rTR/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-tr-rTR/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/values-tr-rTR/strings.xml
index d5d7b46d5d..e42bee6ba7 100644
--- a/app/src/main/res/values-tr-rTR/strings.xml
+++ b/app/src/main/res/values-tr-rTR/strings.xml
@@ -5,7 +5,6 @@
-
Tedavilerin güvenlik ayarlarıMax izin verilen bolus [U]Max izin verilen karbonhidrat [g]
@@ -53,8 +52,6 @@
WearOS saatinizi kullanarak AndroidAPS\'yi izleyin ve kontrol edin.Döngü\'yle ilgili bilgileri xDrip+ watchface\'inizde gösterin.SMS komutlarını kullanarak uzaktan AndroidAPS kontrolü.
- Başlat
- DoğrulayınÜniteDIAIC Karbonhidrat İnsülin Oranı
@@ -170,9 +167,6 @@
NSClient\'in desteklenmeyen sürümüNightscout\'un desteklenmeyen sürümüNSClient yüklü değil. Kayıt kaybedildi!
- KŞ NS\'de mevcut
- Pompa durumu NS mevcut
- Manuel eylemlerDÖNGÜ KISITLAMALARDAN İPTAL EDİLDİBazal IOBBolus kısıtlaması uygulandı
@@ -215,7 +209,6 @@
Geçici BazalYayım BolusNightscout sürümü:
- EksikTercihler dışa aktarıldıAyarları aktarAyarları içe aktar
@@ -304,8 +297,6 @@
DurDURDUR\'A BASTIĞINIZPompa bekleniyor
- Nightscout üzerinden izlemeyi ve görselleştirmeyi yapılandırın ve bazal oranlarını ve faktörleri düzenleyin
- Nightscout\'ta KŞ\'nin bulunduğunu ve insülin verilerinin yüklenmekte olduğunu doğrulayınİzin verilen sınıra ulaştınızProfil seçilmediDöngü devre dışı bırakıldı
@@ -798,8 +789,6 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d
Profildeğiştir kayıp. Lütfen bir profil değiştir seçin veya YerelPorfil\'de \"Profili Etkinleştir\" düğmesine basın.Bolus sayısıTBR (GBO) Geçici Bazal Oranı sayısı
- Hedef %1$d başlanamadı
- Hedef %1$d tamamlanamadıPompa geçici bazal yetenekli değilPompadan okunan geçerli bir bazal oranı yokKapalı Döngü tercihlerde devre dışı bırakıldı
@@ -920,7 +909,6 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d
Tamamlandı, aferin!Henüz tamamlanmadıGeçen süre
- %1$d. GörevPoctechPoctech app\'ten KŞ değerlerini alırKŞ değerlerini Tomato app (MiaoMiao Cihazından) al
@@ -981,16 +969,4 @@ Aktif Karbonhidratın ne kadar hızlı sindirildiğine ve KŞ\'nin beklenenden d
-
- %1$d gün
- %1$d gün
-
-
- %1$d saat
- %1$d saat
-
-
- %1$d dakika
- %1$d dakika
-
diff --git a/app/src/main/res/values-zh-rCN/objectives.xml b/app/src/main/res/values-zh-rCN/objectives.xml
new file mode 100644
index 0000000000..70489fbc5e
--- /dev/null
+++ b/app/src/main/res/values-zh-rCN/objectives.xml
@@ -0,0 +1,3 @@
+
+
+
diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml
index 956f3864ba..5335791cbe 100644
--- a/app/src/main/res/values-zh-rCN/strings.xml
+++ b/app/src/main/res/values-zh-rCN/strings.xml
@@ -5,7 +5,6 @@
-
治疗安全允许的最大大剂量值[U]最大允许碳水化合物 [g]
@@ -55,9 +54,6 @@
使用您的 WearOS 手表监视和控制 AndroidAPS。在 xDrip + 表盘上显示有关闭环的信息。远程控制 AndroidAPS 使用 SMS 短信命令。
- 返回
- 开始
- 校验单位DIA胰岛素作用持续时间IC碳水系数
@@ -175,9 +171,6 @@
不支持的 NSClient 版本不支持的 Nightscout 版本未安装 NSClient。记录丢失!
- 血糖在NS中可用
- 泵状态在 NS 中可用
- 手动制定按约束条件禁用循环基础 IOB大剂量约束条件应用了
@@ -220,7 +213,6 @@
临时基础扩展大剂量Nightscout 版本:
- 缺少参数选项导出了导出配置导入配置
@@ -315,8 +307,6 @@
停止键按下了正在等待泵将要输注 %1$.2fU
- 设置可视化和监视, 并分析基础率和比率
- 验证 Nightscout 中的血糖是否可用, 并且正在上传泵的胰岛素数据你达到了允许的极限没有选定配置文件闭环已经被禁用
@@ -550,8 +540,6 @@
在主屏幕上显示状态指示灯储药器药量低于阈值[U] 警告储药器药量低于阈值[U] 严重警告
- 电池电量低于阈值[%%] 警告
- 电池电量低于阈值[%%] 严重警告IOB活性胰岛素COB活性碳水固件
@@ -842,8 +830,6 @@
配置文件切换缺失。请做一次配置文件切换或者在本地配置文件里按“激活配置文件”大剂量 计数临时基础率 计数
- 目标 %1$d 未开始
- 目标 %1$d 未完成这个泵无法设置临时基础率从泵中无法读取有效的基础率在参数选项中禁用了闭环模式
@@ -964,7 +950,6 @@
完成了,做的好尚未完成已用时间
- %1$d.目标Poctech从 Poctech app 接收血糖值。从番茄app(喵喵设备) 接收血糖值
@@ -1106,8 +1091,6 @@
上传临时基础率上传配置文件切换,临时目标上传血糖值
- 在24小时内或更少时间内更夏令时时间
- 不到3小时前夏令时时间变化了-已禁用闭环内部储存空间不足至少 剩余%1$d MB 内部存储!闭环已禁用!格式错误
@@ -1135,13 +1118,4 @@
-
- %1$d 天
-
-
- %1$d 小时
-
-
- %1$d 分钟
-
diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml
index 864835bd87..6b98e1c0dd 100644
--- a/app/src/main/res/values/arrays.xml
+++ b/app/src/main/res/values/arrays.xml
@@ -24,6 +24,7 @@
@string/ko_lang@string/lt_lang@string/pt_lang
+ @string/pt_BR_lang@string/ro_lang@string/ru_lang@string/sk_lang
@@ -46,6 +47,7 @@
koltpt
+ pt_BRrorusk
@@ -97,7 +99,7 @@
@string/use_gps_location
-
+ PASSIVENETWORKGPS
@@ -149,7 +151,7 @@
@string/medtronic_pump_frequency_worldwide
-
+ @string/key_medtronic_pump_frequency_us_ca@string/key_medtronic_pump_frequency_worldwide
@@ -165,6 +167,11 @@
@string/medtronic_pump_encoding_4b6b_rileylink
+
+ @string/common_on
+ @string/common_off
+
+
@string/key_medtronic_pump_encoding_4b6b_local@string/key_medtronic_pump_encoding_4b6b_rileylink
@@ -174,12 +181,17 @@
@string/medtronic_pump_battery_no@string/medtronic_pump_battery_alkaline@string/medtronic_pump_battery_lithium
+ @string/medtronic_pump_battery_nizn@string/key_medtronic_pump_battery_no@string/key_medtronic_pump_battery_alkaline@string/key_medtronic_pump_battery_lithium
+ @string/key_medtronic_pump_battery_nizn
+
+ key_medtronic_bolus_debug
+
diff --git a/app/src/main/res/values/exam.xml b/app/src/main/res/values/exam.xml
index 4b869dcfa0..e9063fd2b1 100644
--- a/app/src/main/res/values/exam.xml
+++ b/app/src/main/res/values/exam.xml
@@ -2,63 +2,66 @@
What is true about DIA?Topic: Duration of Insulin Action
- The predetermined minimum is 3 hours.
- The predetermined minimum is 5 hours.
+ The minimum value is 3 hours.
+ The minimum value is 5 hours.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html?#insulin
- It is equal to the DIA parameter used in your pump.
+ The meaning is equal to the DIA parameter used in your pump.You have to determine your individual value (but not less than 5 hours).Topic: Hypo Temp-Target
- Why is it useful to set a hypo TT?
- Prevent BG from going low.
- To prevent SMB enactment after a hypo rise from fast carbs.
+ What is primary reason to set a hypo TT?
+ To prevent BG from going low if there is already zero temp running.
+ To prevent AAPS from dosing too much insulin after a rise caused by fast-acting carbs used to treat a low.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.htmlWhich profile can be used and configured offline?Topic: Offline ProfileNS Profile can be used, but not configured.https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#profileTopic: Disconnecting from the Pump
- What to do when taking the pump off?
- Let the loop know that there is no insulin being delivered to your body by clicking disconnect pump.
- Don\'t change anything in loop, just take the pump off.
+ What should be done when disconnecting the pump?
+ Click ‘Disconnect pump’ so that AAPS knows that no insulin is being delivered.
+ Click ‘Suspend loop’ so that AAPS stops looping while the pump is disconnected.
+ Don’t change anything in AAPS, just disconnect the pump.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#other-settingsTopic: AndroidAPS SettingsWhat are best practices to backup your settings?Locally export them from Maintenance menu.Store exported file to another place like email, Dropbox, Google drive…Export them right after installation of AAPS.
- Export them after every change of a setting.
+ Export them after making setting changes.
+ Export them after completing an objective.Export them when you finish initial settings.https://androidaps.readthedocs.io/en/latest/EN/Usage/ExportImportSettings.htmlhttps://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#what-emergency-equipment-is-recommended-to-take-with-meTopic: Noisy CGM Readings
- What to do when you see CGM signals are too noisy?
- Nothing, the loop will deal with it.
- Pause closed-loop mode to avoid overdosing.
+ What should be done if CGM data is noisy?
+ Nothing, AAPS will deal with it.
+ Disable the loop to avoid overdosing.Replace the CGM sensor.Turn off the phone.https://androidaps.readthedocs.io/en/latest/EN/Usage/Smoothing-Blood-Glucose-Data-in-xDrip.html#smoothing-blood-glucose-data
- Check if your CGM app smoothes data.
+ Verify that your CGM app smoothes BG data.Topic: ExerciseHow can you help the system deal with exercise?
- Set an activity temp-target.
+ Using of temp-target feature.Do a profile switch below 100%.Do a profile switch above 100%.Stop the loop.
- Set activity temp-target before the start of exercise.
+ Set an activity temp-target before starting exercise.
+ Setting an activity temp-target after starting exercise leads to worse results than if started before.https://androidaps.readthedocs.io/en/latest/EN/Usage/temptarget.html#activity-temp-target
- Topic: Suspended Loop
- Do I get insulin when loop is suspended?
- Yes, the common basal rate.
+ Topic: Disabled/Suspended loop
+ Do I receive insulin when the loop is disabled/suspended?
+ Yes, basal insulin continues to be delivered.No, delivery of insulin is stopped.Topic: Basal, ISF, and IC TestingWhen should I validate basals, ISF, and IC values?Before I start looping.
- When having regular hypos BG\'s.
- When having regular hypers BG\'s.
+ When experiencing low BG frequently.
+ When experiencing high BG frequently.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#androidaps-settingsTopic: PrerequisitesWhat do I need?
- Determined correct profile (Basals, IC, ISF, DIA).
+ Validated profile information (Basal, IC, ISF, DIA).A computer to create an APK.A supported phone.A Car.
@@ -66,15 +69,15 @@
A Tidepool account.A Google account.A Github account.
- Need to be an Android developer.
+ Android development experience.A MiniMed 670G pump.https://androidaps.readthedocs.io/en/latest/EN/Module/module.htmlA Smartwatch.A Supported CGM.
- Topic: Updating of AndroidAPS
+ Topic: Updating AndroidAPSWhat is true?You need to have Git installed.
- Update as soon as new version is released.
+ Update as soon as new version is released and having enough time to do it.You should use the same signing keys.Never update if the system is working well.Ask your friend for the new APK.
@@ -82,27 +85,27 @@
Topic: TroubleshootingWhere to look for help?Join the AndroidAPS Facebook group.
- Visit the AndroidAPS Wiki.
+ Read the AndroidAPS documentation.Visit AndroidAPS Gitter Room.Visit AndroidAPS Google supportSpeak to your endocrinologist.https://androidaps.readthedocs.io/en/latest/EN/Installing-AndroidAPS/Update-to-new-version.html#troubleshootinghttps://www.facebook.com/groups/AndroidAPSUsers/https://gitter.im/MilosKozak/AndroidAPS
- Topic: Insulin
- Which brand of insulin can be used with Ultra-Rapid-Oref plugin?
+ Topic: Insulin Plugins
+ Which brand of insulin can be used with the ‘Ultra-Rapid-Oref’ plugin?Fiasp®NovoRapid®Humalog®Actrapid®https://androidaps.readthedocs.io/en/latest/EN/Configuration/Config-Builder.html#insulin
- Topic: Sensitivity Plugin
- Which sensitivity plugin has user defined time range for detection?
+ Topic: Sensitivity Plugins
+ Which sensitivity algorithm has a configurable time range?https://androidaps.readthedocs.io/en/latest/EN/Configuration/Sensitivity-detection-and-COB.htmlWhich sensitivity plugin must be used for the UAM feature?
- Topic: Wrong Carb Entries
- You see you have entered wrong carbs. What should you do?
- Go to Treatments, delete wrong carbs and enter new carbs.
+ Topic: Carb Entry Errors
+ What should you do if you’ve made an incorrect carb entry?
+ In Treatments, delete the incorrect carb entry. Enter new carbs.Add fake insulin by using Refill functionTopic: Food with Fat and ProteinWhat to do if your food contains a large amount of fat and\/or proteins?
@@ -110,7 +113,7 @@
Recalculate fat and proteins to carbs and add it to bolus calculation.Use extended bolus to cover fat and proteins.https://androidaps.readthedocs.io/en/latest/EN/Usage/Extended-Carbs.html
- Topic: Monitoring Children
+ Topic: Remote MonitoringHow can you monitor AAPS of your child remotely?Using a Nightscout site.Dexcom Follow app if you are using the original Dexcom app (BG only).
@@ -120,17 +123,17 @@
Spike app on iPhone.https://androidaps.readthedocs.io/en/latest/EN/Children/Children.htmlTopic: Insulin Sensitivity Factor
- Increasing ISF number will lead to less insulin delivery if you are trying to lower your BG with the bolus wizard.
- Decreasing ISF number will lead to less insulin delivery if you are trying to lower your BG with the bolus wizard.
- Changing ISF has no effect on amount of insulin given by AAPS when trying to correct hyperglycemia.
+ Higher ISF values lead to less insulin delivery when AAPS corrects for high BG.
+ Lower ISF values lead to less insulin delivery when AAPS corrects for high BG.
+ Changing ISF values has no effect on the amount of insulin delivered when AAPS corrects for high BG.You have to enter ISF in Preferences.Changing the ISF value in your profile is enough to apply the change.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#insulin-sensitivity-factor-isf-mmol-l-u-or-mg-dl-uhttps://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html
- Topic: The IC Value
- Increasing the IC value will lead to less insulin delivery for the same amount of carbs.
- Decreasing the IC value will lead to less insulin delivery for the same amount of carbs.
- Assume you have 0 COB. Changing IC will lead to a different amount of insulin to correct your BG number.
+ Topic: The IC Ratio
+ Higher IC ratios lead to less insulin delivered for a given amount of carbs.
+ Lower IC ratios lead to less insulin delivered for a given amount of carbs.
+ If you have 0 COB, changing the IC ratio will lead to a different amount of insulin to correct a given BG value.IC will be different if you count bread unit as 10g or 12g.IC meaning is: How many bread units are covered by 1U of insulin.https://androidaps.readthedocs.io/en/latest/EN/Getting-Started/FAQ.html#carbohydrate-to-insulin-ratio-cr-g-u
@@ -147,17 +150,20 @@
Target will be 10% lower.Only bottom target will be 10% lower.https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#profile-switch
- I want to do a profile switch because I had to wake up 1h earlier than usually, so it makes more sense to announce the change by the time shift with a profile switch. What number should I use?
- 1
- -1
+ If you wake up 1h earlier than usual, how should you notify AAPS of the change in your schedule?
+ Initiate a profile switch with a timeshift of 1
+ Initiate a profile switch with a timeshift of -1https://androidaps.readthedocs.io/en/latest/EN/Usage/Profiles.html?highlight=profile%20switch#timeshift
- 60
- -60
+ Initiate a profile switch with a timeshift of 60
+ Initiate a profile switch with a timeshift of -60https://androidaps.readthedocs.io/en/latest/EN/Module/module.html#good-individual-dosage-algorithm-for-your-diabetes-therapyTopic: Help with basal ratesWhere to go for help with basalrate etc.Your diabetes teamGoogleFacebook
+ Other Medication
+ AAPS reduces BR to raise blood sugar. Drugs from the group of SGLT2 inhibitors (gliflozins) can prevent the expected increase in BG and thus may produce a dangerous insulin deficiency (DKA).
+\nCommon brand names are: Invokana®, Forxiga®, Jardiance®, Steglatro®, Suglat®, Apleway®, Deberza®, Synjardy®, Vokanamet®, Xigduo®.\n\nI hereby promise that I will not take such drugs when using AAPS or will deactivate the loop before using these drugs.
diff --git a/app/src/main/res/values/objectives.xml b/app/src/main/res/values/objectives.xml
index 8464c4d947..d5ffbc2e3a 100644
--- a/app/src/main/res/values/objectives.xml
+++ b/app/src/main/res/values/objectives.xml
@@ -47,12 +47,12 @@
Display content of Loop pluginUse scale function by long-pressing BG chartEnter
- Enter code obtained from developers to bypass the rest of objectives
+ If you were OpenAPS user before and your NS has at least 3 months of looping data, you can send an email to objectives@androidaps.org with your NS address and request code to bypass the rest of objectives. Enter code obtained from developersCode acceptedCode invalidProve your knowledgeStudy and answer questions correctly
- Answering disabled to: %1$s
+ Answering disabled until: %1$sWrong answer!Next unfinishedRequest code: %1$s
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 6536071f6f..ccc91c699b 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -4,20 +4,20 @@
AfrikaansBulgarianDutch
-
+
FrenchGermanGreek
-
+
Chinese
-
+
Italian
-
+
KoreanLithuanianPolishPortuguese
-
+ Portuguese, BrazilianRomanianRussianSlovak
@@ -121,6 +121,7 @@
ProfileMeal dataResult
+ Result: %1$s %2$sNo glucose data availableNo change requestedRequest
@@ -245,7 +246,7 @@
TempBasalExtended BolusNightscout version:
- Missing
+ Missing %1$dgPreferences exportedExport settings toImport settings from
@@ -291,11 +292,24 @@
Allowed phone numbers+XXXXXXXXXX;+YYYYYYYYYYTo deliver bolus %1$.2fU reply with code %2$s
+ To deliver meal bolus %1$.2fU reply with code %2$s
+ To set the Temp Target %1$s reply with code %2$s
+ To cancel Temp Target reply with code %1$s
+ To disable the SMS Remote Service reply with code %1$s.\n\nKeep in mind that you\'ll able to reactivate it directly from the AAPS master smartphone only.
+ SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone.To send calibration %1$.2f reply with code %2$sBolus failed
+ smscommunicator_remotebolusmindistance
+ Minimum number of minutes that must elapse between one remote bolus and the next
+ How many minutes must elapse, at least, between one bolus and the next
+ For your safety, to edit this preference you need to add at least 2 phone numbers.Bolus %1$.2fU delivered successfullyGoing to deliver %1$.2fUBolus %1$.2fU delivered successfully
+ Meal Bolus %1$.2fU delivered successfully
+ Target %1$s for %2$d minutes
+ Target %1$s for %2$d minutes set successfully
+ Temp Target canceled successfullyDelivering %1$.2fUAllow remote commands via SMSFinger
@@ -355,10 +369,13 @@
To start basal %1$.2fU/h for %2$d min reply with code %3$sTo switch profile to %1$s %2$d%% reply with code %3$sTo start extended bolus %1$.2fU for %2$d min reply with code %3$s
+ To enter %1$dg at %2$s reply with code %3$sTo start basal %1$d%% for %2$d min reply with code %3$sTo suspend loop for %1$d minutes reply with code %2$sTemp basal %1$.2fU/h for %2$d min started successfullyExtended bolus %1$.2fU for %2$d min started successfully
+ Carbs %1$dg entered successfully
+ Entering %1$dg of carbs failedTemp basal %1$d%% for %2$d min started successfullyTemp basal start failedExtended bolus start failed
@@ -611,9 +628,9 @@
key_statuslights_res_criticalThreshold critical reservoir level [U]key_statuslights_bat_warning
- Threshold warning battery level [%%]
+ Threshold warning battery level [%]key_statuslights_bat_critical
- Threshold critical battery level [%%]
+ Threshold critical battery level [%]IOBCOBFirmware
@@ -777,6 +794,7 @@
gmh
+ d]]>kJEn
@@ -815,9 +833,9 @@
Show delta with one more decimal placekey_smbintervalHow frequently SMBs will be given in min
- 45 60 75 90 105 120
+ SMB max minutesMax minutes of basal to limit SMB to
- 45 60 75 90 105 120
+ UAM SMB max minutesMax minutes of basal to limit SMB to for UAMbolus_incrementMinimum bolus that can be delivered as an SMB
@@ -1336,9 +1354,9 @@
Upload BG testssmbmaxminutes
- Dayligh Saving time
- Dayligh Saving time change in 24h or less
- Daylight saving time change less than 3 hours ago - Closed loop disabled
+ Daylight Saving time
+ Daylight Saving time change in 24h or less
+ Daylight Saving time change less than 3 hours ago - Closed loop disabledinternal storage constraintFree at least %1$d MB from internal storage! Loop disabled!Wrong format
@@ -1410,6 +1428,7 @@
REMOVEPreconditions:
+
Operation not supported by pump and/or driver.Operation not YET supported by pump.
@@ -1428,6 +1447,7 @@
pref_medtronic_bolus_delaypref_medtronic_encodingpref_medtronic_battery_type
+ pref_medtronic_bolus_debugpref_rileylink_mac_addressmedtronic_pump_frequency_us_camedtronic_pump_frequency_worldwide
@@ -1436,6 +1456,7 @@
medtronic_pump_battery_nomedtronic_pump_battery_alkalinemedtronic_pump_battery_lithium
+ medtronic_pump_battery_niznPump Serial NumberPump Type
@@ -1455,6 +1476,8 @@
Not selected (Simple view)Alkaline (Extended view)Lithium (Extended view)
+ NiZn (Extended view)
+ Bolus/Treatments DebuggingSCAN
@@ -1580,6 +1603,9 @@
Set BolusChange profile toChange profile to %1$s
+ Last connection to pump
+ Last connection to pump [minutes ago]
+ Last connection to pump %1$s %2$s min agoSend SMS: %1$sSend SMS to all numbers in preferencesSend SMS with text
@@ -1601,5 +1627,15 @@
CloseIncreasing max basal value because setting is lower than your max basal in profileInvalid message body
+ %1$s ISF: %2$.1f
+ %1$.0fg IC: %2$.1f
+ %1$.1fg IC: %2$.1f
+ %1$d%%
+ Bolus wizard
+ min
+ wizard_calculation_visible
+ %1$dg
+ On
+ Off
diff --git a/app/src/main/res/xml/pref_medtronic.xml b/app/src/main/res/xml/pref_medtronic.xml
index 603d3873f8..10730f4fcb 100644
--- a/app/src/main/res/xml/pref_medtronic.xml
+++ b/app/src/main/res/xml/pref_medtronic.xml
@@ -68,6 +68,14 @@
android:selectable="true"
android:title="@string/medtronic_pump_battery_select" />
+
+
-
+
@@ -8,6 +9,16 @@
android:key="@string/key_smscommunicator_allowednumbers"
android:summary="@string/smscommunicator_allowednumbers_summary"
android:title="@string/smscommunicator_allowednumbers" />
+ list = new ProfileIntervals<>();
@@ -91,7 +89,6 @@ public class ProfileIntervalsTest {
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockTreatmentPlugin();
}
diff --git a/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java b/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java
index 2e98640325..08f0aab20c 100644
--- a/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/data/ProfileTest.java
@@ -22,7 +22,6 @@ import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
import info.nightscout.androidaps.utils.FabricPrivacy;
-import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
@@ -134,7 +133,7 @@ public class ProfileTest {
// Test hour alignment
ConfigBuilderPlugin.getPlugin().getActivePump().getPumpDescription().is30minBasalRatesCapable = false;
- ((AAPSMocker.MockedBus) MainApp.bus()).notificationSent = false;
+ //((AAPSMocker.MockedBus) MainApp.bus()).notificationSent = false;
p = new Profile(new JSONObject(notAllignedBasalValidProfile), 100, 0);
p.isValid("Test");
//Assert.assertEquals(true, ((AAPSMocker.MockedBus) MainApp.bus()).notificationSent);
@@ -145,7 +144,6 @@ public class ProfileTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockStrings();
- AAPSMocker.prepareMockedBus();
when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump);
diff --git a/app/src/test/java/info/nightscout/androidaps/data/QuickWizardTest.java b/app/src/test/java/info/nightscout/androidaps/data/QuickWizardTest.java
index bda66cc121..820e8d34b1 100644
--- a/app/src/test/java/info/nightscout/androidaps/data/QuickWizardTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/data/QuickWizardTest.java
@@ -30,7 +30,7 @@ public class QuickWizardTest {
try {
array = new JSONArray("[" + data1 + "," + data2 + "]");
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
}
diff --git a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java
index 52de2d12c5..f3577e35c8 100644
--- a/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/interfaces/ConstraintsCheckerTest.java
@@ -2,11 +2,8 @@ package info.nightscout.androidaps.interfaces;
import android.content.Context;
-import com.squareup.otto.Bus;
-
import junit.framework.Assert;
-import org.json.JSONException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -20,12 +17,12 @@ import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.ConstraintChecker;
-import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
-import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSMA.OpenAPSMAPlugin;
import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
+import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin;
import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin;
import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
@@ -73,7 +70,7 @@ public class ConstraintsCheckerTest {
}
@Test
- public void isClosedLoopAllowedTest() {
+ public void isClosedLoopAllowedTest() {
when(SP.getString(R.string.key_aps_mode, "open")).thenReturn("closed");
objectivesPlugin.getObjectives().get(ObjectivesPlugin.INSTANCE.getMAXIOB_ZERO_CL_OBJECTIVE()).setStartedOn(0);
@@ -247,7 +244,7 @@ public class ConstraintsCheckerTest {
// Apply all limits
Constraint d = constraintChecker.getMaxIOBAllowed();
Assert.assertEquals(1.5d, d.value());
- Assert.assertEquals(d.getReasonList().toString(),2, d.getReasonList().size());
+ Assert.assertEquals(d.getReasonList().toString(), 2, d.getReasonList().size());
Assert.assertEquals("Safety: Limiting IOB to 1.5 U because of max value in preferences", d.getMostLimitedReasons());
}
@@ -278,7 +275,6 @@ public class ConstraintsCheckerTest {
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockConstraintsChecker();
AAPSMocker.mockApplicationContext();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockSP();
AAPSMocker.mockCommandQueue();
@@ -311,12 +307,4 @@ public class ConstraintsCheckerTest {
when(mainApp.getSpecificPluginsListByInterface(ConstraintsInterface.class)).thenReturn(constraintsPluginsList);
}
-
- class MockedBus extends Bus {
- @Override
- public void post(Object event) {
- notificationSent = true;
- }
- }
-
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java
index 0041f6f33a..1db142af2c 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/APSResultTest.java
@@ -179,7 +179,6 @@ public class APSResultTest {
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockTreatmentService();
AAPSMocker.mockL();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java
index 49a68cea4f..ecbc9d55c3 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.java
@@ -2,8 +2,6 @@ package info.nightscout.androidaps.plugins.aps.loop;
import android.content.Context;
-import com.squareup.otto.Bus;
-
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -31,7 +29,6 @@ public class LoopPluginTest {
VirtualPumpPlugin virtualPumpPlugin;
LoopPlugin loopPlugin;
- MockedBus bus;
@Test
public void testPluginInterface() {
@@ -91,17 +88,10 @@ public class LoopPluginTest {
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
- bus = new MockedBus();
- when(MainApp.bus()).thenReturn(bus);
-
loopPlugin = LoopPlugin.getPlugin();
virtualPumpPlugin = VirtualPumpPlugin.getPlugin();
when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin);
}
- class MockedBus extends Bus {
- }
-
-
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java
index f54105d994..39c5f3279e 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.java
@@ -13,8 +13,6 @@ import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.utils.SP;
-import static org.powermock.api.mockito.PowerMockito.mock;
-
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class, SP.class})
public class ConfigBuilderPluginTest {
@@ -29,7 +27,6 @@ public class ConfigBuilderPluginTest {
public void onStartTest() {
ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin();
configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true);
- Assert.assertEquals(true, ((AAPSMocker.MockedBus) MainApp.bus()).registered);
}
@Test
@@ -37,7 +34,6 @@ public class ConfigBuilderPluginTest {
ConfigBuilderPlugin configBuilderPlugin = ConfigBuilderPlugin.getPlugin();
configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, true);
configBuilderPlugin.setPluginEnabled(PluginType.GENERAL, false);
- Assert.assertEquals(false, ((AAPSMocker.MockedBus) MainApp.bus()).registered);
}
@Before
@@ -45,7 +41,6 @@ public class ConfigBuilderPluginTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
- AAPSMocker.prepareMockedBus();
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java
index 7c9514629d..371e970d23 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.java
@@ -8,8 +8,6 @@ import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import java.util.Date;
-
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.interfaces.Constraint;
@@ -82,7 +80,6 @@ public class ObjectivesPluginTest {
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java
index 938baf0611..1dabf0ff30 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPluginTest.java
@@ -229,7 +229,6 @@ public class SafetyPluginTest {
AAPSMocker.mockConstraintsChecker();
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt
new file mode 100644
index 0000000000..6d4a37882a
--- /dev/null
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt
@@ -0,0 +1,15 @@
+package info.nightscout.androidaps.plugins.constraints.signatureVerifier
+
+import org.junit.Test
+
+import org.junit.Assert.*
+
+class SignatureVerifierPluginTest {
+
+ @Test
+ fun singleCharUnMapTest() {
+ val key = "2ΙšÄΠΒϨÒÇeЄtЄЗž-*Ж*ZcHijЊÄœ<|x\"Ε"
+ val unmapped = SignatureVerifierPlugin.getPlugin().singleCharUnMap(key)
+ assertEquals("32:99:61:C4:A0:92:E8:D2:C7:65:04:74:04:17:7E:2D:2A:16:2A:5A:63:48:69:6A:0A:C4:53:3C:7C:78:22:95", unmapped)
+ }
+}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java
index 34c064a214..bd118d1391 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.java
@@ -1,4 +1,5 @@
package info.nightscout.androidaps.plugins.constraints.storage;
+
import android.os.Environment;
import android.os.StatFs;
@@ -15,13 +16,12 @@ import java.io.File;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
-import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.Constraint;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.mock;
-import static org.powermock.api.mockito.PowerMockito.whenNew;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import static org.powermock.api.mockito.PowerMockito.whenNew;
/**
* Created by Rumen on 06.03.2019.
@@ -72,7 +72,6 @@ public class StorageConstraintPluginTest extends StorageConstraintPlugin{
public void prepareMock() {
AAPSMocker.mockMainApp();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
mockedFile = mock(File.class);
mockedStatFs = mock(StatFs.class);
storageConstraintPlugin = StorageConstraintPlugin.getPlugin();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt
new file mode 100644
index 0000000000..49fd78ff13
--- /dev/null
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtilsKtTest.kt
@@ -0,0 +1,478 @@
+package info.nightscout.androidaps.plugins.constraints.versionChecker
+
+import info.nightscout.androidaps.MainApp
+import info.nightscout.androidaps.R
+import info.nightscout.androidaps.logging.L
+import info.nightscout.androidaps.utils.SP
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.ArgumentMatchers
+import org.mockito.Mockito.*
+import org.powermock.api.mockito.PowerMockito
+import org.powermock.core.classloader.annotations.PrepareForTest
+import org.powermock.modules.junit4.PowerMockRunner
+
+
+@RunWith(PowerMockRunner::class)
+class VersionCheckerUtilsKtTest {
+
+
+
+ @Test
+ fun `should keep 2 digit version`() {
+ assertEquals("1.2", "1.2".numericVersionPart())
+ }
+
+ @Test
+ fun `should keep 3 digit version`() {
+ assertEquals("1.2.3", "1.2.3".numericVersionPart())
+ }
+
+ @Test
+ fun `should keep 4 digit version`() {
+ assertEquals("1.2.3.4", "1.2.3.4".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version RC`() {
+ assertEquals("1.2", "1.2-RC1".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version RC old format`() {
+ assertEquals("1.2", "1.2RC1".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version RC without digit`() {
+ assertEquals("1.2", "1.2-RC".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version dev`() {
+ assertEquals("1.2", "1.2-dev".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version dev old format 1`() {
+ assertEquals("1.2", "1.2dev".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 2 digit version dev old format 2`() {
+ assertEquals("1.2", "1.2dev-a3".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 3 digit version RC`() {
+ assertEquals("1.2.3", "1.2.3-RC1".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip 4 digit version RC`() {
+ assertEquals("1.2.3.4", "1.2.3.4-RC5".numericVersionPart())
+ }
+
+ @Test
+ fun `should strip even with dot`() {
+ assertEquals("1.2", "1.2.RC5".numericVersionPart())
+ }
+
+
+ @Test
+ fun findVersionMatchesRegularVersion() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "2.2.2"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ val detectedVersion: String? = findVersion(buildGradle)
+ assertEquals("2.2.2", detectedVersion)
+ }
+
+
+ // In case we merge a "x.x.x-dev" into master, don't see it as update.
+ @Test
+ fun `should return null on non-digit versions on master`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "2.2.2-nefarious-underground-mod"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ val detectedVersion: String? = findVersion(buildGradle)
+ assertEquals(null, detectedVersion)
+ }
+
+ @Test
+ fun findVersionMatchesDoesNotMatchErrorResponse() {
+ val buildGradle = """Balls! No build.gradle here. Move along"""
+ val detectedVersion: String? = findVersion(buildGradle)
+ assertEquals(null, detectedVersion)
+ }
+
+ @Test
+ fun testVersionStrip() {
+ assertEquals("2.2.2", "2.2.2".versionStrip())
+ assertEquals("2.2.2", "2.2.2-dev".versionStrip())
+ assertEquals("2.2.2", "2.2.2dev".versionStrip())
+ assertEquals("2.2.2", """"2.2.2"""".versionStrip())
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update1`() {
+ prepareMainApp()
+
+ compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update2`() {
+ prepareMainApp()
+
+ compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1-dev")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update3`() {
+ prepareMainApp()
+
+ compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.1")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update4`() {
+ prepareMainApp()
+
+ compareWithCurrentVersion(newVersion = "2.2", currentVersion = "2.1.1")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update5`() {
+ prepareMainApp()
+ compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2-dev")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should find update6`() {
+ prepareMainApp()
+ compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2dev")
+
+ //verify(bus, times(1)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should not find update on fourth version digit`() {
+ prepareMainApp()
+ compareWithCurrentVersion(newVersion = "2.5.0", currentVersion = "2.5.0.1")
+
+ //verify(bus, times(0)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `should not find update on personal version with same number` (){
+ prepareMainApp()
+ compareWithCurrentVersion(newVersion = "2.5.0", currentVersion = "2.5.0-myversion")
+
+ //verify(bus, times(0)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find same version`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "2.2.2"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2")
+
+ //verify(bus, times(0)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version with longer number`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version after RC`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0-RC04")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version after RC 2 - typo`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0RC04")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version after RC 3 - typo`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.RC04")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version after RC 4 - typo`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.0.0"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.0.RC04")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `find higher version on multi digit numbers`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "3.7.12"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "3.7.9")
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `don't find higher version on higher but shorter version`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "2.2.2"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.3")
+
+ //verify(bus, times(0)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+ @Test
+ @PrepareForTest(MainApp::class, L::class, SP::class)
+ fun `don't find higher version if on next RC`() {
+ val buildGradle = """blabla
+ | android {
+ | aosenuthoae
+ | }
+ | version = "2.2.2"
+ | appName = "Aaoeu"
+ """.trimMargin()
+ prepareMainApp()
+ compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.3-RC")
+
+ //verify(bus, times(0)).post(any())
+
+ PowerMockito.verifyStatic(SP::class.java, times(1))
+ SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
+ PowerMockito.verifyNoMoreInteractions(SP::class.java)
+ }
+
+
+
+
+ @Test
+ @PrepareForTest(System::class)
+ fun `set time`() {
+ PowerMockito.spy(System::class.java)
+ PowerMockito.`when`(System.currentTimeMillis()).thenReturn(100L)
+
+ assertEquals(100L, System.currentTimeMillis())
+ }
+
+ private fun prepareMainApp() {
+ PowerMockito.mockStatic(MainApp::class.java)
+ val mainApp = mock(MainApp::class.java)
+ `when`(MainApp.instance()).thenReturn(mainApp)
+ `when`(MainApp.gs(ArgumentMatchers.anyInt())).thenReturn("some dummy string")
+ prepareSP()
+ }
+
+ private fun prepareSP() {
+ PowerMockito.mockStatic(SP::class.java)
+ }
+
+ private fun prepareLogging() {
+ PowerMockito.mockStatic(L::class.java)
+ `when`(L.isEnabled(any())).thenReturn(true)
+ }
+
+}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java
index 257392ca6e..c0cb9b70a2 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopDisableTest.java
@@ -65,7 +65,6 @@ public class ActionLoopDisableTest {
public void prepareTest() {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockCommandQueue();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java
index c5d9b81f56..d42549d222 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopEnableTest.java
@@ -65,7 +65,6 @@ public class ActionLoopEnableTest {
public void prepareTest() {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockCommandQueue();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java
index 755c56024d..c690681513 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResumeTest.java
@@ -63,7 +63,6 @@ public class ActionLoopResumeTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockNSUpload();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java
index 6b7c7f781f..67e22b0d5b 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopSuspendTest.java
@@ -80,7 +80,6 @@ public class ActionLoopSuspendTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
AAPSMocker.mockConfigBuilder();
AAPSMocker.mockNSUpload();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java
index 62447ac717..d1393c6824 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.java
@@ -6,29 +6,17 @@ import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
-import org.mockito.Mockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker;
-import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.db.TempTarget;
-import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
-import info.nightscout.androidaps.plugins.general.automation.elements.InputBg;
-import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration;
import info.nightscout.androidaps.plugins.general.automation.elements.InputString;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
-import info.nightscout.androidaps.plugins.general.overview.OverviewPlugin;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.SP;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.when;
-
@RunWith(PowerMockRunner.class)
@PrepareForTest({MainApp.class, SP.class, NSUpload.class})
public class ActionNotificationTest {
@@ -85,7 +73,6 @@ public class ActionNotificationTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockNSUpload();
actionNotification = new ActionNotification();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java
index 78a603701e..da1ce78cc7 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercentTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.actions;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.junit.Assert;
import org.junit.Before;
@@ -20,7 +19,7 @@ import info.nightscout.androidaps.queue.Callback;
import info.nightscout.androidaps.utils.SP;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, SP.class, Bus.class, ProfileFunctions.class})
+@PrepareForTest({MainApp.class, SP.class, ProfileFunctions.class})
public class ActionProfileSwitchPercentTest {
private ActionProfileSwitchPercent actionProfileSwitchPercent;
@@ -77,7 +76,6 @@ public class ActionProfileSwitchPercentTest {
public void prepareTest() {
AAPSMocker.mockMainApp();
AAPSMocker.mockSP();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockProfileFunctions();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java
index e62f573c2b..28f0278887 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchTest.java
@@ -45,7 +45,6 @@ public class ActionProfileSwitchTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockStrings();
AAPSMocker.mockTreatmentService();
- AAPSMocker.mockBus();
AAPSMocker.mockDatabaseHelper();
AAPSMocker.mockProfileFunctions();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java
index 4db3d79dc5..7254d85192 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.java
@@ -76,7 +76,6 @@ public class ActionSendSMSTest {
@Before
public void prepareTest() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockSP();
mockStatic(SmsManager.class);
SmsManager smsManager = mock(SmsManager.class);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java
index ff2baf6198..ed1141f0a4 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTargetTest.java
@@ -90,7 +90,6 @@ public class ActionStartTempTargetTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockSP();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockProfileFunctions();
treatmentsPlugin = AAPSMocker.mockTreatmentPlugin();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java
index 8a56a65459..dd2e335e86 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBgTest.java
@@ -31,7 +31,6 @@ public class InputBgTest {
@Before
public void prepare() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockProfileFunctions();
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java
index a9a0a4c91f..008b7a6743 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTargetTest.java
@@ -31,7 +31,6 @@ public class InputTempTargetTest {
@Before
public void prepare() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockProfileFunctions();
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java
index ab1851aefc..dd2a4a533e 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValueTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -28,7 +27,7 @@ import static org.mockito.ArgumentMatchers.anyDouble;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class})
public class TriggerAutosensValueTest {
long now = 1514766900000L;
@@ -115,7 +114,6 @@ public class TriggerAutosensValueTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockIobCobCalculatorPlugin();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java
index 002ac70488..1fb94492c9 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBgTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -30,7 +29,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class})
public class TriggerBgTest {
long now = 1514766900000L;
@@ -112,7 +111,6 @@ public class TriggerBgTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockIobCobCalculatorPlugin();
AAPSMocker.mockProfileFunctions();
@@ -126,7 +124,7 @@ public class TriggerBgTest {
try {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":214,\"mills\":" + (now - 1) + ",\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java
index b4965eb1d1..1d3a45a05e 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgoTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -25,7 +24,7 @@ import static org.mockito.ArgumentMatchers.anyDouble;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class})
public class TriggerBolusAgoTest {
long now = 1514766900000L;
@@ -109,7 +108,6 @@ public class TriggerBolusAgoTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockProfileFunctions();
PowerMockito.mockStatic(DateUtil.class);
AAPSMocker.mockTreatmentPlugin();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java
index 1681f00356..725cc6cfd5 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOBTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -16,8 +15,6 @@ import org.powermock.modules.junit4.PowerMockRunner;
import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.IobTotal;
-import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
import info.nightscout.androidaps.plugins.general.automation.elements.Comparator;
@@ -27,12 +24,10 @@ import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.SP;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyLong;
-import static org.powermock.api.mockito.PowerMockito.verifyNew;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class, L.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, SP.class, L.class})
public class TriggerCOBTest {
long now = 1514766900000L;
@@ -104,7 +99,6 @@ public class TriggerCOBTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
iobCobCalculatorPlugin = AAPSMocker.mockIobCobCalculatorPlugin();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java
index 722b6f1643..3d36968cec 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDeltaTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -32,7 +31,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, GlucoseStatus.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class, GlucoseStatus.class})
public class TriggerDeltaTest {
long now = 1514766900000L;
@@ -122,7 +121,6 @@ public class TriggerDeltaTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockIobCobCalculatorPlugin();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockApplicationContext();
@@ -154,7 +152,7 @@ public class TriggerDeltaTest {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":226,\"mills\":1514765100000,\"direction\":\"Flat\"}"))));
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java
index f2deee54a3..db39c05d2c 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerIobTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -28,7 +27,7 @@ import static org.mockito.ArgumentMatchers.anyLong;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, IobCobCalculatorPlugin.class})
public class TriggerIobTest {
long now = 1514766900000L;
@@ -103,7 +102,6 @@ public class TriggerIobTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
iobCobCalculatorPlugin = AAPSMocker.mockIobCobCalculatorPlugin();
AAPSMocker.mockProfileFunctions();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java
index 3e9a566615..9e1f713339 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocationTest.java
@@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.general.automation.triggers;
import android.location.Location;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -26,7 +25,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, LocationService.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, LocationService.class})
public class TriggerLocationTest {
@@ -35,7 +34,6 @@ public class TriggerLocationTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockApplicationContext();
PowerMockito.mockStatic(DateUtil.class);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java
index 9aea88e141..4b83495937 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercentTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, L.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, L.class})
public class TriggerProfilePercentTest {
private long now = 1514766900000L;
@@ -102,7 +101,6 @@ public class TriggerProfilePercentTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockL();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java
new file mode 100644
index 0000000000..9ba61af960
--- /dev/null
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnectionTest.java
@@ -0,0 +1,110 @@
+package info.nightscout.androidaps.plugins.general.automation.triggers;
+
+import com.google.common.base.Optional;
+
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import info.AAPSMocker;
+import info.nightscout.androidaps.MainApp;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
+import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctions;
+import info.nightscout.androidaps.plugins.general.automation.elements.Comparator;
+import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
+import info.nightscout.androidaps.utils.DateUtil;
+
+import static org.powermock.api.mockito.PowerMockito.when;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class, ConfigBuilderPlugin.class, System.class})
+public class TriggerPumpLastConnectionTest {
+
+ long now = 1514766900000L;
+
+ @Test
+ public void shouldRunTest() {
+// System.currentTimeMillis() is always 0
+// and so is every last connection time
+ VirtualPumpPlugin virtualPumpPlugin = VirtualPumpPlugin.getPlugin();
+ when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin);
+ Assert.assertEquals(0L, virtualPumpPlugin.lastDataTime());
+ TriggerPumpLastConnection t = new TriggerPumpLastConnection().setValue(110).comparator(Comparator.Compare.IS_EQUAL).lastRun(now - 1);
+ Assert.assertFalse(t.shouldRun());
+ when(DateUtil.now()).thenReturn(now + (10*60*1000)); // set current time to now + 10 min
+ t = new TriggerPumpLastConnection().setValue(110).comparator(Comparator.Compare.IS_EQUAL);
+ Assert.assertEquals(110, t.getValue(), 0.01d);
+ Assert.assertEquals(Comparator.Compare.IS_EQUAL, t.getComparator().getValue());
+ Assert.assertFalse(t.shouldRun());
+ t = new TriggerPumpLastConnection().setValue(10).comparator(Comparator.Compare.IS_EQUAL);
+ Assert.assertEquals(10, t.getValue(), 0.01d);
+ Assert.assertFalse(t.shouldRun()); // 0 == 10 -> FALSE
+ t = new TriggerPumpLastConnection().setValue(5).comparator(Comparator.Compare.IS_EQUAL_OR_GREATER);
+ Assert.assertTrue(t.shouldRun()); // 5 => 0 -> TRUE
+ t = new TriggerPumpLastConnection().setValue(310).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER);
+ Assert.assertFalse(t.shouldRun()); // 310 <= 0 -> FALSE
+ t = new TriggerPumpLastConnection().setValue(420).comparator(Comparator.Compare.IS_EQUAL);
+ Assert.assertFalse(t.shouldRun()); // 420 == 0 -> FALSE
+ }
+
+ @Test
+ public void copyConstructorTest() {
+ TriggerPumpLastConnection t = new TriggerPumpLastConnection().setValue(213).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER);
+ TriggerPumpLastConnection t1 = (TriggerPumpLastConnection) t.duplicate();
+ Assert.assertEquals(213, t1.getValue(), 0.01d);
+ Assert.assertEquals(Comparator.Compare.IS_EQUAL_OR_LESSER, t.getComparator().getValue());
+ }
+
+ @Test
+ public void executeTest() {
+ TriggerPumpLastConnection t = new TriggerPumpLastConnection().setValue(213).comparator(Comparator.Compare.IS_EQUAL_OR_LESSER);
+ t.executed(1);
+ Assert.assertEquals(1l, t.getLastRun());
+ }
+
+ String LBJson = "{\"data\":{\"comparator\":\"IS_EQUAL\",\"lastRun\":0,\"minutesAgo\":410},\"type\":\"info.nightscout.androidaps.plugins.general.automation.triggers.TriggerPumpLastConnection\"}";
+
+ @Test
+ public void toJSONTest() {
+ TriggerPumpLastConnection t = new TriggerPumpLastConnection().setValue(410).comparator(Comparator.Compare.IS_EQUAL);
+ Assert.assertEquals(LBJson, t.toJSON());
+ }
+
+ @Test
+ public void fromJSONTest() throws JSONException {
+ TriggerPumpLastConnection t = new TriggerPumpLastConnection().setValue(410).comparator(Comparator.Compare.IS_EQUAL);
+
+ TriggerPumpLastConnection t2 = (TriggerPumpLastConnection) Trigger.instantiate(new JSONObject(t.toJSON()));
+ Assert.assertEquals(Comparator.Compare.IS_EQUAL, t2.getComparator().getValue());
+ Assert.assertEquals(410, t2.getValue(), 0.01d);
+ }
+
+ @Test
+ public void iconTest() {
+ Assert.assertEquals(Optional.of(R.drawable.remove), new TriggerPumpLastConnection().icon());
+ }
+
+ @Test
+ public void friendlyNameTest() {
+ Assert.assertEquals(R.string.automation_trigger_pump_last_connection_label, new TriggerPumpLastConnection().friendlyName());
+ }
+
+
+ @Before
+ public void mock() {
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockConfigBuilder();
+ PowerMockito.mockStatic(DateUtil.class);
+ when(DateUtil.now()).thenReturn(now);
+
+ }
+
+}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java
index 21c69da80c..c9b463dfd0 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTimeTest.java
@@ -1,7 +1,5 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
-import com.squareup.otto.Bus;
-
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
@@ -22,7 +20,7 @@ import info.nightscout.androidaps.utils.T;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class})
+@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class})
public class TriggerRecurringTimeTest {
long now = 1514766900000L;
@@ -65,7 +63,6 @@ public class TriggerRecurringTimeTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
PowerMockito.mockStatic(DateUtil.class);
when(DateUtil.now()).thenReturn(now);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java
index 7e42d6ba48..03c7e5cda2 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTargetTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -22,11 +21,10 @@ import info.nightscout.androidaps.plugins.general.automation.elements.Comparator
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.DateUtil;
-import static org.mockito.ArgumentMatchers.any;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class})
+@PrepareForTest({MainApp.class, ProfileFunctions.class, DateUtil.class, TreatmentsPlugin.class})
public class TriggerTempTargetTest {
TreatmentsPlugin treatmentsPlugin;
@@ -86,7 +84,6 @@ public class TriggerTempTargetTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
treatmentsPlugin = AAPSMocker.mockTreatmentPlugin();
PowerMockito.mockStatic(DateUtil.class);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java
index 6e411fb2a5..6b36cc1fd3 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRangeTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -19,12 +18,11 @@ import info.AAPSMocker;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.utils.DateUtil;
-import info.nightscout.androidaps.utils.T;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class})
+@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class})
public class TriggerTimeRangeTest {
int now = 754;
@@ -98,7 +96,6 @@ public class TriggerTimeRangeTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
PowerMockito.mockStatic(DateUtil.class);
when(DateUtil.now()).thenReturn((long) now * 60000);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java
index cf8cfd7b75..b4b1794481 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.T;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, DateUtil.class, GregorianCalendar.class})
+@PrepareForTest({MainApp.class, DateUtil.class, GregorianCalendar.class})
public class TriggerTimeTest {
long now = 1514766900000L;
@@ -90,7 +89,6 @@ public class TriggerTimeTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
PowerMockito.mockStatic(DateUtil.class);
when(DateUtil.now()).thenReturn(now);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java
index 8156e483cc..d6eef521ed 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsidTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.automation.triggers;
import com.google.common.base.Optional;
-import com.squareup.otto.Bus;
import org.json.JSONException;
import org.json.JSONObject;
@@ -24,7 +23,7 @@ import info.nightscout.androidaps.utils.DateUtil;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, Bus.class, NetworkChangeReceiver.class, DateUtil.class})
+@PrepareForTest({MainApp.class, NetworkChangeReceiver.class, DateUtil.class})
public class TriggerWifiSsidTest {
long now = 1514766900000L;
@@ -36,22 +35,22 @@ public class TriggerWifiSsidTest {
TriggerWifiSsid t = new TriggerWifiSsid().setValue("aSSID").comparator(Comparator.Compare.IS_EQUAL);
- e.wifiConnected = false;
+ e.setWifiConnected(false);
Assert.assertFalse(t.shouldRun());
- e.wifiConnected = true;
- e.ssid = "otherSSID";
+ e.setWifiConnected(true);
+ e.setSsid("otherSSID");
Assert.assertFalse(t.shouldRun());
- e.wifiConnected = true;
- e.ssid = "aSSID";
+ e.setWifiConnected(true);
+ e.setSsid("aSSID");
Assert.assertTrue(t.shouldRun());
t.lastRun(now - 1);
Assert.assertFalse(t.shouldRun());
t = new TriggerWifiSsid().setValue("aSSID").comparator(Comparator.Compare.IS_NOT_AVAILABLE);
- e.wifiConnected = false;
+ e.setWifiConnected(false);
Assert.assertTrue(t.shouldRun());
// no network data
@@ -102,7 +101,6 @@ public class TriggerWifiSsidTest {
@Before
public void mock() {
AAPSMocker.mockMainApp();
- AAPSMocker.mockBus();
PowerMockito.mockStatic(NetworkChangeReceiver.class);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java
index a1b21fe9a2..f8496a71b2 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialogTest.java
@@ -68,7 +68,6 @@ public class NewNSTreatmentDialogTest {
AAPSMocker.mockStrings();
PowerMockito.mockStatic(NSUpload.class);
AAPSMocker.mockTreatmentService();
- AAPSMocker.mockBus();
AAPSMocker.mockDatabaseHelper();
NSProfilePlugin profilePlugin = NSProfilePlugin.getPlugin();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java
index 0400532e9d..b0fde44b08 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.plugins.general.nsclient;
import android.content.Context;
-import com.squareup.otto.Bus;
import org.junit.Before;
import org.junit.Test;
@@ -34,10 +33,7 @@ public class NsClientReceiverDelegateTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
- Bus bus = MainApp.bus();
- Context context = MainApp.instance().getApplicationContext();
-
- sut = new NsClientReceiverDelegate(context, bus);
+ sut = new NsClientReceiverDelegate();
}
@Test
@@ -64,67 +60,67 @@ public class NsClientReceiverDelegateTest {
when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false);
when(SP.getString(anyInt(), anyString())).thenReturn("");
EventNetworkChange ev = new EventNetworkChange();
- ev.ssid = "";
+ ev.setSsid("");
- ev.mobileConnected = true;
- ev.wifiConnected = true;
+ ev.setMobileConnected(true);
+ ev.setWifiConnected(true);
assertTrue(sut.calculateStatus(ev));
- ev.ssid = "test";
+ ev.setSsid("test");
when(SP.getString(anyInt(), anyString())).thenReturn("\"test\"");
assertTrue(sut.calculateStatus(ev));
- ev.ssid = "\"test\"";
+ ev.setSsid("\"test\"");
assertTrue(sut.calculateStatus(ev));
- ev.wifiConnected = false;
+ ev.setWifiConnected(false);
assertTrue(sut.calculateStatus(ev));
// wifiOnly = true
// allowRoaming = true as well
when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(true);
- ev.wifiConnected = true;
+ ev.setWifiConnected(true);
assertTrue(sut.calculateStatus(ev));
- ev.wifiConnected = false;
+ ev.setWifiConnected(false);
assertTrue(!sut.calculateStatus(ev));
// wifiOnly = false
// allowRoaming = false as well
when(SP.getBoolean(anyInt(), anyBoolean())).thenReturn(false);
- ev.wifiConnected = false;
- ev.roaming = true;
+ ev.setWifiConnected(false);
+ ev.setRoaming(true);
assertTrue(!sut.calculateStatus(ev));
// wifiOnly = false
// allowRoaming = true
when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false);
when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true);
- ev.wifiConnected = false;
- ev.roaming = true;
+ ev.setWifiConnected(false);
+ ev.setRoaming(true);
assertTrue(sut.calculateStatus(ev));
// wifiOnly = true
// allowRoaming = true
when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true);
when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true);
- ev.wifiConnected = false;
- ev.roaming = true;
+ ev.setWifiConnected(false);
+ ev.setRoaming(true);
assertTrue(!sut.calculateStatus(ev));
// wifiOnly = true
// allowRoaming = true
when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(true);
when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(true);
- ev.wifiConnected = true;
- ev.roaming = true;
+ ev.setWifiConnected(true);
+ ev.setRoaming(true);
assertTrue(sut.calculateStatus(ev));
// wifiOnly = false
// allowRoaming = false
when(SP.getBoolean(R.string.key_ns_wifionly, false)).thenReturn(false);
when(SP.getBoolean(R.string.key_ns_allowroaming, true)).thenReturn(false);
- ev.wifiConnected = true;
- ev.roaming = true;
+ ev.setWifiConnected(true);
+ ev.setRoaming(true);
assertTrue(sut.calculateStatus(ev));
}
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.java
index dd41f9873a..4d0ed00415 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.java
@@ -8,8 +8,6 @@ import org.mockito.stubbing.Answer;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
-import java.util.Date;
-
import info.AAPSMocker;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
@@ -28,9 +26,9 @@ import static org.powermock.api.mockito.PowerMockito.when;
@PrepareForTest({SmsCommunicatorPlugin.class, L.class, SP.class, MainApp.class, DateUtil.class})
public class AuthRequestTest {
- SmsCommunicatorPlugin smsCommunicatorPlugin;
- Sms sentSms;
- boolean actionCalled = false;
+ private SmsCommunicatorPlugin smsCommunicatorPlugin;
+ private Sms sentSms;
+ private boolean actionCalled = false;
@Test
public void doTests() {
@@ -45,14 +43,14 @@ public class AuthRequestTest {
// Check if SMS requesting code is sent
AuthRequest authRequest = new AuthRequest(smsCommunicatorPlugin, requester, "Request text", "ABC", action);
- Assert.assertEquals(sentSms.phoneNumber, "aNumber");
- Assert.assertEquals(sentSms.text, "Request text");
+ Assert.assertEquals(sentSms.getPhoneNumber(), "aNumber");
+ Assert.assertEquals(sentSms.getText(), "Request text");
// wrong reply
actionCalled = false;
authRequest.action("EFG");
- Assert.assertEquals(sentSms.phoneNumber, "aNumber");
- Assert.assertEquals(sentSms.text, "Wrong code. Command cancelled.");
+ Assert.assertEquals(sentSms.getPhoneNumber(), "aNumber");
+ Assert.assertEquals(sentSms.getText(), "Wrong code. Command cancelled.");
Assert.assertFalse(actionCalled);
// correct reply
@@ -77,12 +75,6 @@ public class AuthRequestTest {
@Before
public void prepareTests() {
- smsCommunicatorPlugin = mock(SmsCommunicatorPlugin.class);
- doAnswer((Answer) invocation -> {
- sentSms = invocation.getArgument(0);
- return null;
- }).when(smsCommunicatorPlugin).sendSMS(any(Sms.class));
-
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
@@ -90,5 +82,12 @@ public class AuthRequestTest {
AAPSMocker.mockStrings();
mockStatic(DateUtil.class);
+
+ smsCommunicatorPlugin = mock(SmsCommunicatorPlugin.class);
+ doAnswer((Answer) invocation -> {
+ sentSms = invocation.getArgument(0);
+ return null;
+ }).when(smsCommunicatorPlugin).sendSMS(any(Sms.class));
+
}
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.java
index f4d61e56eb..f6a4712b72 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsActionTest.java
@@ -41,7 +41,7 @@ public class SmsActionTest {
};
smsAction.run();
Assert.assertEquals(result, "B");
- Assert.assertEquals(smsAction.aDouble, 1d, 0.000001d);
+ Assert.assertEquals(smsAction.aDouble(), 1d, 0.000001d);
smsAction = new SmsAction(1d, 2) {
@Override
@@ -51,8 +51,8 @@ public class SmsActionTest {
};
smsAction.run();
Assert.assertEquals(result, "C");
- Assert.assertEquals(smsAction.aDouble, 1d, 0.000001d);
- Assert.assertEquals(smsAction.secondInteger.intValue(), 2);
+ Assert.assertEquals(smsAction.aDouble(), 1d, 0.000001d);
+ Assert.assertEquals(smsAction.secondInteger(), 2);
smsAction = new SmsAction("aString", 3) {
@Override
@@ -62,8 +62,8 @@ public class SmsActionTest {
};
smsAction.run();
Assert.assertEquals(result, "D");
- Assert.assertEquals(smsAction.aString, "aString");
- Assert.assertEquals(smsAction.secondInteger.intValue(), 3);
+ Assert.assertEquals(smsAction.aString(), "aString");
+ Assert.assertEquals(smsAction.secondInteger(), 3);
smsAction = new SmsAction(4) {
@Override
@@ -73,7 +73,7 @@ public class SmsActionTest {
};
smsAction.run();
Assert.assertEquals(result, "E");
- Assert.assertEquals(smsAction.anInteger.intValue(), 4);
+ Assert.assertEquals(smsAction.anInteger(), 4);
smsAction = new SmsAction(5, 6) {
@Override
@@ -83,8 +83,8 @@ public class SmsActionTest {
};
smsAction.run();
Assert.assertEquals(result, "F");
- Assert.assertEquals(smsAction.anInteger.intValue(), 5);
- Assert.assertEquals(smsAction.secondInteger.intValue(), 6);
+ Assert.assertEquals(smsAction.anInteger(), 5);
+ Assert.assertEquals(smsAction.secondInteger(), 6);
}
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java
index abc29216b0..c757840c1f 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java
@@ -25,7 +25,6 @@ import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PluginType;
import info.nightscout.androidaps.interfaces.ProfileInterface;
-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.configBuilder.ConfigBuilderPlugin;
@@ -50,6 +49,7 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.powermock.api.mockito.PowerMockito.doAnswer;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
+import static org.powermock.api.mockito.PowerMockito.spy;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@@ -57,7 +57,7 @@ import static org.powermock.api.mockito.PowerMockito.when;
L.class, SP.class, MainApp.class, DateUtil.class, ProfileFunctions.class,
TreatmentsPlugin.class, SmsManager.class, IobCobCalculatorPlugin.class,
CommandQueue.class, ConfigBuilderPlugin.class, NSUpload.class, ProfileInterface.class,
- SimpleProfilePlugin.class, XdripCalibrations.class, VirtualPumpPlugin.class
+ SimpleProfilePlugin.class, XdripCalibrations.class, VirtualPumpPlugin.class, LoopPlugin.class
})
public class SmsCommunicatorPluginTest {
@@ -67,27 +67,29 @@ public class SmsCommunicatorPluginTest {
private boolean hasBeenRun = false;
+ private VirtualPumpPlugin virtualPumpPlugin;
+
@Test
public void processSettingsTest() {
// called from constructor
- Assert.assertEquals("1234", smsCommunicatorPlugin.allowedNumbers.get(0));
- Assert.assertEquals("5678", smsCommunicatorPlugin.allowedNumbers.get(1));
- Assert.assertEquals(2, smsCommunicatorPlugin.allowedNumbers.size());
+ Assert.assertEquals("1234", smsCommunicatorPlugin.getAllowedNumbers().get(0));
+ Assert.assertEquals("5678", smsCommunicatorPlugin.getAllowedNumbers().get(1));
+ Assert.assertEquals(2, smsCommunicatorPlugin.getAllowedNumbers().size());
}
@Test
public void isCommandTest() {
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BOLUS", ""));
- smsCommunicatorPlugin.messageToConfirm = null;
+ smsCommunicatorPlugin.setMessageToConfirm(null);
Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", ""));
- smsCommunicatorPlugin.messageToConfirm = new AuthRequest(smsCommunicatorPlugin, new Sms("1234", "ddd"), "RequestText", "ccode", new SmsAction() {
+ smsCommunicatorPlugin.setMessageToConfirm(new AuthRequest(smsCommunicatorPlugin, new Sms("1234", "ddd"), "RequestText", "ccode", new SmsAction() {
@Override
public void run() {
}
- });
+ }));
Assert.assertTrue(smsCommunicatorPlugin.isCommand("BLB", "1234"));
Assert.assertFalse(smsCommunicatorPlugin.isCommand("BLB", "2345"));
- smsCommunicatorPlugin.messageToConfirm = null;
+ smsCommunicatorPlugin.setMessageToConfirm(null);
}
@Test
@@ -101,82 +103,82 @@ public class SmsCommunicatorPluginTest {
Sms sms;
// SMS from not allowed number should be ignored
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("12", "aText");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertTrue(sms.ignored);
- Assert.assertEquals("aText", smsCommunicatorPlugin.messages.get(0).text);
+ Assert.assertTrue(sms.getIgnored());
+ Assert.assertEquals("aText", smsCommunicatorPlugin.getMessages().get(0).getText());
//UNKNOWN
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "UNKNOWN");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("UNKNOWN", smsCommunicatorPlugin.messages.get(0).text);
+ Assert.assertEquals("UNKNOWN", smsCommunicatorPlugin.getMessages().get(0).getText());
//BG
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BG");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BG", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("IOB:"));
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("Last BG: 100"));
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("COB: 10(2)g"));
+ Assert.assertEquals("BG", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("IOB:"));
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Last BG: 100"));
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("COB: 10(2)g"));
// LOOP : test remote control disabled
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP STATUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("Remote command is not allowed"));
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Remote command is not allowed"));
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//LOOP STATUS : disabled
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP STATUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP STATUS : suspended
when(loopPlugin.minutesToEndOfSuspend()).thenReturn(10);
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(true);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP STATUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Suspended (10 m)", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Suspended (10 m)", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP STATUS : enabled
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP STATUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP STATUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP : wrong format
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP DISABLE : already disabled
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP DISABLE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop is disabled", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP DISABLE : from enabled
hasBeenRun = false;
@@ -185,22 +187,22 @@ public class SmsCommunicatorPluginTest {
hasBeenRun = true;
return null;
}).when(loopPlugin).setPluginEnabled(PluginType.LOOP, false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP DISABLE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop has been disabled Temp basal canceled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop has been disabled Temp basal canceled", smsCommunicatorPlugin.getMessages().get(1).getText());
Assert.assertTrue(hasBeenRun);
//LOOP ENABLE : already enabled
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP ENABLE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop is enabled", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP ENABLE : from disabled
hasBeenRun = false;
@@ -209,143 +211,205 @@ public class SmsCommunicatorPluginTest {
hasBeenRun = true;
return null;
}).when(loopPlugin).setPluginEnabled(PluginType.LOOP, true);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP ENABLE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop has been enabled", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP ENABLE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop has been enabled", smsCommunicatorPlugin.getMessages().get(1).getText());
Assert.assertTrue(hasBeenRun);
//LOOP RESUME : already enabled
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP RESUME");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP RESUME", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Loop resumed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP RESUME", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Loop resumed", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP SUSPEND 1 2: wrong format
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP SUSPEND 1 2");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP SUSPEND 1 2", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP SUSPEND 1 2", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP SUSPEND 0 : wrong duration
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP SUSPEND 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP SUSPEND 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong duration", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP SUSPEND 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong duration", smsCommunicatorPlugin.getMessages().get(1).getText());
//LOOP SUSPEND 100 : suspend for 100 min + correct answer
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP SUSPEND 100");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP SUSPEND 100", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To suspend loop for 100 minutes reply with code "));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP SUSPEND 100", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To suspend loop for 100 minutes reply with code "));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Loop suspended Temp basal canceled", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Loop suspended Temp basal canceled", smsCommunicatorPlugin.getMessages().get(3).getText());
//LOOP SUSPEND 200 : limit to 180 min + wrong answer
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP SUSPEND 200");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP SUSPEND 200", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To suspend loop for 180 minutes reply with code "));
- passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP SUSPEND 200", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To suspend loop for 180 minutes reply with code "));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
// ignore from other number
smsCommunicatorPlugin.processSms(new Sms("5678", passCode));
smsCommunicatorPlugin.processSms(new Sms("1234", "XXXX"));
- Assert.assertEquals("XXXX", smsCommunicatorPlugin.messages.get(3).text);
- Assert.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.messages.get(4).text);
+ Assert.assertEquals("XXXX", smsCommunicatorPlugin.getMessages().get(3).getText());
+ Assert.assertEquals("Wrong code. Command cancelled.", smsCommunicatorPlugin.getMessages().get(4).getText());
//then correct code should not work
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(5).text);
- Assert.assertEquals(6, smsCommunicatorPlugin.messages.size()); // processed as common message
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(5).getText());
+ Assert.assertEquals(6, smsCommunicatorPlugin.getMessages().size()); // processed as common message
//LOOP BLABLA
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "LOOP BLABLA");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("LOOP BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//TREATMENTS REFRESH
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "TREATMENTS REFRESH");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("TREATMENTS REFRESH", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("TREATMENTS REFRESH"));
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("TREATMENTS REFRESH", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("TREATMENTS REFRESH"));
//TREATMENTS BLA BLA
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "TREATMENTS BLA BLA");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("TREATMENTS BLA BLA", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("TREATMENTS BLA BLA", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//TREATMENTS BLABLA
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "TREATMENTS BLABLA");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("TREATMENTS BLABLA", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("TREATMENTS BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//NSCLIENT RESTART
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "NSCLIENT RESTART");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("NSCLIENT RESTART", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("NSCLIENT RESTART"));
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("NSCLIENT RESTART", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("NSCLIENT RESTART"));
//NSCLIENT BLA BLA
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "NSCLIENT BLA BLA");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("NSCLIENT BLA BLA", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("NSCLIENT BLA BLA", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//NSCLIENT BLABLA
when(loopPlugin.isEnabled(PluginType.LOOP)).thenReturn(true);
when(loopPlugin.isSuspended()).thenReturn(false);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "NSCLIENT BLABLA");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertFalse(sms.ignored);
- Assert.assertEquals("NSCLIENT BLABLA", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("NSCLIENT BLABLA", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//PUMP
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PUMP");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PUMP", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Virtual Pump", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PUMP", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Virtual Pump", smsCommunicatorPlugin.getMessages().get(1).getText());
+ //HELP
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "HELP");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("HELP", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("PUMP"));
+
+ //HELP PUMP
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "HELP PUMP");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("HELP PUMP", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("PUMP"));
+
+ //SMS : wrong format
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "SMS");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("SMS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ //SMS STOP
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "SMS DISABLE");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("SMS DISABLE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To disable the SMS Remote Service reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("SMS Remote Service stopped. To reactivate it, use AAPS on master smartphone."));
+
+ //TARGET : wrong format
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "TARGET");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertFalse(sms.getIgnored());
+ Assert.assertEquals("TARGET", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ //TARGET MEAL
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "TARGET MEAL");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("TARGET MEAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To set the Temp Target"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("set successfully"));
+
+ //TARGET STOP/CANCEL
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "TARGET STOP");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("TARGET STOP", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To cancel Temp Target reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Temp Target canceled successfully"));
}
@Test
@@ -353,92 +417,92 @@ public class SmsCommunicatorPluginTest {
Sms sms;
//PROFILE
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//PROFILE
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE LIST (no profile interface)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE LIST");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Not configured", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Not configured", smsCommunicatorPlugin.getMessages().get(1).getText());
ProfileInterface profileInterface = mock(SimpleProfilePlugin.class);
when(ConfigBuilderPlugin.getPlugin().getActiveProfileInterface()).thenReturn(profileInterface);
//PROFILE LIST (no profile defined)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE LIST");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Not configured", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Not configured", smsCommunicatorPlugin.getMessages().get(1).getText());
when(profileInterface.getProfile()).thenReturn(AAPSMocker.getValidProfileStore());
//PROFILE STATUS
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE STATUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE STATUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals(AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE STATUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals(AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE LIST
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE LIST");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("1. " + AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE LIST", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("1. " + AAPSMocker.TESTPROFILENAME, smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE 2 (non existing)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE 2");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE 2", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE 2", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE 1 0(wrong percentage)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE 1 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE 1 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE 1 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE 0(wrong index)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("PROFILE 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//PROFILE 1(OK)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE 1");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE 1", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To switch profile to someProfile 100% reply with code"));
+ Assert.assertEquals("PROFILE 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To switch profile to someProfile 100% reply with code"));
//PROFILE 1 90(OK)
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "PROFILE 1 90");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("PROFILE 1 90", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To switch profile to someProfile 90% reply with code"));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("PROFILE 1 90", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To switch profile to someProfile 90% reply with code"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Profile switch created", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Profile switch created", smsCommunicatorPlugin.getMessages().get(3).getText());
}
@Test
@@ -446,85 +510,85 @@ public class SmsCommunicatorPluginTest {
Sms sms;
//BASAL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//BASAL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//BASAL CANCEL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL CANCEL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL CANCEL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To stop temp basal reply with code"));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("BASAL CANCEL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To stop temp basal reply with code"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Temp basal canceled\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Temp basal canceled"));
//BASAL a%
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL a%");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL a%", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL a%", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//BASAL 10% 0
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL 10% 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL 10% 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyBasalPercentConstraints(any(), any())).thenReturn(new Constraint<>(20));
//BASAL 20% 20
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL 20% 20");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To start basal 20% for 20 min reply with code"));
- passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("BASAL 20% 20", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start basal 20% for 20 min reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Temp basal 20% for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Temp basal 20% for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText());
//BASAL a
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL a");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL a", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL a", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//BASAL 1 0
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL 1 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BASAL 1 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyBasalConstraints(any(), any())).thenReturn(new Constraint<>(1d));
//BASAL 1 20
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BASAL 1 20");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BASAL 1 20", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To start basal 1.00U/h for 20 min reply with code"));
- passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("BASAL 1 20", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start basal 1.00U/h for 20 min reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Temp basal 1.00U/h for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Temp basal 1.00U/h for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText());
}
@@ -533,58 +597,58 @@ public class SmsCommunicatorPluginTest {
Sms sms;
//EXTENDED
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//EXTENDED
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("EXTENDED", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//EXTENDED CANCEL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED CANCEL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED CANCEL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To stop extended bolus reply with code"));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("EXTENDED CANCEL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To stop extended bolus reply with code"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Extended bolus canceled\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Extended bolus canceled"));
//EXTENDED a%
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED a%");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("EXTENDED a%", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d));
//EXTENDED 1 0
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED 1 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED 1 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("EXTENDED 1 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//EXTENDED 1 20
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "EXTENDED 1 20");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("EXTENDED 1 20", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To start extended bolus 1.00U for 20 min reply with code"));
- passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("EXTENDED 1 20", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To start extended bolus 1.00U for 20 min reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Extended bolus 1.00U for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Extended bolus 1.00U for 20 min started successfully\nVirtual Pump", smsCommunicatorPlugin.getMessages().get(3).getText());
}
@Test
@@ -592,75 +656,91 @@ public class SmsCommunicatorPluginTest {
Sms sms;
//BOLUS
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//BOLUS
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BOLUS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d));
when(DateUtil.now()).thenReturn(1000L);
//BOLUS 1
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS 1");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote bolus not available. Try again later.", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(0d));
when(DateUtil.now()).thenReturn(Constants.remoteBolusMinDistance + 1002L);
//BOLUS 0
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BOLUS 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//BOLUS a
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS a");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("BOLUS a", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(MainApp.getConstraintChecker().applyExtendedBolusConstraints(any())).thenReturn(new Constraint<>(1d));
when(MainApp.getConstraintChecker().applyBolusConstraints(any())).thenReturn(new Constraint<>(1d));
//BOLUS 1
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS 1");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To deliver bolus 1.00U reply with code"));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To deliver bolus 1.00U reply with code"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Bolus 1.00U delivered successfully\nVirtual Pump", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().contains("Bolus 1.00U delivered successfully"));
//BOLUS 1 (Suspended pump)
- smsCommunicatorPlugin.lastRemoteBolusTime = 0;
- PumpInterface pump = mock(VirtualPumpPlugin.class);
- when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(pump);
- when(pump.isSuspended()).thenReturn(true);
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setLastRemoteBolusTime(0);
+ when(virtualPumpPlugin.isSuspended()).thenReturn(true);
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "BOLUS 1");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Pump suspended", smsCommunicatorPlugin.messages.get(1).text);
- when(pump.isSuspended()).thenReturn(false);
+ Assert.assertEquals("BOLUS 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Pump suspended", smsCommunicatorPlugin.getMessages().get(1).getText());
+ when(virtualPumpPlugin.isSuspended()).thenReturn(false);
+
+ //BOLUS 1 a
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "BOLUS 1 a");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("BOLUS 1 a", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ //BOLUS 1 MEAL
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "BOLUS 1 MEAL");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("BOLUS 1 MEAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To deliver meal bolus 1.00U reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Meal Bolus 1.00U delivered successfully\nVirtual Pump\nTarget 5.0 for 45 minutes", smsCommunicatorPlugin.getMessages().get(3).getText());
}
@Test
@@ -668,47 +748,128 @@ public class SmsCommunicatorPluginTest {
Sms sms;
//CAL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "CAL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("CAL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("CAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
//CAL
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "CAL");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("CAL", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("CAL", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
//CAL 0
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "CAL 0");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("CAL 0", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("Wrong format", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("CAL 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
when(XdripCalibrations.sendIntent(any())).thenReturn(true);
//CAL 1
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
sms = new Sms("1234", "CAL 1");
smsCommunicatorPlugin.processSms(sms);
- Assert.assertEquals("CAL 1", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertTrue(smsCommunicatorPlugin.messages.get(1).text.contains("To send calibration 1.00 reply with code"));
- String passCode = smsCommunicatorPlugin.messageToConfirm.confirmCode;
+ Assert.assertEquals("CAL 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To send calibration 1.00 reply with code"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
- Assert.assertEquals(passCode, smsCommunicatorPlugin.messages.get(2).text);
- Assert.assertEquals("Calibration sent. Receiving must be enabled in xDrip.", smsCommunicatorPlugin.messages.get(3).text);
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertEquals("Calibration sent. Receiving must be enabled in xDrip.", smsCommunicatorPlugin.getMessages().get(3).getText());
+ }
+
+ @Test
+ public void processCarbsTest() {
+ Sms sms;
+
+ when(DateUtil.now()).thenReturn(1000000L);
+ when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(false);
+ //CAL
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Remote command is not allowed", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ when(SP.getBoolean(R.string.key_smscommunicator_remotecommandsallowed, false)).thenReturn(true);
+
+ //CARBS
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(0));
+
+ //CARBS 0
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 0");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 0", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("Wrong format", smsCommunicatorPlugin.getMessages().get(1).getText());
+
+ when(MainApp.getConstraintChecker().applyCarbsConstraints(any())).thenReturn(new Constraint<>(1));
+
+ //CARBS 1
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 1");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 1", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at"));
+ String passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully"));
+
+ //CARBS 1 a
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 1 a");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 1 a", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Wrong format"));
+
+ //CARBS 1 00
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 1 00");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 1 00", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("Wrong format"));
+
+ //CARBS 1 12:01
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 1 12:01");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 1 12:01", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at 12:01PM reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully"));
+
+ //CARBS 1 3:01AM
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
+ sms = new Sms("1234", "CARBS 1 3:01AM");
+ smsCommunicatorPlugin.processSms(sms);
+ Assert.assertEquals("CARBS 1 3:01AM", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(1).getText().contains("To enter 1g at 03:01AM reply with code"));
+ passCode = smsCommunicatorPlugin.getMessageToConfirm().getConfirmCode();
+ smsCommunicatorPlugin.processSms(new Sms("1234", passCode));
+ Assert.assertEquals(passCode, smsCommunicatorPlugin.getMessages().get(2).getText());
+ Assert.assertTrue(smsCommunicatorPlugin.getMessages().get(3).getText().startsWith("Carbs 1g entered successfully"));
}
@Test
public void sendNotificationToAllNumbers() {
- smsCommunicatorPlugin.messages = new ArrayList<>();
+ smsCommunicatorPlugin.setMessages(new ArrayList<>());
smsCommunicatorPlugin.sendNotificationToAllNumbers("abc");
- Assert.assertEquals("abc", smsCommunicatorPlugin.messages.get(0).text);
- Assert.assertEquals("abc", smsCommunicatorPlugin.messages.get(1).text);
+ Assert.assertEquals("abc", smsCommunicatorPlugin.getMessages().get(0).getText());
+ Assert.assertEquals("abc", smsCommunicatorPlugin.getMessages().get(1).getText());
}
@Before
@@ -718,7 +879,6 @@ public class SmsCommunicatorPluginTest {
AAPSMocker.mockSP();
AAPSMocker.mockL();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
AAPSMocker.mockProfileFunctions();
AAPSMocker.mockTreatmentPlugin();
AAPSMocker.mockTreatmentService();
@@ -736,17 +896,18 @@ public class SmsCommunicatorPluginTest {
PowerMockito.when(IobCobCalculatorPlugin.getPlugin().getCobInfo(false, "SMS COB")).thenReturn(new CobInfo(10d, 2d));
mockStatic(XdripCalibrations.class);
- mockStatic(DateUtil.class);
+ spy(DateUtil.class);
mockStatic(SmsManager.class);
SmsManager smsManager = mock(SmsManager.class);
when(SmsManager.getDefault()).thenReturn(smsManager);
when(SP.getString(R.string.key_smscommunicator_allowednumbers, "")).thenReturn("1234;5678");
- smsCommunicatorPlugin = SmsCommunicatorPlugin.getPlugin();
+ smsCommunicatorPlugin = SmsCommunicatorPlugin.INSTANCE;
smsCommunicatorPlugin.setPluginEnabled(PluginType.GENERAL, true);
+ mockStatic(LoopPlugin.class);
loopPlugin = mock(LoopPlugin.class);
- when(MainApp.getSpecificPlugin(LoopPlugin.class)).thenReturn(loopPlugin);
+ when(LoopPlugin.getPlugin()).thenReturn(loopPlugin);
Mockito.doAnswer(invocation -> {
Callback callback = invocation.getArgument(1);
@@ -797,8 +958,10 @@ public class SmsCommunicatorPluginTest {
return null;
}).when(AAPSMocker.queue).extendedBolus(anyDouble(), anyInt(), any(Callback.class));
- VirtualPumpPlugin virtualPumpPlugin = VirtualPumpPlugin.getPlugin();
+ virtualPumpPlugin = mock(VirtualPumpPlugin.class);
when(ConfigBuilderPlugin.getPlugin().getActivePump()).thenReturn(virtualPumpPlugin);
+ when(virtualPumpPlugin.shortStatus(anyBoolean())).thenReturn("Virtual Pump");
+ when(virtualPumpPlugin.isSuspended()).thenReturn(false);
}
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsTest.java
index 5f7af11a67..a406a35f9d 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsTest.java
@@ -28,19 +28,19 @@ public class SmsTest {
when(smsMessage.getMessageBody()).thenReturn("aBody");
Sms sms = new Sms(smsMessage);
- Assert.assertEquals(sms.phoneNumber, "aNumber");
- Assert.assertEquals(sms.text, "aBody");
- Assert.assertTrue(sms.received);
+ Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
+ Assert.assertEquals(sms.getText(), "aBody");
+ Assert.assertTrue(sms.getReceived());
sms = new Sms("aNumber", "aBody");
- Assert.assertEquals(sms.phoneNumber, "aNumber");
- Assert.assertEquals(sms.text, "aBody");
- Assert.assertTrue(sms.sent);
+ Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
+ Assert.assertEquals(sms.getText(), "aBody");
+ Assert.assertTrue(sms.getSent());
sms = new Sms("aNumber", R.string.insulin_unit_shortname);
- Assert.assertEquals(sms.phoneNumber, "aNumber");
- Assert.assertEquals(sms.text, MainApp.gs(R.string.insulin_unit_shortname));
- Assert.assertTrue(sms.sent);
+ Assert.assertEquals(sms.getPhoneNumber(), "aNumber");
+ Assert.assertEquals(sms.getText(), MainApp.gs(R.string.insulin_unit_shortname));
+ Assert.assertTrue(sms.getSent());
Assert.assertEquals(sms.toString(), "SMS from aNumber: U");
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt
deleted file mode 100644
index 9a60941f36..0000000000
--- a/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt
+++ /dev/null
@@ -1,230 +0,0 @@
-package info.nightscout.androidaps.plugins.general.versionChecker
-
-import com.squareup.otto.Bus
-import info.nightscout.androidaps.MainApp
-import info.nightscout.androidaps.R
-import info.nightscout.androidaps.logging.L
-import info.nightscout.androidaps.utils.SP
-import org.junit.Assert.assertEquals
-import org.junit.Test
-import org.junit.runner.RunWith
-import org.mockito.ArgumentMatchers
-import org.mockito.Mockito.*
-import org.powermock.api.mockito.PowerMockito
-import org.powermock.core.classloader.annotations.PrepareForTest
-import org.powermock.modules.junit4.PowerMockRunner
-
-
-@RunWith(PowerMockRunner::class)
-class VersionCheckerUtilsKtTest {
- @Test
- fun findVersionMatchesRegularVersion() {
- val buildGradle = """blabla
- | android {
- | aosenuthoae
- | }
- | version = "2.2.2"
- | appName = "Aaoeu"
- """.trimMargin()
- val detectedVersion: String? = findVersion(buildGradle)
- assertEquals("2.2.2", detectedVersion)
- }
-
-
- // In case we merge a "x.x.x-dev" into master, don't see it as update.
- @Test
- fun `should return null on non-digit versions on master`() {
- val buildGradle = """blabla
- | android {
- | aosenuthoae
- | }
- | version = "2.2.2-nefarious-underground-mod"
- | appName = "Aaoeu"
- """.trimMargin()
- val detectedVersion: String? = findVersion(buildGradle)
- assertEquals(null, detectedVersion)
- }
-
- @Test
- fun findVersionMatchesDoesNotMatchErrorResponse() {
- val buildGradle = """Balls! No build.gradle here. Move along"""
- val detectedVersion: String? = findVersion(buildGradle)
- assertEquals(null, detectedVersion)
- }
-
- @Test
- fun testVersionStrip() {
- assertEquals("2.2.2", "2.2.2".versionStrip())
- assertEquals("2.2.2", "2.2.2-dev".versionStrip())
- assertEquals("2.2.2", "2.2.2dev".versionStrip())
- assertEquals("2.2.2", """"2.2.2"""".versionStrip())
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update1`() {
- val bus = prepareBus()
-
- compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
-
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update2`() {
- val bus = prepareBus()
-
- compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.2.1-dev")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update3`() {
- val bus = prepareBus()
-
- compareWithCurrentVersion(newVersion = "2.2.3", currentVersion = "2.1")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update4`() {
- val bus = prepareBus()
-
- compareWithCurrentVersion(newVersion = "2.2", currentVersion = "2.1.1")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update5`() {
- val bus = prepareBus()
- compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2-dev")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `should find update6`() {
- val bus = prepareBus()
- compareWithCurrentVersion(newVersion = "2.2.1", currentVersion = "2.2dev")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `find same version`() {
- val buildGradle = """blabla
- | android {
- | aosenuthoae
- | }
- | version = "2.2.2"
- | appName = "Aaoeu"
- """.trimMargin()
- val bus = prepareBus()
- compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2")
-
- verify(bus, times(0)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_time_this_version_detected), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
- @Test
- @PrepareForTest(MainApp::class, L::class, SP::class)
- fun `find higher version`() {
- val buildGradle = """blabla
- | android {
- | aosenuthoae
- | }
- | version = "3.0"
- | appName = "Aaoeu"
- """.trimMargin()
- val bus = prepareBus()
- compareWithCurrentVersion(findVersion(buildGradle), currentVersion = "2.2.2")
-
- //verify(bus, times(1)).post(any())
-
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.getLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyStatic(SP::class.java, times(1))
- SP.putLong(eq(R.string.key_last_versionchecker_warning), ArgumentMatchers.anyLong())
- PowerMockito.verifyNoMoreInteractions(SP::class.java)
- }
-
-
- @Test
- @PrepareForTest(System::class)
- fun `set time`() {
- PowerMockito.spy(System::class.java)
- PowerMockito.`when`(System.currentTimeMillis()).thenReturn(100L)
-
- assertEquals(100L, System.currentTimeMillis())
- }
-
- private fun prepareBus(): Bus {
- PowerMockito.mockStatic(MainApp::class.java)
- val mainApp = mock(MainApp::class.java)
- `when`(MainApp.instance()).thenReturn(mainApp)
- val bus = mock(Bus::class.java)
- `when`(MainApp.bus()).thenReturn(bus)
- `when`(MainApp.gs(ArgumentMatchers.anyInt())).thenReturn("some dummy string")
- prepareSP()
- return bus
- }
-
- private fun prepareSP() {
- PowerMockito.mockStatic(SP::class.java)
- }
-
- private fun prepareLogging() {
- PowerMockito.mockStatic(L::class.java)
- `when`(L.isEnabled(any())).thenReturn(true)
- }
-
-}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculatorPlugin/GlucoseStatusTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculatorPlugin/GlucoseStatusTest.java
index 19e497b834..6d91bea911 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculatorPlugin/GlucoseStatusTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/iob/iobCobCalculatorPlugin/GlucoseStatusTest.java
@@ -153,7 +153,7 @@ public class GlucoseStatusTest {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":226,\"mills\":1514765100000,\"direction\":\"Flat\"}"))));
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
@@ -165,7 +165,7 @@ public class GlucoseStatusTest {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":216,\"mills\":1514766800000,\"direction\":\"Flat\"}")))); // +2
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":216,\"mills\":1514766600000,\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
@@ -180,7 +180,7 @@ public class GlucoseStatusTest {
try {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":228,\"mills\":1514764800000,\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
@@ -190,7 +190,7 @@ public class GlucoseStatusTest {
try {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":214,\"mills\":1514766900000,\"direction\":\"Flat\"}"))));
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
@@ -211,7 +211,7 @@ public class GlucoseStatusTest {
list.add(new BgReading(new NSSgv(new JSONObject("{\"mgdl\":" + (latest_reading + (i*2)) + ",\"mills\":" + (end_time - (1000 * 60 * i)) + ",\"direction\":\"Flat\"}"))));
}
} catch (JSONException e) {
- e.printStackTrace();
+ throw new RuntimeException(e);
}
return list;
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java
index 1ea781941f..8e7784f5b8 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.java
@@ -62,7 +62,6 @@ public class ComboPluginTest {
public void prepareMocks() throws Exception {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockCommandQueue();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java
index c7407e7af5..322655caaa 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPluginTest.java
@@ -62,7 +62,6 @@ public class DanaRPluginTest {
public void prepareMocks() throws Exception {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java
index 0ed6c5f7cd..289df3d186 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgressTest.java
@@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/28/2018.
@@ -27,7 +27,6 @@ public class MsgBolusProgressTest {
AAPSMocker.mockSP();
AAPSMocker.mockL();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
Treatment t = new Treatment();
MsgBolusProgress packet = new MsgBolusProgress(3D, t);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java
index 5dc65b7228..4032ef7dad 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStopTest.java
@@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/28/2018.
@@ -26,7 +26,7 @@ public class MsgBolusStopTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
+ AAPSMocker.mockStrings();
Treatment t = new Treatment();
MsgBolusStop packet = new MsgBolusStop(1d,t);
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java
index 32b82270ab..83dbdcd12c 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValueTest.java
@@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump;
import info.nightscout.androidaps.plugins.treatments.Treatment;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/28/2018.
@@ -28,7 +28,6 @@ public class MsgCheckValueTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
Treatment t = new Treatment();
MsgCheckValue packet = new MsgCheckValue();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java
index b597c69062..45664cdfb7 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgErrorTest.java
@@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/28/2018.
@@ -26,7 +26,6 @@ public class MsgErrorTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
AAPSMocker.mockNSUpload();
MsgError packet = new MsgError();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java
index c4d40abcc7..2bfec9baee 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllTest.java
@@ -11,7 +11,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/30/2018.
@@ -26,7 +26,6 @@ public class MsgHistoryAllTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
AAPSMocker.mockDatabaseHelper();
MsgHistoryAll packet = new MsgHistoryAll();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java
index 11aa667f1e..f7860fbaa2 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBolusTest.java
@@ -26,7 +26,6 @@ public class MsgInitConnStatusBolusTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
MsgInitConnStatusBolus packet = new MsgInitConnStatusBolus();
// test message decoding
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java
index 467ccc2f9b..0b1d956ded 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusOptionTest.java
@@ -27,7 +27,6 @@ public class MsgInitConnStatusOptionTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
AAPSMocker.mockConfigBuilder();
MsgInitConnStatusOption packet = new MsgInitConnStatusOption();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java
index 1da818b5bc..b5ef46e9b2 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTimeTest.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaR.comm;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -11,7 +12,7 @@ import info.nightscout.androidaps.logging.L;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.utils.SP;
-import static org.junit.Assert.*;
+import static org.junit.Assert.assertEquals;
/**
* Created by Rumen Georgiev on 8/30/2018.
@@ -22,14 +23,6 @@ import static org.junit.Assert.*;
public class MsgInitConnStatusTimeTest {
@Test
public void runTest() {
- AAPSMocker.mockMainApp();
- AAPSMocker.mockApplicationContext();
- AAPSMocker.mockSP();
- AAPSMocker.mockL();
- AAPSMocker.mockBus();
- AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockCommandQueue();
- AAPSMocker.mockDanaRPlugin();
MsgInitConnStatusTime packet = new MsgInitConnStatusTime();
// test message decoding
@@ -57,4 +50,13 @@ public class MsgInitConnStatusTimeTest {
return ret;
}
+ @Before
+ public void mock() {
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockSP();
+ AAPSMocker.mockL();
+ AAPSMocker.mockConfigBuilder();
+ AAPSMocker.mockCommandQueue();
+ }
}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java
index f49cb5eace..ed4fb83a10 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetBasalProfileTest.java
@@ -25,7 +25,6 @@ public class MsgSetBasalProfileTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
MsgSetBasalProfile packet = new MsgSetBasalProfile((byte) 1, createArray(24,1));
// test message decoding
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java
index 5a272c8cf6..cfb17d9ab5 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetSingleBasalProfileTest.java
@@ -25,7 +25,6 @@ public class MsgSetSingleBasalProfileTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
MsgSetSingleBasalProfile packet = new MsgSetSingleBasalProfile(createArray(24, 2));
// test message decoding
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java
index 7680e6c5a9..2ba1be66a7 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMealTest.java
@@ -26,7 +26,6 @@ public class MsgSettingMealTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
MsgSettingMeal packet = new MsgSettingMeal();
// test message decoding
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java
index ca249e016c..269a6a0304 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPluginTest.java
@@ -62,7 +62,6 @@ public class DanaRSPluginTest {
public void prepareMocks() throws Exception {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java
index 309644d7f0..a866ce73a7 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_EventsTest.java
@@ -93,7 +93,6 @@ public class DanaRS_Packet_APS_History_EventsTest extends DanaRS_Packet_APS_Hist
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
- AAPSMocker.mockBus();
SPMocker.prepareMock();
SP.putString("profile", AAPSMocker.getValidProfileStore().getData().toString());
AAPSMocker.mockConfigBuilder();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java
index a530749e27..762403142f 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Basal_RateTest.java
@@ -26,7 +26,6 @@ public class DanaRS_Packet_Basal_Get_Basal_RateTest {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
- AAPSMocker.mockBus();
AAPSMocker.mockL();
DanaRS_Packet_Basal_Get_Basal_Rate packet = new DanaRS_Packet_Basal_Get_Basal_Rate();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java
index da023edd1a..8feee88e7a 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Basal_RateTest.java
@@ -26,7 +26,6 @@ public class DanaRS_Packet_Basal_Get_Profile_Basal_RateTest extends DanaRS_Packe
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
- AAPSMocker.mockBus();
AAPSMocker.mockL();
// test if pumpRofile array is set right
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java
index 9931e02bd6..73e67f6830 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Bolus_OptionTest.java
@@ -28,7 +28,6 @@ public class DanaRS_Packet_Bolus_Get_Bolus_OptionTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
DanaRS_Packet_Bolus_Get_Bolus_Option packet = new DanaRS_Packet_Bolus_Get_Bolus_Option();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java
index c04ccd2767..f41a686201 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest.java
@@ -25,8 +25,8 @@ public class DanaRS_Packet_Bolus_Set_Step_Bolus_StopTest extends DanaRS_Packet_B
public void runTest() {
AAPSMocker.mockMainApp();
AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockStrings();
AAPSMocker.mockSP();
- AAPSMocker.mockBus();
AAPSMocker.mockL();
DanaRS_Packet_Bolus_Set_Step_Bolus_Stop testPacket = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(1d , new Treatment());
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java
index 858abdbfd7..b3dde0b102 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Pump_CheckTest.java
@@ -27,7 +27,6 @@ public class DanaRS_Packet_General_Get_Pump_CheckTest {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
DanaRS_Packet_General_Get_Pump_Check packet = new DanaRS_Packet_General_Get_Pump_Check();
// test params
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java
index bf83dcee13..0d209edb33 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_CompleteTest.java
@@ -30,7 +30,6 @@ public class DanaRS_Packet_Notify_Delivery_CompleteTest {
AAPSMocker.mockSP();
AAPSMocker.mockL();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
DanaRS_Packet_Notify_Delivery_Complete packet = new DanaRS_Packet_Notify_Delivery_Complete(0.5d,new Treatment());
// test params
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java
index 7d2603991b..ce3554cf74 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Notify_Delivery_Rate_DisplayTest.java
@@ -30,7 +30,6 @@ public class DanaRS_Packet_Notify_Delivery_Rate_DisplayTest {
AAPSMocker.mockSP();
AAPSMocker.mockL();
AAPSMocker.mockStrings();
- AAPSMocker.mockBus();
DanaRS_Packet_Notify_Delivery_Rate_Display packet = new DanaRS_Packet_Notify_Delivery_Rate_Display(1, new Treatment());
// test params
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java
index 288df852f9..71ae9b1d51 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2PluginTest.java
@@ -66,7 +66,6 @@ public class DanaRv2PluginTest {
public void prepareMocks() throws Exception {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java
index 33c64510cd..0dc1f174c9 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTable_rv2Test.java
@@ -25,7 +25,6 @@ public class MessageHashTable_rv2Test {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
MessageHashTableRv2 hashTableRv2 = MessageHashTableRv2.INSTANCE;
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java
index acc2675c92..d7910d313d 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -20,18 +21,10 @@ import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, SP.class, L.class, DanaRv2Plugin.class, DanaRPlugin.class, ConfigBuilderPlugin.class, CommandQueue.class})
+@PrepareForTest({MainApp.class, SP.class, L.class, ConfigBuilderPlugin.class, CommandQueue.class})
public class MsgCheckValue_v2Test {
@Test
public void runTest() {
- AAPSMocker.mockMainApp();
- AAPSMocker.mockApplicationContext();
- AAPSMocker.mockSP();
- AAPSMocker.mockL();
- AAPSMocker.mockBus();
- AAPSMocker.mockDanaRPlugin();
- AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockCommandQueue();
Treatment t = new Treatment();
MsgCheckValue_v2 packet = new MsgCheckValue_v2();
// test message decoding
@@ -56,4 +49,13 @@ public class MsgCheckValue_v2Test {
return ret;
}
+ @Before
+ public void mock() {
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockSP();
+ AAPSMocker.mockL();
+ AAPSMocker.mockConfigBuilder();
+ AAPSMocker.mockCommandQueue();
+ }
}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java
index 334c556ccb..fc70670e31 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2Test.java
@@ -28,7 +28,6 @@ public class MsgHistoryEvents_v2Test {
AAPSMocker.mockApplicationContext();
AAPSMocker.mockSP();
AAPSMocker.mockL();
- AAPSMocker.mockBus();
AAPSMocker.mockDatabaseHelper();
AAPSMocker.mockTreatmentPlugin();
AAPSMocker.mockTreatmentService();
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java
index 50f80550b5..d554c33e8d 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -18,16 +19,10 @@ import static org.junit.Assert.*;
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, SP.class, L.class, DanaRv2Plugin.class, DanaRPlugin.class})
+@PrepareForTest({MainApp.class, SP.class, L.class})
public class MsgSetHistoryEntry_v2Test {
@Test
public void runTest() {
- AAPSMocker.mockMainApp();
- AAPSMocker.mockApplicationContext();
- AAPSMocker.mockSP();
- AAPSMocker.mockL();
- AAPSMocker.mockBus();
- AAPSMocker.mockDanaRPlugin();
MsgSetHistoryEntry_v2 initializerTest = new MsgSetHistoryEntry_v2((byte) 1, System.currentTimeMillis(), 1, 0);
MsgSetHistoryEntry_v2 packet = new MsgSetHistoryEntry_v2();
@@ -57,4 +52,11 @@ public class MsgSetHistoryEntry_v2Test {
return ret;
}
+ @Before
+ public void mock() {
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockSP();
+ AAPSMocker.mockL();
+ }
}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java
index 70a7a36f0e..8cb45dc5ee 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2Test.java
@@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.danaRv2.comm;
+import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
@@ -19,17 +20,10 @@ import static org.junit.Assert.*;
*/
@RunWith(PowerMockRunner.class)
-@PrepareForTest({MainApp.class, SP.class, L.class, DanaRv2Plugin.class, DanaRPlugin.class})
+@PrepareForTest({MainApp.class, SP.class, L.class})
public class MsgStatusTempBasal_v2Test {
@Test
public void runTest() {
- AAPSMocker.mockMainApp();
- AAPSMocker.mockApplicationContext();
- AAPSMocker.mockSP();
- AAPSMocker.mockL();
- AAPSMocker.mockBus();
- AAPSMocker.mockDanaRPlugin();
-
MsgStatusTempBasal_v2 packet = new MsgStatusTempBasal_v2();
DanaRPump pump = DanaRPump.getInstance();
// test message decoding
@@ -58,4 +52,12 @@ public class MsgStatusTempBasal_v2Test {
return ret;
}
+ @Before
+ public void mock() {
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockSP();
+ AAPSMocker.mockL();
+ }
+
}
\ No newline at end of file
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java
index e24fe1f0ea..6ceb3cc438 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/MedtronicHistoryDataUTest.java
@@ -3,22 +3,24 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm;
import android.util.Log;
import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
import java.util.List;
+import info.AAPSMocker;
+import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistoryPage;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder;
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry;
+import info.nightscout.androidaps.utils.SP;
+
+import static org.mockito.Mockito.when;
//import uk.org.lidalia.slf4jtest.TestLogger;
//import uk.org.lidalia.slf4jtest.TestLoggerFactory;
/**
* Created by andy on 3/10/19.
*/
-@Ignore
public class MedtronicHistoryDataUTest {
//TestLogger LOGGER = TestLoggerFactory.getTestLogger(MedtronicHistoryDataUTest.class);
@@ -31,7 +33,7 @@ public class MedtronicHistoryDataUTest {
// Logger LOGGER = LoggerFactory.getLogger(MedtronicHistoryDataUTest.class);
- @Before
+ //@Before
public void setup() {
System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
@@ -44,10 +46,30 @@ public class MedtronicHistoryDataUTest {
// } finally {
// logger.removeAppender(appender);
// }
+
+
+ AAPSMocker.mockMainApp();
}
- @Test
+ @Before
+ public void prepareMocks() throws Exception {
+
+ System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "trace");
+ AAPSMocker.mockMainApp();
+ AAPSMocker.mockConfigBuilder();
+ AAPSMocker.mockStrings();
+ AAPSMocker.mockApplicationContext();
+ AAPSMocker.mockSP();
+ AAPSMocker.mockCommandQueue();
+
+ when(SP.getString(R.string.key_danars_address, "")).thenReturn("");
+
+ //danaRPlugin = DanaRPlugin.getPlugin();
+ }
+
+
+ //@Test
public void testTBR() throws Exception {
RawHistoryPage historyPage = new RawHistoryPage();
@@ -87,4 +109,27 @@ public class MedtronicHistoryDataUTest {
}
+
+ // @Test
+ public void testJRoth_2111() throws Exception {
+
+ byte[] historyPageData = ByteUtil
+ .createByteArrayFromString("01 03 03 00 8E 85 52 48 13 33 00 AB 89 12 48 13 00 16 00 AB 89 12 48 13 33 34 AD 89 12 48 13 00 16 01 AD 89 12 48 13 01 01 01 00 B8 8A 52 48 13 01 08 08 00 9F 8C 52 48 13 33 00 91 8F 12 48 13 00 16 00 91 8F 12 48 13 33 00 92 8F 12 48 13 00 16 03 92 8F 12 48 13 33 00 BA A7 12 48 13 00 16 04 BA A7 12 48 13 01 19 19 00 AF B0 52 48 13 33 00 8C 8A 13 48 13 00 16 04 8C 8A 13 48 13 33 00 9D A8 13 48 13 00 16 04 9D A8 13 48 13 33 00 AA 85 14 48 13 00 16 04 AA 85 14 48 13 33 00 8D A1 14 48 13 00 16 04 8D A1 14 48 13 33 10 89 BA 14 48 13 00 16 01 89 BA 14 48 13 33 00 AD 88 15 48 13 00 16 00 AD 88 15 48 13 33 00 AF 88 15 48 13 00 16 01 AF 88 15 48 13 01 1D 1D 00 95 8D 55 48 13 33 00 95 92 15 48 13 00 16 04 95 92 15 48 13 33 1E B7 9C 15 48 13 00 16 01 B7 9C 15 48 13 33 00 AA A6 15 48 13 00 16 00 AA A6 15 48 13 33 00 AC A6 15 48 13 00 16 04 AC A6 15 48 13 01 02 02 00 B7 A6 55 48 13 01 01 01 00 A6 AC 55 48 13 33 00 B3 8D 16 48 13 00 16 04 B3 8D 16 48 13 33 00 B7 97 16 48 13 00 16 04 B7 97 16 48 13 33 18 A7 B2 16 48 13 00 16 01 A7 B2 16 48 13 33 00 8B B8 16 48 13 00 16 00 8B B8 16 48 13 33 00 8D B8 16 48 13 00 16 03 8D B8 16 48 13 33 18 AE 85 17 48 13 00 16 01 AE 85 17 48 13 33 00 92 8A 17 48 13 00 16 00 92 8A 17 48 13 33 00 94 8A 17 48 13 00 16 01 94 8A 17 48 13 01 02 02 00 9F 8A 57 48 13 33 06 AC 8F 17 48 13 00 16 01 AC 8F 17 48 13 01 02 02 00 B8 8F 57 48 13 33 00 98 94 17 48 13 00 16 00 98 94 17 48 13 33 0C 9A 94 17 48 13 00 16 01 9A 94 17 48 13 01 02 02 00 A5 94 57 48 13 33 00 9C 99 17 48 13 00 16 00 9C 99 17 48 13 33 00 9E 99 17 48 13 00 16 01 9E 99 17 48 13 01 02 02 00 A9 99 57 48 13 01 02 02 00 84 9F 57 48 13 01 02 02 00 A7 A6 57 48 13 33 00 A4 AB 17 48 13 00 16 00 A4 AB 17 48 13 01 02 02 00 B0 AB 57 48 13 33 00 A7 B0 17 48 13 00 16 02 A7 B0 17 48 13 01 01 01 00 B2 B0 57 48 13 33 00 AD BA 17 48 13 00 16 04 AD BA 17 48 13 07 00 00 05 3A A8 13 6D A8 13 05 0C 00 E8 00 00 00 00 05 3A 00 F6 12 04 44 52 00 00 04 44 52 00 00 00 00 00 00 04 44 64 35 00 00 00 35 0C 00 E8 00 00 00 06 0A 1D 66 80 81 60 09 13 0C 0A 8D 82 00 09 13 1A 00 9A 82 00 09 13 1A 01 AF 82 00 09 13 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 05 28");
+
+ RawHistoryPage historyPage = new RawHistoryPage();
+ historyPage.appendData(historyPageData);
+
+ List pumpHistoryEntries = decoder.processPageAndCreateRecords(historyPage);
+
+ System.out.println("PumpHistoryEntries: " + pumpHistoryEntries.size());
+
+ Log.d("Test", "Log.d");
+ //LOGGER.debug("Logger.debug");
+
+ for (PumpHistoryEntry pumpHistoryEntry : pumpHistoryEntries) {
+ Log.d("MedtronicHistoryDataUTest", pumpHistoryEntry.toString());
+ }
+ }
+
+
}
diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java
index 9ef75ef597..0a9d68c1ad 100644
--- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.java
@@ -35,7 +35,6 @@ public class VirtualPumpPluginUTest {
public void prepareMocks() throws Exception {
AAPSMocker.mockMainApp();
AAPSMocker.mockConfigBuilder();
- AAPSMocker.mockBus();
AAPSMocker.mockStrings();
AAPSMocker.mockCommandQueue();
AAPSMocker.mockSP();
diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java
index 63a626d8f7..baaccd95b3 100644
--- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueTest.java
@@ -2,9 +2,6 @@ package info.nightscout.androidaps.queue;
import android.content.Context;
-import com.squareup.otto.Bus;
-import com.squareup.otto.ThreadEnforcer;
-
import junit.framework.Assert;
import org.json.JSONException;
@@ -26,8 +23,8 @@ import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.interfaces.Constraint;
import info.nightscout.androidaps.interfaces.PumpInterface;
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin;
-import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin;
+import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.queue.commands.Command;
import info.nightscout.androidaps.utils.ToastUtils;
@@ -140,9 +137,6 @@ public class CommandQueueTest extends CommandQueue {
String message = null;
PowerMockito.doNothing().when(ToastUtils.class, "showToastInUiThread", context, message);
- Bus bus = new Bus(ThreadEnforcer.ANY);
-
- when(MainApp.bus()).thenReturn(bus);
when(MainApp.gs(0)).thenReturn("");
PowerMockito.mockStatic(TreatmentsPlugin.class);
diff --git a/app/src/test/java/info/nightscout/androidaps/utils/RoundTest.java b/app/src/test/java/info/nightscout/androidaps/utils/RoundTest.java
index fb444804bc..568b67057e 100644
--- a/app/src/test/java/info/nightscout/androidaps/utils/RoundTest.java
+++ b/app/src/test/java/info/nightscout/androidaps/utils/RoundTest.java
@@ -12,9 +12,16 @@ public class RoundTest {
@Test
public void roundToTest() throws Exception {
- assertEquals( 0.55d, Round.roundTo(0.54d, 0.05d), 0.00000001d );
- assertEquals( 1d, Round.roundTo(1.49d, 1d), 0.00000001d );
- assertEquals( 0d, Round.roundTo(0d, 1d), 0.00000001d );
+ assertEquals( 0.55d, Round.roundTo(0.54d, 0.05d), 0.00000000000000000001d );
+ assertEquals( -3.26d, Round.roundTo(-3.2553715764602713d, 0.01d), 0.00000000000000000001d );
+ assertEquals( 0.816d, Round.roundTo(0.8156666666666667d, 0.001d), 0.00000000000000000001d );
+ assertEquals( 0.235d, Round.roundTo(0.235d, 0.001d), 0.00000000000000000001d );
+ assertEquals( 0.3d, Round.roundTo(0.3d, 0.1d), 0.00000000000000001d );
+ assertEquals( 0.0017d, Round.roundTo(0.0016960652144170627d, 0.0001d), 0.00000000000000000001d );
+ assertEquals( 0.0078d, Round.roundTo(0.007804436682291013d, 0.0001d), 0.00000000000000000001d );
+ assertEquals( 0.6d, Round.roundTo(0.6d, 0.05d), 0.00000000000000000001d );
+ assertEquals( 1d, Round.roundTo(1.49d, 1d), 0.00000000000000000001d );
+ assertEquals( 0d, Round.roundTo(0d, 1d), 0.00000000000000000001d );
}
@Test
diff --git a/build.gradle b/build.gradle
index 31658346b6..f8456a8971 100644
--- a/build.gradle
+++ b/build.gradle
@@ -8,9 +8,9 @@ buildscript {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
- classpath 'com.android.tools.build:gradle:3.5.1'
- classpath 'com.google.gms:google-services:4.3.2'
- classpath 'io.fabric.tools:gradle:1.31.0'
+ classpath 'com.android.tools.build:gradle:3.5.2'
+ classpath 'com.google.gms:google-services:4.3.3'
+ classpath 'io.fabric.tools:gradle:1.31.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
diff --git a/icons/battery-burnin/battery-charging-wireless-10-burnin.svg b/icons/battery-burnin/battery-charging-wireless-10-burnin.svg
new file mode 100644
index 0000000000..2888abf209
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-10-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-20-burnin.svg b/icons/battery-burnin/battery-charging-wireless-20-burnin.svg
new file mode 100644
index 0000000000..77d52751d7
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-20-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-30-burnin.svg b/icons/battery-burnin/battery-charging-wireless-30-burnin.svg
new file mode 100644
index 0000000000..9ffa356436
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-30-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-40-burnin.svg b/icons/battery-burnin/battery-charging-wireless-40-burnin.svg
new file mode 100644
index 0000000000..d9ccc46027
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-40-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-50-burnin.svg b/icons/battery-burnin/battery-charging-wireless-50-burnin.svg
new file mode 100644
index 0000000000..4d4905046c
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-50-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-60-burnin.svg b/icons/battery-burnin/battery-charging-wireless-60-burnin.svg
new file mode 100644
index 0000000000..e3c4ba5c44
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-60-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-70-burnin.svg b/icons/battery-burnin/battery-charging-wireless-70-burnin.svg
new file mode 100644
index 0000000000..fe26b5e93d
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-70-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-80-burnin.svg b/icons/battery-burnin/battery-charging-wireless-80-burnin.svg
new file mode 100644
index 0000000000..c949afb1c8
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-80-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-90-burnin.svg b/icons/battery-burnin/battery-charging-wireless-90-burnin.svg
new file mode 100644
index 0000000000..13677dc328
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-90-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-charging-wireless-burnin.svg b/icons/battery-burnin/battery-charging-wireless-burnin.svg
new file mode 100644
index 0000000000..f074b89d34
--- /dev/null
+++ b/icons/battery-burnin/battery-charging-wireless-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-burnin/battery-unknown-burnin.svg b/icons/battery-burnin/battery-unknown-burnin.svg
new file mode 100644
index 0000000000..b0cc3bba40
--- /dev/null
+++ b/icons/battery-burnin/battery-unknown-burnin.svg
@@ -0,0 +1,4 @@
+
+
diff --git a/icons/battery-source/mask-burnin-battery-raw.svg b/icons/battery-source/mask-burnin-battery-raw.svg
new file mode 100644
index 0000000000..e2ab79f2a1
--- /dev/null
+++ b/icons/battery-source/mask-burnin-battery-raw.svg
@@ -0,0 +1,55 @@
+
+
diff --git a/icons/battery-source/mask-burnin-battery.svg b/icons/battery-source/mask-burnin-battery.svg
new file mode 100644
index 0000000000..09be5da8a9
--- /dev/null
+++ b/icons/battery-source/mask-burnin-battery.svg
@@ -0,0 +1,223 @@
+
+
diff --git a/icons/battery/battery-charging-wireless-10.svg b/icons/battery/battery-charging-wireless-10.svg
new file mode 100644
index 0000000000..d6dbd7febc
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-10.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-20.svg b/icons/battery/battery-charging-wireless-20.svg
new file mode 100644
index 0000000000..9e4badedc9
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-20.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-30.svg b/icons/battery/battery-charging-wireless-30.svg
new file mode 100644
index 0000000000..7da87ce966
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-30.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-40.svg b/icons/battery/battery-charging-wireless-40.svg
new file mode 100644
index 0000000000..b9aaad2b0f
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-40.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-50.svg b/icons/battery/battery-charging-wireless-50.svg
new file mode 100644
index 0000000000..705a61c55b
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-50.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-60.svg b/icons/battery/battery-charging-wireless-60.svg
new file mode 100644
index 0000000000..b2cd9f7734
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-60.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-70.svg b/icons/battery/battery-charging-wireless-70.svg
new file mode 100644
index 0000000000..608a404882
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-70.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-80.svg b/icons/battery/battery-charging-wireless-80.svg
new file mode 100644
index 0000000000..c604743cc3
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-80.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless-90.svg b/icons/battery/battery-charging-wireless-90.svg
new file mode 100644
index 0000000000..246886ad08
--- /dev/null
+++ b/icons/battery/battery-charging-wireless-90.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-charging-wireless.svg b/icons/battery/battery-charging-wireless.svg
new file mode 100644
index 0000000000..b36143c4c2
--- /dev/null
+++ b/icons/battery/battery-charging-wireless.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-outline.svg b/icons/battery/battery-outline.svg
new file mode 100644
index 0000000000..e05e71b288
--- /dev/null
+++ b/icons/battery/battery-outline.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/battery/battery-unknown.svg b/icons/battery/battery-unknown.svg
new file mode 100644
index 0000000000..8e117be5cb
--- /dev/null
+++ b/icons/battery/battery-unknown.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/icons/complications-source/ic_br_cob_iob_orig.svg b/icons/complications-source/ic_br_cob_iob_orig.svg
new file mode 100644
index 0000000000..f650e12d99
--- /dev/null
+++ b/icons/complications-source/ic_br_cob_iob_orig.svg
@@ -0,0 +1,93 @@
+
+
+
+
diff --git a/icons/complications-source/ic_cob_detailed_orig.svg b/icons/complications-source/ic_cob_detailed_orig.svg
new file mode 100644
index 0000000000..e599774c5d
--- /dev/null
+++ b/icons/complications-source/ic_cob_detailed_orig.svg
@@ -0,0 +1,83 @@
+
+
+
+
diff --git a/icons/complications-source/ic_cob_iob_orig.svg b/icons/complications-source/ic_cob_iob_orig.svg
new file mode 100644
index 0000000000..98c1764554
--- /dev/null
+++ b/icons/complications-source/ic_cob_iob_orig.svg
@@ -0,0 +1,83 @@
+
+
+
+
diff --git a/icons/complications-source/ic_ins_burnin_orig.svg b/icons/complications-source/ic_ins_burnin_orig.svg
new file mode 100644
index 0000000000..c5bcdfe0ff
--- /dev/null
+++ b/icons/complications-source/ic_ins_burnin_orig.svg
@@ -0,0 +1,57 @@
+
+
diff --git a/icons/complications-source/ic_ins_orig.svg b/icons/complications-source/ic_ins_orig.svg
new file mode 100644
index 0000000000..7601867f58
--- /dev/null
+++ b/icons/complications-source/ic_ins_orig.svg
@@ -0,0 +1,56 @@
+
+
diff --git a/icons/complications-source/ic_iob_detailed_orig.svg b/icons/complications-source/ic_iob_detailed_orig.svg
new file mode 100644
index 0000000000..3479a78565
--- /dev/null
+++ b/icons/complications-source/ic_iob_detailed_orig.svg
@@ -0,0 +1,88 @@
+
+
+
+
diff --git a/icons/complications/ic_aaps_full.svg b/icons/complications/ic_aaps_full.svg
new file mode 100644
index 0000000000..4e005a8228
--- /dev/null
+++ b/icons/complications/ic_aaps_full.svg
@@ -0,0 +1,36 @@
+
+
diff --git a/icons/complications/ic_basal.svg b/icons/complications/ic_basal.svg
new file mode 100644
index 0000000000..0491265177
--- /dev/null
+++ b/icons/complications/ic_basal.svg
@@ -0,0 +1,35 @@
+
+
diff --git a/icons/complications/ic_br_cob_iob.svg b/icons/complications/ic_br_cob_iob.svg
new file mode 100644
index 0000000000..b340c42187
--- /dev/null
+++ b/icons/complications/ic_br_cob_iob.svg
@@ -0,0 +1,40 @@
+
+
diff --git a/icons/complications/ic_carbs.svg b/icons/complications/ic_carbs.svg
new file mode 100644
index 0000000000..0785741d47
--- /dev/null
+++ b/icons/complications/ic_carbs.svg
@@ -0,0 +1,35 @@
+
+
diff --git a/icons/complications/ic_cob_detailed.svg b/icons/complications/ic_cob_detailed.svg
new file mode 100644
index 0000000000..5132260c3c
--- /dev/null
+++ b/icons/complications/ic_cob_detailed.svg
@@ -0,0 +1,36 @@
+
+
diff --git a/icons/complications/ic_cob_iob.svg b/icons/complications/ic_cob_iob.svg
new file mode 100644
index 0000000000..81a2e9250f
--- /dev/null
+++ b/icons/complications/ic_cob_iob.svg
@@ -0,0 +1,36 @@
+
+
diff --git a/icons/complications/ic_ins.svg b/icons/complications/ic_ins.svg
new file mode 100644
index 0000000000..e5d1b3e147
--- /dev/null
+++ b/icons/complications/ic_ins.svg
@@ -0,0 +1,31 @@
+
+
diff --git a/icons/complications/ic_ins_burnin.svg b/icons/complications/ic_ins_burnin.svg
new file mode 100644
index 0000000000..623db41e5b
--- /dev/null
+++ b/icons/complications/ic_ins_burnin.svg
@@ -0,0 +1,31 @@
+
+
diff --git a/icons/complications/ic_iob_detailed.svg b/icons/complications/ic_iob_detailed.svg
new file mode 100644
index 0000000000..8bd9aabc0e
--- /dev/null
+++ b/icons/complications/ic_iob_detailed.svg
@@ -0,0 +1,36 @@
+
+
diff --git a/icons/complications/ic_sgv.svg b/icons/complications/ic_sgv.svg
new file mode 100644
index 0000000000..1dc46d403b
--- /dev/null
+++ b/icons/complications/ic_sgv.svg
@@ -0,0 +1,35 @@
+
+
diff --git a/wear/build.gradle b/wear/build.gradle
index 7e6500fe56..3a2277e2fe 100644
--- a/wear/build.gradle
+++ b/wear/build.gradle
@@ -1,8 +1,23 @@
+buildscript {
+ repositories {
+ jcenter()
+ }
+
+ dependencies {
+ classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4'
+ }
+}
apply plugin: 'com.android.application'
+apply plugin: 'jacoco-android'
+
+jacoco {
+ toolVersion = "0.8.3"
+}
ext {
wearableVersion = "2.4.0"
playServicesWearable = "17.0.0"
+ powermockVersion = "1.7.3"
}
def generateGitBuild = { ->
@@ -92,6 +107,10 @@ dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//implementation files("libs/hellocharts-library-1.5.5.jar")
//compile "com.ustwo.android:clockwise-wearable:1.0.2"
+
+ implementation 'androidx.appcompat:appcompat:1.1.0'
+ implementation 'androidx.legacy:legacy-support-v13:1.0.0'
+
compileOnly "com.google.android.wearable:wearable:${wearableVersion}"
implementation "com.google.android.support:wearable:${wearableVersion}"
implementation "com.google.android.gms:play-services-wearable:${playServicesWearable}"
@@ -101,4 +120,27 @@ dependencies {
implementation 'androidx.wear:wear:1.0.0'
implementation('me.denley.wearpreferenceactivity:wearpreferenceactivity:0.5.0')
implementation('com.github.lecho:hellocharts-library:1.5.8@aar')
+
+ testImplementation "junit:junit:4.12"
+ testImplementation "org.json:json:20140107"
+ testImplementation ("org.mockito:mockito-core:2.8.47") {
+ exclude group: 'net.bytebuddy', module: 'byte-buddy'
+ exclude group: 'net.bytebuddy', module: 'byte-buddy-android'
+ exclude group: 'net.bytebuddy', module: 'byte-buddy-agent'
+ }
+ // to fix org.mockito:mockito-core dependency issues, fixed in mockito 3+
+ testImplementation 'net.bytebuddy:byte-buddy:1.8.22'
+ testImplementation 'net.bytebuddy:byte-buddy-android:1.8.22'
+ testImplementation 'net.bytebuddy:byte-buddy-agent:1.8.22'
+
+ testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}"
+ testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}"
+ testImplementation "org.powermock:powermock-module-junit4-rule:${powermockVersion}"
+ testImplementation "org.powermock:powermock-module-junit4:${powermockVersion}"
+ testImplementation "joda-time:joda-time:2.9.9"
+ testImplementation("com.google.truth:truth:0.39") {
+ exclude group: "com.google.guava", module: "guava"
+ }
+ testImplementation "org.skyscreamer:jsonassert:1.5.0"
+ testImplementation "org.hamcrest:hamcrest-all:1.3"
}
diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml
index 874a9c8763..1097be80be 100644
--- a/wear/src/main/AndroidManifest.xml
+++ b/wear/src/main/AndroidManifest.xml
@@ -10,6 +10,7 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/wear/src/main/assets/watch_dark.jpg b/wear/src/main/assets/watch_dark.jpg
new file mode 100644
index 0000000000..54cd4dc1dc
Binary files /dev/null and b/wear/src/main/assets/watch_dark.jpg differ
diff --git a/wear/src/main/assets/watch_gray.jpg b/wear/src/main/assets/watch_gray.jpg
new file mode 100644
index 0000000000..2cb3778b6b
Binary files /dev/null and b/wear/src/main/assets/watch_gray.jpg differ
diff --git a/wear/src/main/assets/watch_light.jpg b/wear/src/main/assets/watch_light.jpg
new file mode 100644
index 0000000000..a8183304d6
Binary files /dev/null and b/wear/src/main/assets/watch_light.jpg differ
diff --git a/wear/src/main/java/info/nightscout/androidaps/aaps.java b/wear/src/main/java/info/nightscout/androidaps/aaps.java
new file mode 100644
index 0000000000..f05f032f2e
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/aaps.java
@@ -0,0 +1,75 @@
+package info.nightscout.androidaps;
+
+import android.annotation.SuppressLint;
+import android.app.Application;
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Build;
+import android.preference.PreferenceManager;
+
+import androidx.annotation.StringRes;
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+
+/**
+ * Created for xDrip+ by Emma Black on 3/21/15.
+ * Adapted for AAPS by dlvoy 2019-11-06.
+ */
+
+public class aaps extends Application implements SharedPreferences.OnSharedPreferenceChangeListener {
+
+ @SuppressLint("StaticFieldLeak")
+ private static Context context;
+ private static Boolean unicodeComplications = true;
+ private static String complicationTapAction = "default";
+
+ @Override
+ public void onCreate() {
+ aaps.context = getApplicationContext();
+ SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ sharedPrefs.registerOnSharedPreferenceChangeListener(this);
+ updatePrefs(sharedPrefs);
+ super.onCreate();
+ }
+
+ private void updatePrefs(SharedPreferences sharedPrefs) {
+ unicodeComplications = sharedPrefs.getBoolean("complication_unicode", true);
+ complicationTapAction = sharedPrefs.getString("complication_tap_action", "default");
+ }
+
+ public static Context getAppContext() {
+ return aaps.context;
+ }
+
+ private static boolean isWear2OrAbove() {
+ return Build.VERSION.SDK_INT > 23;
+ }
+
+ public static String gs(@StringRes final int id) {
+ return getAppContext().getString(id);
+ }
+
+ public static String gs(@StringRes final int id, String... args) {
+ return getAppContext().getString(id, (Object[]) args);
+ }
+
+ public static Boolean areComplicationsUnicode() {
+ return unicodeComplications;
+ }
+
+ public static String getComplicationTapAction() {
+ return complicationTapAction;
+ }
+
+ @Override
+ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
+ SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
+ updatePrefs(sharedPrefs);
+
+ // we trigger update on Complications
+ Intent messageIntent = new Intent();
+ messageIntent.setAction(Intent.ACTION_SEND);
+ LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java
new file mode 100644
index 0000000000..49f8f82837
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java
@@ -0,0 +1,411 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.graphics.drawable.Icon;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationManager;
+import android.support.wearable.complications.ComplicationProviderService;
+import android.support.wearable.complications.ComplicationText;
+import android.support.wearable.complications.ProviderUpdateRequester;
+import android.util.Log;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import androidx.localbroadcastmanager.content.LocalBroadcastManager;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.data.ListenerService;
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+import info.nightscout.androidaps.interaction.utils.Inevitable;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+
+/**
+ * Base class for all complications
+ *
+ * Created by dlvoy on 2019-11-12
+ */
+public abstract class BaseComplicationProviderService extends ComplicationProviderService {
+
+ private static final String TAG = BaseComplicationProviderService.class.getSimpleName();
+
+ private static final String KEY_COMPLICATIONS = "complications";
+ private static final String KEY_LAST_SHOWN_SINCE_VALUE = "lastSince";
+ private static final String KEY_STALE_REPORTED = "staleReported";
+ private static final String TASK_ID_REFRESH_COMPLICATION = "refresh-complication";
+
+
+ private LocalBroadcastManager localBroadcastManager;
+ private MessageReceiver messageReceiver;
+
+ public static void turnOff() {
+ Log.d(TAG, "TURNING OFF all active complications");
+ final Persistence persistence = new Persistence();
+ persistence.putString(KEY_COMPLICATIONS, "");
+ }
+
+ //==============================================================================================
+ // ABSTRACT COMPLICATION INTERFACE
+ //==============================================================================================
+
+ public abstract ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent);
+ public abstract String getProviderCanonicalName();
+
+ public ComplicationAction getComplicationAction() { return ComplicationAction.MENU; };
+
+ //----------------------------------------------------------------------------------------------
+ // DEFAULT BEHAVIOURS
+ //----------------------------------------------------------------------------------------------
+
+ public ComplicationData buildNoSyncComplicationData(int dataType,
+ RawDisplayData raw,
+ PendingIntent complicationPendingIntent,
+ PendingIntent exceptionalPendingIntent,
+ long since) {
+
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(dataType);
+ if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
+ builder.setIcon(Icon.createWithResource(this, R.drawable.ic_sync_alert));
+ }
+
+ if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
+ builder.setMinValue(0);
+ builder.setMaxValue(100);
+ builder.setValue(0);
+ }
+
+ switch (dataType) {
+ case ComplicationData.TYPE_ICON:
+ case ComplicationData.TYPE_SHORT_TEXT:
+ case ComplicationData.TYPE_RANGED_VALUE:
+ if (since > 0) {
+ builder.setShortText(ComplicationText.plainText(DisplayFormat.shortTimeSince(since) + " old"));
+ } else {
+ builder.setShortText(ComplicationText.plainText("!err!"));
+ }
+ break;
+ case ComplicationData.TYPE_LONG_TEXT:
+ builder.setLongTitle(ComplicationText.plainText(aaps.gs(R.string.label_warning_sync)));
+ if (since > 0) {
+ builder.setLongText(ComplicationText.plainText(String.format(aaps.gs(R.string.label_warning_since), DisplayFormat.shortTimeSince(since))));
+ } else {
+ builder.setLongText(ComplicationText.plainText(aaps.gs(R.string.label_warning_sync_aaps)));
+ }
+ break;
+ case ComplicationData.TYPE_LARGE_IMAGE:
+ return buildComplicationData(dataType, raw, complicationPendingIntent);
+ default:
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ break;
+ }
+
+ builder.setTapAction(exceptionalPendingIntent);
+ return builder.build();
+ }
+
+ public ComplicationData buildOutdatedComplicationData(int dataType,
+ RawDisplayData raw,
+ PendingIntent complicationPendingIntent,
+ PendingIntent exceptionalPendingIntent,
+ long since) {
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(dataType);
+ if (dataType != ComplicationData.TYPE_LARGE_IMAGE) {
+ builder.setIcon(Icon.createWithResource(this, R.drawable.ic_alert));
+ builder.setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_alert_burnin));
+ }
+
+ if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
+ builder.setMinValue(0);
+ builder.setMaxValue(100);
+ builder.setValue(0);
+ }
+
+ switch (dataType) {
+ case ComplicationData.TYPE_ICON:
+ case ComplicationData.TYPE_SHORT_TEXT:
+ case ComplicationData.TYPE_RANGED_VALUE:
+ if (since > 0) {
+ builder.setShortText(ComplicationText.plainText(DisplayFormat.shortTimeSince(since) + " old"));
+ } else {
+ builder.setShortText(ComplicationText.plainText("!old!"));
+ }
+ break;
+ case ComplicationData.TYPE_LONG_TEXT:
+ builder.setLongTitle(ComplicationText.plainText(aaps.gs(R.string.label_warning_old)));
+ if (since > 0) {
+ builder.setLongText(ComplicationText.plainText(String.format(aaps.gs(R.string.label_warning_since), DisplayFormat.shortTimeSince(since))));
+ } else {
+ builder.setLongText(ComplicationText.plainText(aaps.gs(R.string.label_warning_sync_aaps)));
+ }
+ break;
+ case ComplicationData.TYPE_LARGE_IMAGE:
+ return buildComplicationData(dataType, raw, complicationPendingIntent);
+ default:
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ break;
+ }
+
+ builder.setTapAction(exceptionalPendingIntent);
+ return builder.build();
+ }
+
+ /**
+ * If Complication depend on "since" field and need to be updated every minute or not
+ * and need only update when new DisplayRawData arrive
+ */
+ protected boolean usesSinceField() {
+ return false;
+ }
+
+ //==============================================================================================
+ // COMPLICATION LIFECYCLE
+ //==============================================================================================
+
+ /*
+ * Called when a complication has been activated. The method is for any one-time
+ * (per complication) set-up.
+ *
+ * You can continue sending data for the active complicationId until onComplicationDeactivated()
+ * is called.
+ */
+ @Override
+ public void onComplicationActivated(
+ int complicationId, int dataType, ComplicationManager complicationManager) {
+ Log.d(TAG, "onComplicationActivated(): " + complicationId + " of kind: "+getProviderCanonicalName());
+
+ Persistence persistence = new Persistence();
+ persistence.putString("complication_"+complicationId, getProviderCanonicalName());
+ persistence.putBoolean("complication_"+complicationId+"_since", usesSinceField());
+ persistence.addToSet(KEY_COMPLICATIONS, "complication_"+complicationId);
+
+ IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND);
+
+ messageReceiver = new BaseComplicationProviderService.MessageReceiver();
+ localBroadcastManager = LocalBroadcastManager.getInstance(this);
+ localBroadcastManager.registerReceiver(messageReceiver, messageFilter);
+
+ ListenerService.requestData(this);
+ checkIfUpdateNeeded();
+ }
+
+ /*
+ * Called when the complication needs updated data from your provider. There are four scenarios
+ * when this will happen:
+ *
+ * 1. An active watch face complication is changed to use this provider
+ * 2. A complication using this provider becomes active
+ * 3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS)
+ * 4. You triggered an update from your own class via the
+ * ProviderUpdateRequester.requestUpdate() method.
+ */
+ @Override
+ public void onComplicationUpdate(
+ int complicationId, int dataType, ComplicationManager complicationManager) {
+ Log.d(TAG, "onComplicationUpdate() id: " + complicationId + " of class: "+getProviderCanonicalName());
+
+ // Create Tap Action so that the user can checkIfUpdateNeeded an update by tapping the complication.
+ final ComponentName thisProvider = new ComponentName(this, getProviderCanonicalName());
+
+ // We pass the complication id, so we can only update the specific complication tapped.
+ final PendingIntent complicationPendingIntent =
+ ComplicationTapBroadcastReceiver.getTapActionIntent(
+ aaps.getAppContext(), thisProvider, complicationId, getComplicationAction());
+
+ final Persistence persistence = new Persistence();
+
+ final RawDisplayData raw = new RawDisplayData();
+ raw.updateForComplicationsFromPersistence(persistence);
+ Log.d(TAG, "Complication data: " + raw.toDebugString());
+
+ // store what is currently rendered in 'SGV since' field, to detect if it was changed and need update
+ persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, DisplayFormat.shortTimeSince(raw.datetime));
+
+ // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round
+ persistence.putBoolean(KEY_STALE_REPORTED, false);
+
+ ComplicationData complicationData;
+
+ if (WearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) {
+ // no new data arrived - probably configuration or connection error
+ final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent(
+ aaps.getAppContext(), thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated());
+ complicationData = buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated());
+ } else if (WearUtil.msSince(raw.datetime) > Constants.STALE_MS) {
+ // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error)
+ final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent(
+ aaps.getAppContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.datetime);
+ complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.datetime);
+ } else {
+ // data is up-to-date, we can render standard complication
+ complicationData = buildComplicationData(dataType, raw, complicationPendingIntent);
+ }
+
+ if (complicationData != null) {
+ complicationManager.updateComplicationData(complicationId, complicationData);
+ } else {
+ // If no data is sent, we still need to inform the ComplicationManager, so the update
+ // job can finish and the wake lock isn't held any longer than necessary.
+ complicationManager.noUpdateRequired(complicationId);
+ }
+ }
+
+ /*
+ * Called when the complication has been deactivated.
+ */
+ @Override
+ public void onComplicationDeactivated(int complicationId) {
+ Log.d(TAG, "onComplicationDeactivated(): " + complicationId);
+
+ Persistence persistence = new Persistence();
+ persistence.removeFromSet(KEY_COMPLICATIONS, "complication_"+complicationId);
+
+ if (localBroadcastManager != null && messageReceiver != null) {
+ localBroadcastManager.unregisterReceiver(messageReceiver);
+ }
+ Inevitable.kill(TASK_ID_REFRESH_COMPLICATION);
+ }
+
+ //==============================================================================================
+ // UPDATE AND REFRESH LOGIC
+ //==============================================================================================
+
+ /*
+ * Schedule check for field update
+ */
+ public static void checkIfUpdateNeeded() {
+
+ Persistence p = new Persistence();
+
+ Log.d(TAG, "Pending check if update needed - "+p.getString(KEY_COMPLICATIONS, ""));
+
+ Inevitable.task(TASK_ID_REFRESH_COMPLICATION, 15 * Constants.SECOND_IN_MS, () -> {
+ if (WearUtil.isBelowRateLimit("complication-checkIfUpdateNeeded", 5)) {
+ Log.d(TAG, "Checking if update needed");
+ requestUpdateIfSinceChanged();
+ // We reschedule need for check - to make sure next check will Inevitable go in next 15s
+ checkIfUpdateNeeded();
+ }
+ });
+
+ }
+
+ /*
+ * Check if displayed since field (field that shows how old, in minutes, is reading)
+ * is up-to-date or need to be changed (a minute or more elapsed)
+ */
+ private static void requestUpdateIfSinceChanged() {
+ final Persistence persistence = new Persistence();
+
+ final RawDisplayData raw = new RawDisplayData();
+ raw.updateForComplicationsFromPersistence(persistence);
+
+ final String lastSince = persistence.getString(KEY_LAST_SHOWN_SINCE_VALUE, "-");
+ final String calcSince = DisplayFormat.shortTimeSince(raw.datetime);
+ final boolean isStale = (WearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS)
+ ||(WearUtil.msSince(raw.datetime) > Constants.STALE_MS);
+
+ final boolean staleWasRefreshed = persistence.getBoolean(KEY_STALE_REPORTED, false);
+ final boolean sinceWasChanged = !lastSince.equals(calcSince);
+
+ if (sinceWasChanged|| (isStale && !staleWasRefreshed)) {
+ persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, calcSince);
+ persistence.putBoolean(KEY_STALE_REPORTED, isStale);
+
+ Log.d(TAG, "Detected refresh of time needed! Reason: "
+ + (isStale ? "- stale detected": "")
+ + (sinceWasChanged ? "- since changed from: "+lastSince+" to: "+calcSince : ""));
+
+ if (isStale) {
+ // all complications should update to show offline/old warning
+ requestUpdate(getActiveProviderClasses());
+ } else {
+ // ... but only some require update due to 'since' field change
+ requestUpdate(getSinceDependingProviderClasses());
+ }
+ }
+ }
+
+ /*
+ * Request update for specified list of providers
+ */
+ private static void requestUpdate(Set providers) {
+ for (String provider: providers) {
+ Log.d(TAG, "Pending update of "+provider);
+ // We wait with updating allowing all request, from various sources, to arrive
+ Inevitable.task("update-req-"+provider, 700, () -> {
+ if (WearUtil.isBelowRateLimit("update-req-"+provider, 2)) {
+ Log.d(TAG, "Requesting update of "+provider);
+ final ComponentName componentName = new ComponentName(aaps.getAppContext(), provider);
+ final ProviderUpdateRequester providerUpdateRequester = new ProviderUpdateRequester(aaps.getAppContext(), componentName);
+ providerUpdateRequester.requestUpdateAll();
+ }
+ });
+ }
+ }
+
+ /*
+ * List all Complication providing classes that have active (registered) providers
+ */
+ private static Set getActiveProviderClasses() {
+ Persistence persistence = new Persistence();
+ Set providers = new HashSet<>();
+ Set complications = persistence.getSetOf(KEY_COMPLICATIONS);
+ for (String complication: complications) {
+ final String providerClass = persistence.getString(complication, "");
+ if (providerClass.length() > 0) {
+ providers.add(providerClass);
+ }
+ }
+ return providers;
+ }
+
+ /*
+ * List all Complication providing classes that have active (registered) providers
+ * and additionally they depend on "since" field
+ * == they need to be updated not only on data broadcasts, but every minute or so
+ */
+ private static Set getSinceDependingProviderClasses() {
+ Persistence persistence = new Persistence();
+ Set providers = new HashSet<>();
+ Set complications = persistence.getSetOf(KEY_COMPLICATIONS);
+ for (String complication: complications) {
+ final String providerClass = persistence.getString(complication, "");
+ final boolean dependOnSince = persistence.getBoolean(complication+"_since", false);
+ if ((providerClass.length() > 0)&&(dependOnSince)) {
+ providers.add(providerClass);
+ }
+ }
+ return providers;
+ }
+
+ /*
+ * Listen to broadcast --> new data was stored by ListenerService to Persistence
+ */
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Set complications = Persistence.setOf(KEY_COMPLICATIONS);
+ if (complications.size() > 0) {
+ checkIfUpdateNeeded();
+ // We request all active providers
+ requestUpdate(getActiveProviderClasses());
+ }
+ }
+ }
+
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java
new file mode 100644
index 0000000000..ec862f4f47
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java
@@ -0,0 +1,49 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
+
+import static info.nightscout.androidaps.interaction.utils.DisplayFormat.MAX_FIELD_LEN_SHORT;
+import static info.nightscout.androidaps.interaction.utils.DisplayFormat.MIN_FIELD_LEN_COB;
+import static info.nightscout.androidaps.interaction.utils.DisplayFormat.MIN_FIELD_LEN_IOB;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class BrCobIobComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = BrCobIobComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ final String cob = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE).minimise(MIN_FIELD_LEN_COB);
+ final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_IOB, (MAX_FIELD_LEN_SHORT -1) - cob.length()));
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(DisplayFormat.basalRateSymbol()+raw.sBasalRate))
+ .setShortTitle(ComplicationText.plainText(cob + " " + iob))
+ .setTapAction(complicationPendingIntent);
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return BrCobIobComplication.class.getCanonicalName();
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java
new file mode 100644
index 0000000000..350ec9b0ec
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java
@@ -0,0 +1,52 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+import info.nightscout.androidaps.interaction.utils.Pair;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class CobDetailedComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = CobDetailedComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+
+ Pair cob = DisplayFormat.detailedCob(raw);
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(cob.first))
+ .setTapAction(complicationPendingIntent);
+
+ if (cob.second.length() > 0) {
+ builder.setShortTitle(ComplicationText.plainText(cob.second));
+ }
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return CobDetailedComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.WIZARD;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java
new file mode 100644
index 0000000000..e42f46e3a4
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java
@@ -0,0 +1,51 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.graphics.drawable.Icon;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.RawDisplayData;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class CobIconComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = CobIconComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(raw.sCOB2))
+ .setIcon(
+ Icon.createWithResource(
+ this, R.drawable.ic_carbs))
+ .setBurnInProtectionIcon(
+ Icon.createWithResource(
+ this, R.drawable.ic_carbs))
+ .setTapAction(complicationPendingIntent);
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return CobIconComplication.class.getCanonicalName();
+ }
+
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.WIZARD;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java
new file mode 100644
index 0000000000..31ea4dc5f4
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java
@@ -0,0 +1,46 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
+
+import static info.nightscout.androidaps.interaction.utils.DisplayFormat.MAX_FIELD_LEN_SHORT;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class CobIobComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = CobIobComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ final String cob = raw.sCOB2;
+ final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(MAX_FIELD_LEN_SHORT);
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(cob))
+ .setShortTitle(ComplicationText.plainText(iob))
+ .setTapAction(complicationPendingIntent);
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return CobIobComplication.class.getCanonicalName();
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java
new file mode 100644
index 0000000000..9ca1e9c456
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java
@@ -0,0 +1,12 @@
+package info.nightscout.androidaps.complications;
+
+public enum ComplicationAction {
+ NONE,
+ MENU,
+ WIZARD,
+ BOLUS,
+ ECARB,
+ STATUS,
+ WARNING_SYNC,
+ WARNING_OLD
+}
\ No newline at end of file
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java
new file mode 100644
index 0000000000..61dc8d4dde
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java
@@ -0,0 +1,167 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.content.BroadcastReceiver;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.wearable.complications.ProviderUpdateRequester;
+import android.util.Log;
+import android.widget.Toast;
+
+import androidx.annotation.StringRes;
+
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.interaction.actions.BolusActivity;
+import info.nightscout.androidaps.interaction.actions.ECarbActivity;
+import info.nightscout.androidaps.interaction.actions.WizardActivity;
+import info.nightscout.androidaps.interaction.menus.MainMenuActivity;
+import info.nightscout.androidaps.interaction.menus.StatusMenuActivity;
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class ComplicationTapBroadcastReceiver extends BroadcastReceiver {
+
+ private static final String TAG = ComplicationTapBroadcastReceiver.class.getSimpleName();
+
+ private static final String EXTRA_PROVIDER_COMPONENT =
+ "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT";
+ private static final String EXTRA_COMPLICATION_ID =
+ "info.nightscout.androidaps.complications.action.COMPLICATION_ID";
+ private static final String EXTRA_COMPLICATION_ACTION =
+ "info.nightscout.androidaps.complications.action.COMPLICATION_ACTION";
+ private static final String EXTRA_COMPLICATION_SINCE =
+ "info.nightscout.androidaps.complications.action.COMPLICATION_SINCE";
+
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ Bundle extras = intent.getExtras();
+ ComponentName provider = extras.getParcelable(EXTRA_PROVIDER_COMPONENT);
+ int complicationId = extras.getInt(EXTRA_COMPLICATION_ID);
+ String complicationAction = extras.getString(EXTRA_COMPLICATION_ACTION, ComplicationAction.MENU.toString());
+
+ ComplicationAction action = ComplicationAction.MENU;
+ try {
+ action = ComplicationAction.valueOf(ComplicationAction.class, complicationAction);
+ } catch (IllegalArgumentException | NullPointerException ex) {
+ // but how?
+ Log.e(TAG, "Cannot interpret complication action: "+complicationAction);
+ }
+
+ action = remapActionWithUserPreferences(action);
+
+ // Request an update for the complication that has just been tapped.
+ ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider);
+ requester.requestUpdate(complicationId);
+
+ Intent intentOpen = null;
+
+ switch (action) {
+ case NONE:
+ // do nothing
+ return;
+ case WIZARD:
+ intentOpen = new Intent(aaps.getAppContext(), WizardActivity.class);
+ break;
+ case BOLUS:
+ intentOpen = new Intent(aaps.getAppContext(), BolusActivity.class);
+ break;
+ case ECARB:
+ intentOpen = new Intent(aaps.getAppContext(), ECarbActivity.class);
+ break;
+ case STATUS:
+ intentOpen = new Intent(aaps.getAppContext(), StatusMenuActivity.class);
+ break;
+ case WARNING_OLD:
+ case WARNING_SYNC:
+ long oneAndHalfMinuteAgo = WearUtil.timestamp() - (Constants.MINUTE_IN_MS+Constants.SECOND_IN_MS * 30);
+ long since = extras.getLong(EXTRA_COMPLICATION_SINCE, oneAndHalfMinuteAgo);
+ @StringRes int labelId = (action == ComplicationAction.WARNING_SYNC) ?
+ R.string.msg_warning_sync : R.string.msg_warning_old;
+ String msg = String.format(aaps.gs(labelId), DisplayFormat.shortTimeSince(since));
+ Toast.makeText(aaps.getAppContext(), msg, Toast.LENGTH_LONG).show();
+ break;
+ case MENU:
+ default:
+ intentOpen = new Intent(aaps.getAppContext(), MainMenuActivity.class);
+ }
+
+ if (intentOpen != null) {
+ // Perform intent - open dialog
+ intentOpen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ aaps.getAppContext().startActivity(intentOpen);
+ }
+ }
+
+ private ComplicationAction remapActionWithUserPreferences(ComplicationAction originalAction) {
+ final String userPrefAction = aaps.getComplicationTapAction();
+ switch (originalAction) {
+ case WARNING_OLD:
+ case WARNING_SYNC:
+ // warnings cannot be reconfigured by user
+ return originalAction;
+ default:
+ switch (userPrefAction) {
+ case "menu":
+ return ComplicationAction.MENU;
+ case "wizard":
+ return ComplicationAction.WIZARD;
+ case "bolus":
+ return ComplicationAction.BOLUS;
+ case "ecarb":
+ return ComplicationAction.ECARB;
+ case "status":
+ return ComplicationAction.STATUS;
+ case "none":
+ return ComplicationAction.NONE;
+ case "default":
+ default:
+ return originalAction;
+ }
+ }
+ }
+
+ /**
+ * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
+ * toggled and updated.
+ */
+ static PendingIntent getTapActionIntent(
+ Context context, ComponentName provider, int complicationId, ComplicationAction action) {
+ Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
+ intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
+ intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);
+ intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString());
+
+
+ // Pass complicationId as the requestCode to ensure that different complications get
+ // different intents.
+ return PendingIntent.getBroadcast(
+ context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+
+ /**
+ * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be
+ * toggled and updated.
+ */
+ static PendingIntent getTapWarningSinceIntent(
+ Context context, ComponentName provider, int complicationId, ComplicationAction action, long since) {
+ Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class);
+ intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider);
+ intent.putExtra(EXTRA_COMPLICATION_ID, complicationId);
+ intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString());
+ intent.putExtra(EXTRA_COMPLICATION_SINCE, since);
+
+
+ // Pass complicationId as the requestCode to ensure that different complications get
+ // different intents.
+ return PendingIntent.getBroadcast(
+ context, complicationId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
+ }
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java
new file mode 100644
index 0000000000..db1d67a66c
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java
@@ -0,0 +1,52 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+import info.nightscout.androidaps.interaction.utils.Pair;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class IobDetailedComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = IobDetailedComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+
+ Pair iob = DisplayFormat.detailedIob(raw);
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(iob.first))
+ .setTapAction(complicationPendingIntent);
+
+ if (iob.second.length() > 0) {
+ builder.setShortTitle(ComplicationText.plainText(iob.second));
+ }
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return IobDetailedComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.BOLUS;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java
new file mode 100644
index 0000000000..1dca0f2e4d
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java
@@ -0,0 +1,56 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.graphics.drawable.Icon;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.SmallestDoubleString;
+
+import static info.nightscout.androidaps.interaction.utils.DisplayFormat.MAX_FIELD_LEN_SHORT;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class IobIconComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = IobIconComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(MAX_FIELD_LEN_SHORT);
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(iob))
+ .setIcon(Icon.createWithResource(
+ this, R.drawable.ic_ins))
+ .setBurnInProtectionIcon(
+ Icon.createWithResource(
+ this, R.drawable.ic_ins_burnin))
+ .setTapAction(complicationPendingIntent);
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return IobIconComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.BOLUS;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java
new file mode 100644
index 0000000000..f18ad21662
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java
@@ -0,0 +1,52 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class LongStatusComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = LongStatusComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ switch (dataType) {
+ case ComplicationData.TYPE_LONG_TEXT:
+
+ final String glucoseLine = DisplayFormat.longGlucoseLine(raw);
+ final String detailsLine = DisplayFormat.longDetailsLine(raw);
+
+ final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
+ .setLongTitle(ComplicationText.plainText(glucoseLine))
+ .setLongText(ComplicationText.plainText(detailsLine))
+ .setTapAction(complicationPendingIntent);
+ complicationData = builderLong.build();
+
+ break;
+ default:
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return LongStatusComplication.class.getCanonicalName();
+ }
+
+ @Override
+ protected boolean usesSinceField() {
+ return true;
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java
new file mode 100644
index 0000000000..7c0b730c76
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java
@@ -0,0 +1,52 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class LongStatusFlippedComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = LongStatusFlippedComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ switch (dataType) {
+ case ComplicationData.TYPE_LONG_TEXT:
+
+ final String glucoseLine = DisplayFormat.longGlucoseLine(raw);
+ final String detailsLine = DisplayFormat.longDetailsLine(raw);
+
+ final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT)
+ .setLongTitle(ComplicationText.plainText(detailsLine))
+ .setLongText(ComplicationText.plainText(glucoseLine))
+ .setTapAction(complicationPendingIntent);
+ complicationData = builderLong.build();
+
+ break;
+ default:
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return LongStatusFlippedComplication.class.getCanonicalName();
+ }
+
+ @Override
+ protected boolean usesSinceField() {
+ return true;
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java
new file mode 100644
index 0000000000..0296f8bab6
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java
@@ -0,0 +1,48 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.DisplayFormat;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class SgvComplication extends BaseComplicationProviderService {
+
+ private static final String TAG = SgvComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ switch (dataType) {
+ case ComplicationData.TYPE_SHORT_TEXT:
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(raw.sSgv + raw.sDirection))
+ .setShortTitle(ComplicationText.plainText(DisplayFormat.shortTrend(raw)))
+ .setTapAction(complicationPendingIntent);
+
+ complicationData = builder.build();
+ break;
+ default:
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return SgvComplication.class.getCanonicalName();
+ }
+
+ @Override
+ protected boolean usesSinceField() {
+ return true;
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java
new file mode 100644
index 0000000000..a5fcedacdd
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java
@@ -0,0 +1,114 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.graphics.drawable.Icon;
+import android.support.wearable.complications.ComplicationData;
+import android.support.wearable.complications.ComplicationText;
+import android.util.Log;
+
+import androidx.annotation.DrawableRes;
+import info.nightscout.androidaps.R;
+import info.nightscout.androidaps.data.RawDisplayData;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class UploaderBattery extends BaseComplicationProviderService {
+
+ private static final String TAG = UploaderBattery.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ @DrawableRes int batteryIcon = R.drawable.ic_battery_unknown;
+ @DrawableRes int burnInBatteryIcon = R.drawable.ic_battery_unknown_burnin;
+ int level = 0;
+ String levelStr = "???";
+
+ if (raw.sUploaderBattery.matches("^[0-9]+$")) {
+ try {
+ level = Integer.parseInt(raw.sUploaderBattery);
+ level = Math.max(Math.min(level, 100), 0);
+ levelStr = level + "%";
+ int iconNo = (int)Math.floor(level / 10.0);
+ if (level > 95) {
+ iconNo = 10;
+ }
+ switch (iconNo) {
+ case 10: batteryIcon = R.drawable.ic_battery_charging_wireless; break;
+ case 9: batteryIcon = R.drawable.ic_battery_charging_wireless_90; break;
+ case 8: batteryIcon = R.drawable.ic_battery_charging_wireless_80; break;
+ case 7: batteryIcon = R.drawable.ic_battery_charging_wireless_70; break;
+ case 6: batteryIcon = R.drawable.ic_battery_charging_wireless_60; break;
+ case 5: batteryIcon = R.drawable.ic_battery_charging_wireless_50; break;
+ case 4: batteryIcon = R.drawable.ic_battery_charging_wireless_40; break;
+ case 3: batteryIcon = R.drawable.ic_battery_charging_wireless_30; break;
+ case 2: batteryIcon = R.drawable.ic_battery_charging_wireless_20; break;
+ case 1: batteryIcon = R.drawable.ic_battery_charging_wireless_10; break;
+ case 0: batteryIcon = R.drawable.ic_battery_alert_variant_outline; break;
+ default: batteryIcon = R.drawable.ic_battery_charging_wireless_outline;
+ }
+
+ switch (iconNo) {
+ case 10: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_burnin; break;
+ case 9: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_90_burnin; break;
+ case 8: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_80_burnin; break;
+ case 7: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_70_burnin; break;
+ case 6: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_60_burnin; break;
+ case 5: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_50_burnin; break;
+ case 4: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_40_burnin; break;
+ case 3: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_30_burnin; break;
+ case 2: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_20_burnin; break;
+ case 1: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_10_burnin; break;
+ case 0: burnInBatteryIcon = R.drawable.ic_battery_alert_variant_outline; break;
+ default: burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_outline;
+ }
+
+
+ } catch (NumberFormatException ex){
+ Log.e(TAG, "Cannot parse battery level of: " + raw.sUploaderBattery);
+ }
+ }
+
+ if (dataType == ComplicationData.TYPE_RANGED_VALUE) {
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE)
+ .setMinValue(0)
+ .setMaxValue(100)
+ .setValue(level)
+ .setShortText(ComplicationText.plainText(levelStr))
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent);
+ complicationData = builder.build();
+ } else if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
+ .setShortText(ComplicationText.plainText(levelStr))
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent);
+ complicationData = builder.build();
+ } else if (dataType == ComplicationData.TYPE_ICON) {
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_ICON)
+ .setIcon(Icon.createWithResource(this, batteryIcon))
+ .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon))
+ .setTapAction(complicationPendingIntent);
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return UploaderBattery.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.STATUS;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java
new file mode 100644
index 0000000000..293b1331ca
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java
@@ -0,0 +1,61 @@
+package info.nightscout.androidaps.complications;
+
+import android.app.PendingIntent;
+import android.content.Context;
+import android.content.res.AssetManager;
+import android.graphics.Bitmap;
+import android.graphics.BitmapFactory;
+import android.graphics.drawable.Icon;
+import android.support.wearable.complications.ComplicationData;
+import android.util.DisplayMetrics;
+import android.util.Log;
+import android.view.WindowManager;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.data.RawDisplayData;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public abstract class WallpaperComplication extends BaseComplicationProviderService {
+
+ public abstract String getWallpaperAssetsFileName();
+
+ private static final String TAG = WallpaperComplication.class.getSimpleName();
+
+ public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) {
+
+ ComplicationData complicationData = null;
+
+ if (dataType == ComplicationData.TYPE_LARGE_IMAGE) {
+
+ DisplayMetrics metrics = new DisplayMetrics();
+ WindowManager windowManager = (WindowManager) aaps.getAppContext()
+ .getSystemService(Context.WINDOW_SERVICE);
+ windowManager.getDefaultDisplay().getMetrics(metrics);
+ int width = metrics.widthPixels;
+ int height = metrics.heightPixels;
+
+ final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE);
+
+ AssetManager assetManager = getAssets();
+ try (InputStream istr = assetManager.open(getWallpaperAssetsFileName())) {
+ Bitmap bitmap = BitmapFactory.decodeStream(istr);
+ Bitmap scaled = Bitmap.createScaledBitmap(bitmap, width, height, true);
+ builder.setLargeImage(Icon.createWithBitmap(scaled));
+ } catch (IOException e) {
+ Log.e(TAG, "Cannot read wallpaper asset: "+e.getMessage(), e);
+ }
+
+ complicationData = builder.build();
+ } else {
+ if (Log.isLoggable(TAG, Log.WARN)) {
+ Log.w(TAG, "Unexpected complication type " + dataType);
+ }
+ }
+ return complicationData;
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java
new file mode 100644
index 0000000000..8c84e1d8c3
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java
@@ -0,0 +1,22 @@
+package info.nightscout.androidaps.complications;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class WallpaperDarkComplication extends WallpaperComplication {
+
+ @Override
+ public String getWallpaperAssetsFileName() {
+ return "watch_dark.jpg";
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return WallpaperDarkComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.NONE;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java
new file mode 100644
index 0000000000..bec047f323
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java
@@ -0,0 +1,22 @@
+package info.nightscout.androidaps.complications;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class WallpaperGrayComplication extends WallpaperComplication {
+
+ @Override
+ public String getWallpaperAssetsFileName() {
+ return "watch_gray.jpg";
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return WallpaperGrayComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.NONE;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java
new file mode 100644
index 0000000000..2d2bbf6f14
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java
@@ -0,0 +1,22 @@
+package info.nightscout.androidaps.complications;
+
+/*
+ * Created by dlvoy on 2019-11-12
+ */
+public class WallpaperLightComplication extends WallpaperComplication {
+
+ @Override
+ public String getWallpaperAssetsFileName() {
+ return "watch_light.jpg";
+ }
+
+ @Override
+ public String getProviderCanonicalName() {
+ return WallpaperLightComplication.class.getCanonicalName();
+ }
+
+ @Override
+ public ComplicationAction getComplicationAction() {
+ return ComplicationAction.NONE;
+ };
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java
index 83c9ad58b3..9e018516ba 100644
--- a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java
+++ b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java
@@ -40,6 +40,7 @@ import info.nightscout.androidaps.interaction.AAPSPreferences;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interaction.actions.AcceptActivity;
import info.nightscout.androidaps.interaction.actions.CPPActivity;
+import info.nightscout.androidaps.interaction.utils.Persistence;
import info.nightscout.androidaps.interaction.utils.SafeParse;
import info.nightscout.androidaps.interaction.utils.WearUtil;
@@ -512,12 +513,14 @@ public class ListenerService extends WearableListenerService implements GoogleAp
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("status", dataMap.toBundle());
+ Persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMap);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
} else if (path.equals(BASAL_DATA_PATH)){
dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("basals", dataMap.toBundle());
+ Persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMap);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
} else if (path.equals(NEW_PREFERENCES_PATH)){
dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap();
@@ -541,6 +544,7 @@ public class ListenerService extends WearableListenerService implements GoogleAp
Intent messageIntent = new Intent();
messageIntent.setAction(Intent.ACTION_SEND);
messageIntent.putExtra("data", dataMap.toBundle());
+ Persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMap);
LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent);
}
}
diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java
new file mode 100644
index 0000000000..d4e3580561
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java
@@ -0,0 +1,272 @@
+package info.nightscout.androidaps.data;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.PowerManager;
+
+import com.google.android.gms.wearable.DataMap;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+
+/**
+ * Holds bunch of data model variables and lists that arrive from phone app and are due to be
+ * displayed on watchface and complications. Keeping them together makes code cleaner and allows
+ * passing it to complications via persistence layer.
+ *
+ * Created by dlvoy on 2019-11-12
+ */
+public class RawDisplayData {
+
+ static final String DATA_PERSISTENCE_KEY = "raw_data";
+ static final String BASALS_PERSISTENCE_KEY = "raw_basals";
+ static final String STATUS_PERSISTENCE_KEY = "raw_status";
+
+ // data bundle
+ public long sgvLevel = 0;
+ public long datetime;
+ public String sSgv = "---";
+ public String sDirection = "--";
+ public String sDelta = "--";
+ public String sAvgDelta = "--";
+ public String sUnits = "-";
+
+ // status bundle
+ public String sBasalRate = "-.--U/h";
+ public String sUploaderBattery = "--";
+ public String sRigBattery = "--";
+ public boolean detailedIOB = false;
+ public String sIOB1 = "IOB";
+ public String sIOB2 = "-.--";
+ public String sCOB1 = "Carb";
+ public String sCOB2= "--g";
+ public String sBgi = "--";
+ public boolean showBGI = false;
+ public String externalStatusString = "no status";
+ public int batteryLevel = 1;
+ public long openApsStatus = -1;
+
+ // basals bundle
+ public ArrayList bgDataList = new ArrayList<>();
+ public ArrayList tempWatchDataList = new ArrayList<>();
+ public ArrayList basalWatchDataList = new ArrayList<>();
+ public ArrayList bolusWatchDataList = new ArrayList<>();
+ public ArrayList predictionList = new ArrayList<>();
+
+ public String toDebugString() {
+ return "DisplayRawData{" +
+ "sgvLevel=" + sgvLevel +
+ ", datetime=" + datetime +
+ ", sSgv='" + sSgv + '\'' +
+ ", sDirection='" + sDirection + '\'' +
+ ", sDelta='" + sDelta + '\'' +
+ ", sAvgDelta='" + sAvgDelta + '\'' +
+ ", sUnits='" + sUnits + '\'' +
+ ", sBasalRate='" + sBasalRate + '\'' +
+ ", sUploaderBattery='" + sUploaderBattery + '\'' +
+ ", sRigBattery='" + sRigBattery + '\'' +
+ ", detailedIOB=" + detailedIOB +
+ ", sIOB1='" + sIOB1 + '\'' +
+ ", sIOB2='" + sIOB2 + '\'' +
+ ", sCOB1='" + sCOB1 + '\'' +
+ ", sCOB2='" + sCOB2 + '\'' +
+ ", sBgi='" + sBgi + '\'' +
+ ", showBGI=" + showBGI +
+ ", externalStatusString='" + externalStatusString + '\'' +
+ ", batteryLevel=" + batteryLevel +
+ ", openApsStatus=" + openApsStatus +
+ ", bgDataList size=" + bgDataList.size() +
+ ", tempWatchDataList size=" + tempWatchDataList.size() +
+ ", basalWatchDataList size=" + basalWatchDataList.size() +
+ ", bolusWatchDataLis size=" + bolusWatchDataList.size() +
+ ", predictionList size=" + predictionList.size() +
+ '}';
+ }
+
+ public void updateFromPersistence(Persistence persistence) {
+
+ DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY);
+ if (dataMapData != null) {
+ updateData(dataMapData);
+ }
+ DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY);
+ if (dataMapStatus != null) {
+ updateStatus(dataMapStatus);
+ }
+ DataMap dataMapBasals = persistence.getDataMap(BASALS_PERSISTENCE_KEY);
+ if (dataMapBasals != null) {
+ updateBasals(dataMapBasals);
+ }
+ }
+
+ /*
+ * Since complications do not need Basals, we skip them for performance
+ */
+ public void updateForComplicationsFromPersistence(Persistence persistence) {
+
+ DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY);
+ if (dataMapData != null) {
+ updateData(dataMapData);
+ }
+ DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY);
+ if (dataMapStatus != null) {
+ updateStatus(dataMapStatus);
+ }
+ }
+
+ public DataMap updateDataFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
+ Bundle bundle = intent.getBundleExtra("data");
+ if (bundle != null) {
+ DataMap dataMap = WearUtil.bundleToDataMap(bundle);
+ updateData(dataMap);
+ return dataMap;
+ }
+ return null;
+ }
+
+ private void updateData(DataMap dataMap) {
+ WearUtil.getWakeLock("readingPrefs", 50);
+ sgvLevel = dataMap.getLong("sgvLevel");
+ datetime = dataMap.getLong("timestamp");
+ sSgv = dataMap.getString("sgvString");
+ sDirection = dataMap.getString("slopeArrow");
+ sDelta = dataMap.getString("delta");
+ sAvgDelta = dataMap.getString("avgDelta");
+ sUnits = dataMap.getString("glucoseUnits");
+ }
+
+ public DataMap updateStatusFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
+ Bundle bundle = intent.getBundleExtra("status");
+ if (bundle != null) {
+ DataMap dataMap = WearUtil.bundleToDataMap(bundle);
+ updateStatus(dataMap);
+ return dataMap;
+ }
+ return null;
+ }
+
+ private void updateStatus(DataMap dataMap) {
+ WearUtil.getWakeLock("readingPrefs", 50);
+ sBasalRate = dataMap.getString("currentBasal");
+ sUploaderBattery = dataMap.getString("battery");
+ sRigBattery = dataMap.getString("rigBattery");
+ detailedIOB = dataMap.getBoolean("detailedIob");
+ sIOB1 = dataMap.getString("iobSum") + "U";
+ sIOB2 = dataMap.getString("iobDetail");
+ sCOB1 = "Carb";
+ sCOB2 = dataMap.getString("cob");
+ sBgi = dataMap.getString("bgi");
+ showBGI = dataMap.getBoolean("showBgi");
+ externalStatusString = dataMap.getString("externalStatusString");
+ batteryLevel = dataMap.getInt("batteryLevel");
+ openApsStatus = dataMap.getLong("openApsStatus");
+ }
+
+ public DataMap updateBasalsFromMessage(Intent intent, PowerManager.WakeLock wakeLock) {
+ Bundle bundle = intent.getBundleExtra("basals");
+ if (bundle != null) {
+ DataMap dataMap = WearUtil.bundleToDataMap(bundle);
+ updateBasals(dataMap);
+ return dataMap;
+ }
+ return null;
+ }
+
+ private void updateBasals(DataMap dataMap) {
+ WearUtil.getWakeLock("readingPrefs", 500);
+ loadBasalsAndTemps(dataMap);
+ }
+
+ private void loadBasalsAndTemps(DataMap dataMap) {
+ ArrayList temps = dataMap.getDataMapArrayList("temps");
+ if (temps != null) {
+ tempWatchDataList = new ArrayList<>();
+ for (DataMap temp : temps) {
+ TempWatchData twd = new TempWatchData();
+ twd.startTime = temp.getLong("starttime");
+ twd.startBasal = temp.getDouble("startBasal");
+ twd.endTime = temp.getLong("endtime");
+ twd.endBasal = temp.getDouble("endbasal");
+ twd.amount = temp.getDouble("amount");
+ tempWatchDataList.add(twd);
+ }
+ }
+ ArrayList basals = dataMap.getDataMapArrayList("basals");
+ if (basals != null) {
+ basalWatchDataList = new ArrayList<>();
+ for (DataMap basal : basals) {
+ BasalWatchData bwd = new BasalWatchData();
+ bwd.startTime = basal.getLong("starttime");
+ bwd.endTime = basal.getLong("endtime");
+ bwd.amount = basal.getDouble("amount");
+ basalWatchDataList.add(bwd);
+ }
+ }
+ ArrayList boluses = dataMap.getDataMapArrayList("boluses");
+ if (boluses != null) {
+ bolusWatchDataList = new ArrayList<>();
+ for (DataMap bolus : boluses) {
+ BolusWatchData bwd = new BolusWatchData();
+ bwd.date = bolus.getLong("date");
+ bwd.bolus = bolus.getDouble("bolus");
+ bwd.carbs = bolus.getDouble("carbs");
+ bwd.isSMB = bolus.getBoolean("isSMB");
+ bwd.isValid = bolus.getBoolean("isValid");
+ bolusWatchDataList.add(bwd);
+ }
+ }
+ ArrayList predictions = dataMap.getDataMapArrayList("predictions");
+ if (boluses != null) {
+ predictionList = new ArrayList<>();
+ for (DataMap prediction : predictions) {
+ BgWatchData bwd = new BgWatchData();
+ bwd.timestamp = prediction.getLong("timestamp");
+ bwd.sgv = prediction.getDouble("sgv");
+ bwd.color = prediction.getInt("color");
+ predictionList.add(bwd);
+ }
+ }
+ }
+
+ public void addToWatchSet(DataMap dataMap) {
+ ArrayList entries = dataMap.getDataMapArrayList("entries");
+ if (entries != null) {
+ bgDataList = new ArrayList<>();
+ for (DataMap entry : entries) {
+ double sgv = entry.getDouble("sgvDouble");
+ double high = entry.getDouble("high");
+ double low = entry.getDouble("low");
+ long timestamp = entry.getLong("timestamp");
+ int color = entry.getInt("color", 0);
+ bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
+ }
+ } else {
+ double sgv = dataMap.getDouble("sgvDouble");
+ double high = dataMap.getDouble("high");
+ double low = dataMap.getDouble("low");
+ long timestamp = dataMap.getLong("timestamp");
+ int color = dataMap.getInt("color", 0);
+
+ final int size = bgDataList.size();
+ if (size > 0) {
+ if (bgDataList.get(size - 1).timestamp == timestamp)
+ return; // Ignore duplicates.
+ }
+
+ bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
+ }
+
+ // We use iterator instead for-loop because we iterate and remove on the go
+ Iterator itr = bgDataList.iterator();
+ while (itr.hasNext()) {
+ BgWatchData entry = (BgWatchData)itr.next();
+ if (entry.timestamp < (WearUtil.timestamp() - (Constants.HOUR_IN_MS * 5))) {
+ itr.remove(); //Get rid of anything more than 5 hours old
+ }
+ }
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java
new file mode 100644
index 0000000000..2af3ef34b6
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java
@@ -0,0 +1,14 @@
+package info.nightscout.androidaps.interaction.utils;
+
+public class Constants {
+
+ public static final long SECOND_IN_MS = 1000;
+ public static final long MINUTE_IN_MS = 60000;
+ public static final long HOUR_IN_MS = 3600000;
+ public static final long DAY_IN_MS = 86400000;
+ public static final long WEEK_IN_MS = DAY_IN_MS * 7;
+ public static final long MONTH_IN_MS = DAY_IN_MS * 30;
+
+ public static final long STALE_MS = Constants.MINUTE_IN_MS * 12;
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java
new file mode 100644
index 0000000000..f2cf06671e
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java
@@ -0,0 +1,143 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.data.RawDisplayData;
+
+public class DisplayFormat {
+
+ /**
+ * Maximal and minimal lengths of fields/labels shown in complications, in characters
+ * For MAX values - above that WearOS and watch faces may start ellipsize (...) contents
+ * For MIN values - this is minimal length that can hold legible data
+ */
+ public static final int MAX_FIELD_LEN_LONG = 22; // this is found out empirical, for TYPE_LONG_TEXT
+ public static final int MAX_FIELD_LEN_SHORT = 7; // according to Wear OS docs for TYPE_SHORT_TEXT
+ public static final int MIN_FIELD_LEN_COB = 3; // since carbs are usually 0..99g
+ public static final int MIN_FIELD_LEN_IOB = 3; // IoB can range from like .1U to 99U
+
+ public static String deltaSymbol() {
+ return aaps.areComplicationsUnicode() ? "\u0394" : "";
+ }
+
+ public static String verticalSeparatorSymbol() {
+ return aaps.areComplicationsUnicode() ? "\u205E" : "|";
+ }
+
+ public static String basalRateSymbol() {
+ return aaps.areComplicationsUnicode() ? "\u238D\u2006" : "";
+ }
+
+ public static String shortTimeSince(final long refTime) {
+
+ long deltaTimeMs = WearUtil.msSince(refTime);
+
+ if (deltaTimeMs < Constants.MINUTE_IN_MS) {
+ return "0'";
+ } else if (deltaTimeMs < Constants.HOUR_IN_MS) {
+ int minutes = (int) (deltaTimeMs / Constants.MINUTE_IN_MS);
+ return minutes + "'";
+ } else if (deltaTimeMs < Constants.DAY_IN_MS) {
+ int hours = (int) (deltaTimeMs / Constants.HOUR_IN_MS);
+ return hours + "h";
+ } else {
+ int days = (int) (deltaTimeMs / Constants.DAY_IN_MS);
+ if (days < 7) {
+ return days + "d";
+ } else {
+ int weeks = days / 7;
+ return weeks + "w";
+ }
+ }
+ }
+
+ public static String shortTrend(final RawDisplayData raw) {
+ String minutes = "--";
+ if (raw.datetime > 0) {
+ minutes = shortTimeSince(raw.datetime);
+ }
+
+ if (minutes.length() + raw.sDelta.length() + deltaSymbol().length() + 1 <= MAX_FIELD_LEN_SHORT) {
+ return minutes + " " + deltaSymbol() + raw.sDelta;
+ }
+
+ // that only optimizes obvious things like 0 before . or at end, + at beginning
+ String delta = (new SmallestDoubleString(raw.sDelta)).minimise(MAX_FIELD_LEN_SHORT -1);
+ if (minutes.length() + delta.length() + deltaSymbol().length() + 1 <= MAX_FIELD_LEN_SHORT) {
+ return minutes + " " + deltaSymbol() + delta;
+ }
+
+ String shortDelta = (new SmallestDoubleString(raw.sDelta)).minimise(MAX_FIELD_LEN_SHORT -(1+minutes.length()));
+
+ return minutes + " " + shortDelta;
+ }
+
+ public static String longGlucoseLine(final RawDisplayData raw) {
+ return raw.sSgv + raw.sDirection + " " + deltaSymbol() + (new SmallestDoubleString(raw.sDelta)).minimise(8) + " (" + shortTimeSince(raw.datetime) + ")";
+ }
+
+ public static String longDetailsLine(final RawDisplayData raw) {
+
+ final String SEP_LONG = " " + verticalSeparatorSymbol() + " ";
+ final String SEP_SHORT = " " + verticalSeparatorSymbol() + " ";
+ final int SEP_SHORT_LEN = SEP_SHORT.length();
+ final String SEP_MIN = " ";
+
+ String line = raw.sCOB2 + SEP_LONG + raw.sIOB1 + SEP_LONG + basalRateSymbol()+raw.sBasalRate;
+ if (line.length() <= MAX_FIELD_LEN_LONG) {
+ return line;
+ }
+ line = raw.sCOB2 + SEP_SHORT + raw.sIOB1 + SEP_SHORT + raw.sBasalRate;
+ if (line.length() <= MAX_FIELD_LEN_LONG) {
+ return line;
+ }
+
+ int remainingMax = MAX_FIELD_LEN_LONG - (raw.sCOB2.length() + raw.sBasalRate.length() + SEP_SHORT_LEN*2);
+ final String smallestIoB = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_IOB, remainingMax));
+ line = raw.sCOB2 + SEP_SHORT + smallestIoB + SEP_SHORT + raw.sBasalRate;
+ if (line.length() <= MAX_FIELD_LEN_LONG) {
+ return line;
+ }
+
+ remainingMax = MAX_FIELD_LEN_LONG - (smallestIoB.length() + raw.sBasalRate.length() + SEP_SHORT_LEN*2);
+ final String simplifiedCob = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_COB, remainingMax));
+
+ line = simplifiedCob + SEP_SHORT + smallestIoB + SEP_SHORT + raw.sBasalRate;
+ if (line.length() <= MAX_FIELD_LEN_LONG) {
+ return line;
+ }
+
+ line = simplifiedCob + SEP_MIN + smallestIoB + SEP_MIN + raw.sBasalRate;
+
+ return line;
+ }
+
+ public static Pair detailedIob(RawDisplayData raw) {
+ final String iob1 = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(MAX_FIELD_LEN_SHORT);
+ String iob2 = "";
+ if (raw.sIOB2.contains("|")) {
+ String[] iobs = raw.sIOB2.replace("(", "").replace(")", "").split("\\|");
+
+ String iobBolus = new SmallestDoubleString(iobs[0]).minimise(MIN_FIELD_LEN_IOB);
+ if (iobBolus.trim().length() == 0) {
+ iobBolus = "--";
+ }
+ String iobBasal = new SmallestDoubleString(iobs[1]).minimise((MAX_FIELD_LEN_SHORT -1) - Math.max(MIN_FIELD_LEN_IOB, iobBolus.length()));
+ if (iobBasal.trim().length() == 0) {
+ iobBasal = "--";
+ }
+ iob2 = iobBolus+" "+iobBasal;
+ }
+ return Pair.create(iob1, iob2);
+ }
+
+ public static Pair detailedCob(final RawDisplayData raw) {
+ SmallestDoubleString cobMini = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE);
+
+ String cob2 = "";
+ if (cobMini.getExtra().length() > 0) {
+ cob2 = cobMini.getExtra() + cobMini.getUnits();
+ }
+ final String cob1 = cobMini.minimise(MAX_FIELD_LEN_SHORT);
+ return Pair.create(cob1, cob2);
+ }
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java
new file mode 100644
index 0000000000..54361b6678
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java
@@ -0,0 +1,118 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import android.os.PowerManager;
+import android.util.Log;
+
+import java.util.concurrent.ConcurrentHashMap;
+
+import info.nightscout.androidaps.BuildConfig;
+
+/**
+ * Created for xDrip by jamorham on 07/03/2018
+ * Adapted for AAPS by dlvoy on 2019-11-11
+ *
+ * Tasks which are fired from events can be scheduled here and only execute when they become idle
+ * and are not being rescheduled within their wait window.
+ *
+ */
+
+public class Inevitable {
+
+ private static final String TAG = Inevitable.class.getSimpleName();
+ private static final int MAX_QUEUE_TIME = (int) Constants.MINUTE_IN_MS * 6;
+ private static final boolean debug = BuildConfig.DEBUG;
+
+ private static final ConcurrentHashMap tasks = new ConcurrentHashMap<>();
+
+ public static synchronized void task(final String id, long idle_for, Runnable runnable) {
+ if (idle_for > MAX_QUEUE_TIME) {
+ throw new RuntimeException(id + " Requested time: " + idle_for + " beyond max queue time");
+ }
+ final Task task = tasks.get(id);
+ if (task != null) {
+ // if it already exists then extend the time
+ task.extendTime(idle_for);
+
+ if (debug)
+ Log.d(TAG, "Extending time for: " + id + " to " + WearUtil.dateTimeText(task.when));
+ } else {
+ // otherwise create new task
+ if (runnable == null) return; // extension only if already exists
+ tasks.put(id, new Task(id, idle_for, runnable));
+
+ if (debug) {
+ Log.d(TAG, "Creating task: " + id + " due: " + WearUtil.dateTimeText(tasks.get(id).when));
+ }
+
+ // create a thread to wait and execute in background
+ final Thread t = new Thread(() -> {
+ final PowerManager.WakeLock wl = WearUtil.getWakeLock(id, MAX_QUEUE_TIME + 5000);
+ try {
+ boolean running = true;
+ // wait for task to be due or killed
+ while (running) {
+ WearUtil.threadSleep(500);
+ final Task thisTask = tasks.get(id);
+ running = thisTask != null && !thisTask.poll();
+ }
+ } finally {
+ WearUtil.releaseWakeLock(wl);
+ }
+ });
+ t.setPriority(Thread.MIN_PRIORITY);
+ t.start();
+ }
+ }
+
+ public static synchronized void stackableTask(String id, long idle_for, Runnable runnable) {
+ int stack = 0;
+ while (tasks.get(id = id + "-" + stack) != null) {
+ stack++;
+ }
+ if (stack > 0) {
+ Log.d(TAG, "Task stacked to: " + id);
+ }
+ task(id, idle_for, runnable);
+ }
+
+ public static void kill(final String id) {
+ tasks.remove(id);
+ }
+
+ public static boolean waiting(final String id) {
+ return tasks.containsKey(id);
+ }
+
+ private static class Task {
+ private long when;
+ private final Runnable what;
+ private final String id;
+
+ Task(String id, long offset, Runnable what) {
+ this.what = what;
+ this.id = id;
+ extendTime(offset);
+ }
+
+ public void extendTime(long offset) {
+ this.when = WearUtil.timestamp() + offset;
+ }
+
+ public boolean poll() {
+ final long till = WearUtil.msTill(when);
+ if (till < 1) {
+ if (debug) Log.d(TAG, "Executing task! " + this.id);
+ tasks.remove(this.id); // early remove to allow overlapping scheduling
+ what.run();
+ return true;
+ } else if (till > MAX_QUEUE_TIME) {
+ Log.wtf(TAG, "Task: " + this.id + " In queue too long: " + till);
+ tasks.remove(this.id);
+ return true;
+ }
+ return false;
+ }
+
+ }
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java
new file mode 100644
index 0000000000..4207cbd743
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java
@@ -0,0 +1,43 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import java.util.Objects;
+
+/**
+ * Same as android Pair, but clean room java class - does not require Android SDK for tests
+ */
+public class Pair {
+
+ public final F first;
+ public final S second;
+
+ public Pair(F first, S second) {
+ this.first = first;
+ this.second = second;
+ }
+
+ public static Pair create(F f, S s) {
+ return new Pair<>(f, s);
+ }
+
+ @Override
+ public boolean equals(java.lang.Object o) {
+ if (o instanceof Pair) {
+ return ((Pair) o).first.equals(first) && ((Pair) o).second.equals(second);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "First: \""+first.toString()+"\" Second: \""+second.toString()+"\"";
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(first, second);
+ }
+
+}
+
+
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java
new file mode 100644
index 0000000000..36c0ae76ee
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java
@@ -0,0 +1,96 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import android.content.SharedPreferences;
+import android.util.Base64;
+
+import androidx.annotation.Nullable;
+
+import com.google.android.gms.wearable.DataMap;
+
+import java.util.Set;
+
+import info.nightscout.androidaps.aaps;
+
+/**
+ * Created by dlvoy on 2019-11-12
+ */
+public class Persistence {
+
+ final SharedPreferences preferences;
+ public static final String COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY =
+ "info.nightscout.androidaps.complications.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY";
+
+ public Persistence() {
+ preferences = aaps.getAppContext().getSharedPreferences(COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY, 0);
+ }
+
+ @Nullable
+ public DataMap getDataMap(String key) {
+ if (preferences.contains(key)) {
+ final String rawB64Data = preferences.getString(key, null);
+ byte[] rawData = Base64.decode(rawB64Data, Base64.DEFAULT);
+ try {
+ return DataMap.fromByteArray(rawData);
+ } catch (IllegalArgumentException ex) {
+ // Should never happen, and if it happen - we ignore and fallback to null
+ }
+ }
+ return null;
+ }
+
+ public void putDataMap(String key, DataMap dataMap) {
+ preferences.edit().putString(key, Base64.encodeToString(dataMap.toByteArray(), Base64.DEFAULT)).apply();
+ }
+
+ public String getString(String key, String defaultValue) {
+ return preferences.getString(key, defaultValue);
+ }
+
+ public void putString(String key, String value) {
+ preferences.edit().putString(key, value).apply();
+ }
+
+ public boolean getBoolean(String key, boolean defaultValue) {
+ return preferences.getBoolean(key, defaultValue);
+ }
+
+ public void putBoolean(String key, boolean value) {
+ preferences.edit().putBoolean(key, value).apply();
+ }
+
+ public long whenDataUpdated() {
+ return preferences.getLong("data_updated_at", 0);
+ }
+
+ private void markDataUpdated() {
+ preferences.edit().putLong("data_updated_at", WearUtil.timestamp()).apply();
+ }
+
+ public Set getSetOf(String key) {
+ return WearUtil.explodeSet(getString(key, ""), "|");
+ }
+
+ public void addToSet(String key, String value) {
+ final Set set = WearUtil.explodeSet(getString(key, ""), "|");
+ set.add(value);
+ putString(key, WearUtil.joinSet(set, "|"));
+ }
+
+ public void removeFromSet(String key, String value) {
+ final Set set = WearUtil.explodeSet(getString(key, ""), "|");
+ set.remove(value);
+ putString(key, WearUtil.joinSet(set, "|"));
+ }
+
+ public static void storeDataMap(String key, DataMap dataMap) {
+ Persistence p = new Persistence();
+ p.putDataMap(key, dataMap);
+ p.markDataUpdated();
+ }
+
+ public static Set setOf(String key) {
+ Persistence p = new Persistence();
+ return p.getSetOf(key);
+ }
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/SmallestDoubleString.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/SmallestDoubleString.java
new file mode 100644
index 0000000000..8361478976
--- /dev/null
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/SmallestDoubleString.java
@@ -0,0 +1,135 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import java.math.RoundingMode;
+import java.text.DecimalFormat;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * Helper to minimise various floating point values, with or without unit, to fit into specified
+ * and limited size, scarifying precision (rounding up) and extra characters like leading zero,
+ * following zero(s) in fractional part, extra plus sign etc.
+ *
+ * Created by dlvoy on 2019-11-12
+ */
+public class SmallestDoubleString {
+
+ private String sign = "";
+ private String decimal = "";
+ private String separator = "";
+ private String fractional = "";
+ private String extra = "";
+ private String units = "";
+
+ private final Units withUnits;
+
+ public enum Units {
+ SKIP,
+ USE
+ }
+
+ private static Pattern pattern = Pattern.compile("^([+-]?)([0-9]*)([,.]?)([0-9]*)(\\([^)]*\\))?(.*?)$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE );
+
+ public SmallestDoubleString(String inputString) {
+ this(inputString, Units.SKIP);
+ }
+
+ public SmallestDoubleString(String inputString, Units withUnits) {
+ Matcher matcher = pattern.matcher(inputString);
+ matcher.matches();
+
+ sign = matcher.group(1);
+ decimal = matcher.group(2);
+ separator = matcher.group(3);
+ fractional = matcher.group(4);
+ units = matcher.group(6);
+
+ if (fractional == null || fractional.length() == 0) {
+ separator = "";
+ fractional = "";
+ }
+ if (decimal == null || decimal.length() == 0) {
+ decimal = "";
+ }
+ if (separator == null || separator.length() == 0) {
+ separator = "";
+ }
+ if (sign == null || sign.length() == 0) {
+ sign = "";
+ }
+
+ final String extraCandidate = matcher.group(5);
+ if (extraCandidate != null && extraCandidate.length() > 2) {
+ extra = extraCandidate.substring(1, extraCandidate.length()-1);
+ }
+
+ if (units != null) {
+ units = units.trim();
+ }
+
+ this.withUnits = withUnits;
+ }
+
+ public String minimise(int maxSize) {
+ final String originalSeparator = separator;
+
+ if (Integer.parseInt("0"+fractional) == 0) {
+ separator = "";
+ fractional = "";
+ }
+ if (Integer.parseInt("0"+decimal) == 0 && (fractional.length() >0)) {
+ decimal = "";
+ }
+ if (currentLen() <= maxSize)
+ return toString();
+
+ if (sign.equals("+")) {
+ sign = "";
+ }
+ if (currentLen() <= maxSize) {
+ return toString();
+ }
+
+ while ((fractional.length() > 1)&&(fractional.charAt(fractional.length()-1) == '0')) {
+ fractional = fractional.substring(0, fractional.length()-1);
+ }
+ if (currentLen() <= maxSize) {
+ return toString();
+ }
+
+ if (fractional.length() > 0) {
+ int remainingForFraction = maxSize-currentLen()+fractional.length();
+ String formatCandidate = "#";
+ if (remainingForFraction>=1) {
+ formatCandidate = "#."+("#######".substring(0, remainingForFraction));
+ }
+ DecimalFormat df = new DecimalFormat(formatCandidate);
+ df.setRoundingMode(RoundingMode.HALF_UP);
+
+ final String decimalSup = (decimal.length() > 0) ? decimal : "0";
+ String result = sign + df.format(Double.parseDouble(decimalSup+"."+fractional)).replace(",", originalSeparator).replace(".", originalSeparator) +
+ ((withUnits == Units.USE) ? units : "");
+ return (decimal.length() > 0) ? result : result.substring(1);
+ }
+ return toString();
+ }
+
+ private int currentLen() {
+ return sign.length() + decimal.length() + separator.length() + fractional.length() +
+ ((withUnits == Units.USE) ? units.length() : 0);
+ }
+
+ @Override
+ public String toString() {
+ return sign+decimal+separator+fractional +
+ ((withUnits == Units.USE) ? units : "");
+ }
+
+ public String getExtra() {
+ return extra;
+ }
+
+ public String getUnits() { return units; }
+
+
+}
diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java
index ca63749888..f8415bdd4a 100644
--- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java
+++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java
@@ -1,19 +1,134 @@
package info.nightscout.androidaps.interaction.utils;
-import java.time.LocalDateTime;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.PowerManager;
+import android.os.SystemClock;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import info.nightscout.androidaps.aaps;
/**
* Created by andy on 3/5/19.
+ * Adapted by dlvoy on 2019-11-06 using code from jamorham JoH class
*/
public class WearUtil {
+ private final static boolean debug_wakelocks = false;
+ private static final Map rateLimits = new HashMap();
+ private static final String TAG = WearUtil.class.getName();
+
+ //==============================================================================================
+ // Time related util methods
+ //==============================================================================================
public static String dateTimeText(long timeInMs) {
Date d = new Date(timeInMs);
return "" + d.getDay() + "." + d.getMonth() + "." + d.getYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
+ public static long timestamp() {
+ return System.currentTimeMillis();
+ }
+ public static long msSince(long when) {
+ return (timestamp() - when);
+ }
+
+ public static long msTill(long when) {
+ return (when - timestamp());
+ }
+
+ //==============================================================================================
+ // Thread and power management utils
+ //==============================================================================================
+
+ // return true if below rate limit
+ public static synchronized boolean isBelowRateLimit(String named, int onceForSeconds) {
+ // check if over limit
+ if ((rateLimits.containsKey(named)) && (timestamp() - rateLimits.get(named) < (onceForSeconds * 1000))) {
+ Log.d(TAG, named + " rate limited to one for " + onceForSeconds + " seconds");
+ return false;
+ }
+ // not over limit
+ rateLimits.put(named, timestamp());
+ return true;
+ }
+
+ public static PowerManager.WakeLock getWakeLock(final String name, int millis) {
+ final PowerManager pm = (PowerManager) aaps.getAppContext().getSystemService(Context.POWER_SERVICE);
+ PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AAPS::"+name);
+ wl.acquire(millis);
+ if (debug_wakelocks) Log.d(TAG, "getWakeLock: " + name + " " + wl.toString());
+ return wl;
+ }
+
+ public static void releaseWakeLock(PowerManager.WakeLock wl) {
+ if (debug_wakelocks) Log.d(TAG, "releaseWakeLock: " + wl.toString());
+ if (wl == null) return;
+ if (wl.isHeld()) wl.release();
+ }
+
+ public static void startActivity(Class c) {
+ aaps.getAppContext().startActivity(getStartActivityIntent(c));
+ }
+
+ public static Intent getStartActivityIntent(Class c) {
+ return new Intent(aaps.getAppContext(), c).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ }
+
+ public static void threadSleep(long millis) {
+ try {
+ Thread.sleep(millis);
+ } catch (InterruptedException e) {
+ // we simply ignore if sleep was interrupted
+ }
+ }
+
+ public static String joinSet(Set set, String separator) {
+ StringBuilder sb = new StringBuilder();
+ int i = 0;
+ for (String item : set) {
+ final String itemToAdd = item.trim();
+ if (itemToAdd.length() > 0) {
+ if (i > 0) {
+ sb.append(separator);
+ }
+ i++;
+ sb.append(itemToAdd);
+ }
+ }
+ return sb.toString();
+ }
+
+ public static Set explodeSet(String joined, String separator) {
+ // special RegEx literal \\Q starts sequence we escape, \\E ends is
+ // we use it to escape separator for use in RegEx
+ String[] items = joined.split("\\Q"+separator+"\\E");
+ Set set = new HashSet<>();
+ for (String item : items) {
+ final String itemToAdd = item.trim();
+ if (itemToAdd.length() > 0) {
+ set.add(itemToAdd);
+ }
+ }
+ return set;
+ }
+
+ /**
+ * Taken out to helper method to allow testing
+ */
+ public static DataMap bundleToDataMap(Bundle bundle) {
+ return DataMap.fromBundle(bundle);
+ }
}
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java
index 229eb64f1b..1d1f5758e8 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java
@@ -10,7 +10,6 @@ import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
-import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
@@ -33,20 +32,18 @@ import com.ustwo.clockwise.common.WatchFaceTime;
import com.ustwo.clockwise.common.WatchShape;
import java.text.SimpleDateFormat;
-import java.util.ArrayList;
import java.util.Date;
-import info.nightscout.androidaps.data.BasalWatchData;
-import info.nightscout.androidaps.data.BgWatchData;
-import info.nightscout.androidaps.data.BolusWatchData;
+import info.nightscout.androidaps.complications.BaseComplicationProviderService;
+import info.nightscout.androidaps.data.RawDisplayData;
import info.nightscout.androidaps.data.ListenerService;
import info.nightscout.androidaps.R;
-import info.nightscout.androidaps.data.TempWatchData;
import lecho.lib.hellocharts.view.LineChartView;
/**
* Created by emmablack on 12/29/14.
* Updated by andrew-warrington on 02-Jan-2018.
+ * Refactored by dlvoy on 2019-11-2019
*/
public abstract class BaseWatchFace extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener {
@@ -54,13 +51,10 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
public static final long[] vibratePattern = {0,400,300,400,300,400};
public TextView mTime, mSgv, mDirection, mTimestamp, mUploaderBattery, mRigBattery, mDelta, mAvgDelta, mStatus, mBasalRate, mIOB1, mIOB2, mCOB1, mCOB2, mBgi, mLoop, mDay, mMonth, isAAPSv2, mHighLight, mLowLight;
public ImageView mGlucoseDial, mDeltaGauge, mHourHand, mMinuteHand;
- public long datetime;
public RelativeLayout mRelativeLayout;
public LinearLayout mLinearLayout, mLinearLayout2, mDate, mChartTap, mMainMenuTap;
- public long sgvLevel = 0;
public int ageLevel = 1;
public int loopLevel = 1;
- public int batteryLevel = 1;
public int highColor = Color.YELLOW;
public int lowColor = Color.RED;
public int midColor = Color.WHITE;
@@ -74,11 +68,9 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
public int pointSize = 2;
public BgGraphBuilder bgGraphBuilder;
public LineChartView chart;
- public ArrayList bgDataList = new ArrayList<>();
- public ArrayList tempWatchDataList = new ArrayList<>();
- public ArrayList basalWatchDataList = new ArrayList<>();
- public ArrayList bolusWatchDataList = new ArrayList<>();
- public ArrayList predictionList = new ArrayList<>();
+
+
+ public RawDisplayData rawData = new RawDisplayData();
public PowerManager.WakeLock wakeLock;
// related endTime manual layout
@@ -90,26 +82,9 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
protected SharedPreferences sharedPrefs;
- public boolean detailedIOB = false;
- public boolean showBGI = false;
public boolean forceSquareCanvas = false; //set to true by the Steampunk watch face.
- public long openApsStatus;
- public String externalStatusString = "no status";
- public String sSgv = "---";
- public String sDirection = "--";
- public String sUploaderBattery = "--";
- public String sRigBattery = "--";
- public String sDelta = "--";
- public String sAvgDelta = "--";
- public String sBasalRate = "-.--U/h";
- public String sIOB1 = "IOB";
- public String sIOB2 = "-.--";
- public String sCOB1 = "Carb";
- public String sCOB2 = "--g";
- public String sBgi = "--";
public String sMinute = "0";
public String sHour = "0";
- public String sUnits = "-";
@Override
public void onCreate() {
@@ -126,6 +101,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
sharedPrefs.registerOnSharedPreferenceChangeListener(this);
+
+ BaseComplicationProviderService.turnOff();
}
@Override
@@ -197,11 +174,11 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
public double timeSince() {
- return System.currentTimeMillis() - datetime;
+ return System.currentTimeMillis() - rawData.datetime;
}
public String readingAge(boolean shortString) {
- if (datetime == 0) { return shortString?"--'":"-- Minute ago"; }
+ if (rawData.datetime == 0) { return shortString?"--'":"-- Minute ago"; }
int minutesAgo = (int) Math.floor(timeSince()/(1000*60));
if (minutesAgo == 1) {
return minutesAgo + (shortString?"'":" Minute ago");
@@ -266,50 +243,20 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
@Override
public void onReceive(Context context, Intent intent) {
- Bundle bundle = intent.getBundleExtra("data");
- if (layoutSet && bundle != null) {
- DataMap dataMap = DataMap.fromBundle(bundle);
- wakeLock.acquire(50);
- sgvLevel = dataMap.getLong("sgvLevel");
- datetime = dataMap.getLong("timestamp");
- sSgv = dataMap.getString("sgvString");
- sDirection = dataMap.getString("slopeArrow");
- sDelta = dataMap.getString("delta");
- sAvgDelta = dataMap.getString("avgDelta");
- sUnits = dataMap.getString("glucoseUnits");
- if (chart != null) {
- addToWatchSet(dataMap);
+ if (layoutSet) {
+ final DataMap dataMap = rawData.updateDataFromMessage(intent, wakeLock);
+ if (chart != null && dataMap != null) {
+ rawData.addToWatchSet(dataMap);
setupCharts();
}
- }
-
- bundle = intent.getBundleExtra("status");
- if (layoutSet && bundle != null) {
- DataMap dataMap = DataMap.fromBundle(bundle);
- wakeLock.acquire(50);
- sBasalRate = dataMap.getString("currentBasal");
- sUploaderBattery = dataMap.getString("battery");
- sRigBattery = dataMap.getString("rigBattery");
- detailedIOB = dataMap.getBoolean("detailedIob");
- sIOB1 = dataMap.getString("iobSum") + "U";
- sIOB2 = dataMap.getString("iobDetail");
- sCOB1 = "Carb";
- sCOB2 = dataMap.getString("cob");
- sBgi = dataMap.getString("bgi");
- showBGI = dataMap.getBoolean("showBgi");
- externalStatusString = dataMap.getString("externalStatusString");
- batteryLevel = dataMap.getInt("batteryLevel");
- openApsStatus = dataMap.getLong("openApsStatus");
+ rawData.updateStatusFromMessage(intent, wakeLock);
}
setDataFields();
setColor();
- bundle = intent.getBundleExtra("basals");
- if (layoutSet && bundle != null) {
- DataMap dataMap = DataMap.fromBundle(bundle);
- wakeLock.acquire(500);
- loadBasalsAndTemps(dataMap);
+ if (layoutSet) {
+ rawData.updateBasalsFromMessage(intent, wakeLock);
}
mRelativeLayout.measure(specW, specH);
@@ -328,7 +275,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mSgv != null) {
if (sharedPrefs.getBoolean("showBG", true)) {
- mSgv.setText(sSgv);
+ mSgv.setText(rawData.sSgv);
mSgv.setVisibility(View.VISIBLE);
} else {
//leave the textview there but invisible, as a height holder for the empty space above the white line
@@ -341,7 +288,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mDirection != null) {
if (sharedPrefs.getBoolean("show_direction", true)) {
- mDirection.setText(sDirection);
+ mDirection.setText(rawData.sDirection);
mDirection.setVisibility(View.VISIBLE);
} else {
mDirection.setVisibility(View.GONE);
@@ -350,7 +297,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mDelta != null) {
if (sharedPrefs.getBoolean("showDelta", true)) {
- mDelta.setText(sDelta);
+ mDelta.setText(rawData.sDelta);
mDelta.setVisibility(View.VISIBLE);
} else {
mDelta.setVisibility(View.GONE);
@@ -359,7 +306,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mAvgDelta != null) {
if (sharedPrefs.getBoolean("showAvgDelta", true)) {
- mAvgDelta.setText(sAvgDelta);
+ mAvgDelta.setText(rawData.sAvgDelta);
mAvgDelta.setVisibility(View.VISIBLE);
} else {
mAvgDelta.setVisibility(View.GONE);
@@ -367,7 +314,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
if (mCOB1 != null && mCOB2 != null) {
- mCOB2.setText(sCOB2);
+ mCOB2.setText(rawData.sCOB2);
if (sharedPrefs.getBoolean("show_cob", true)) {
mCOB1.setVisibility(View.VISIBLE);
mCOB2.setVisibility(View.VISIBLE);
@@ -377,7 +324,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
//deal with cases where there is only the value shown for COB, and not the label
} else if (mCOB2 != null) {
- mCOB2.setText(sCOB2);
+ mCOB2.setText(rawData.sCOB2);
if (sharedPrefs.getBoolean("show_cob", true)) {
mCOB2.setVisibility(View.VISIBLE);
} else {
@@ -389,12 +336,12 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (sharedPrefs.getBoolean("show_iob", true)) {
mIOB1.setVisibility(View.VISIBLE);
mIOB2.setVisibility(View.VISIBLE);
- if (detailedIOB) {
- mIOB1.setText(sIOB1);
- mIOB2.setText(sIOB2);
+ if (rawData.detailedIOB) {
+ mIOB1.setText(rawData.sIOB1);
+ mIOB2.setText(rawData.sIOB2);
} else {
mIOB1.setText("IOB");
- mIOB2.setText(sIOB1);
+ mIOB2.setText(rawData.sIOB1);
}
} else {
mIOB1.setVisibility(View.GONE);
@@ -404,10 +351,10 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
} else if (mIOB2 != null) {
if (sharedPrefs.getBoolean("show_iob", true)) {
mIOB2.setVisibility(View.VISIBLE);
- if (detailedIOB) {
- mIOB2.setText(sIOB2);
+ if (rawData.detailedIOB) {
+ mIOB2.setText(rawData.sIOB2);
} else {
- mIOB2.setText(sIOB1);
+ mIOB2.setText(rawData.sIOB1);
}
} else {
mIOB2.setText("");
@@ -434,13 +381,13 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mUploaderBattery != null) {
if (sharedPrefs.getBoolean("show_uploader_battery", true)) {
if (isAAPSv2 != null) {
- mUploaderBattery.setText(sUploaderBattery + "%");
+ mUploaderBattery.setText(rawData.sUploaderBattery + "%");
mUploaderBattery.setVisibility(View.VISIBLE);
} else {
if (sharedPrefs.getBoolean("showExternalStatus", true)) {
- mUploaderBattery.setText("U: " + sUploaderBattery + "%");
+ mUploaderBattery.setText("U: " + rawData.sUploaderBattery + "%");
} else {
- mUploaderBattery.setText("Uploader: " + sUploaderBattery + "%");
+ mUploaderBattery.setText("Uploader: " + rawData.sUploaderBattery + "%");
}
}
} else {
@@ -450,7 +397,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mRigBattery != null) {
if (sharedPrefs.getBoolean("show_rig_battery", false)) {
- mRigBattery.setText(sRigBattery);
+ mRigBattery.setText(rawData.sRigBattery);
mRigBattery.setVisibility(View.VISIBLE);
} else {
mRigBattery.setVisibility(View.GONE);
@@ -459,7 +406,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mBasalRate != null) {
if (sharedPrefs.getBoolean("show_temp_basal", true)) {
- mBasalRate.setText(sBasalRate);
+ mBasalRate.setText(rawData.sBasalRate);
mBasalRate.setVisibility(View.VISIBLE);
} else {
mBasalRate.setVisibility(View.GONE);
@@ -467,8 +414,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
if (mBgi != null) {
- if (showBGI) {
- mBgi.setText(sBgi);
+ if (rawData.showBGI) {
+ mBgi.setText(rawData.sBgi);
mBgi.setVisibility(View.VISIBLE);
} else {
mBgi.setVisibility(View.GONE);
@@ -477,7 +424,7 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mStatus != null) {
if (sharedPrefs.getBoolean("showExternalStatus", true)) {
- mStatus.setText(externalStatusString);
+ mStatus.setText(rawData.externalStatusString);
mStatus.setVisibility(View.VISIBLE);
} else {
mStatus.setVisibility(View.GONE);
@@ -487,8 +434,8 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
if (mLoop != null) {
if (sharedPrefs.getBoolean("showExternalStatus", true)) {
mLoop.setVisibility(View.VISIBLE);
- if (openApsStatus != -1) {
- int mins = (int) ((System.currentTimeMillis() - openApsStatus) / 1000 / 60);
+ if (rawData.openApsStatus != -1) {
+ int mins = (int) ((System.currentTimeMillis() - rawData.openApsStatus) / 1000 / 60);
mLoop.setText(mins + "'");
if (mins > 14) {
loopLevel = 0;
@@ -594,50 +541,13 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
}
- public void addToWatchSet(DataMap dataMap) {
-
- ArrayList entries = dataMap.getDataMapArrayList("entries");
- if (entries != null) {
- bgDataList = new ArrayList();
- for (DataMap entry : entries) {
- double sgv = entry.getDouble("sgvDouble");
- double high = entry.getDouble("high");
- double low = entry.getDouble("low");
- long timestamp = entry.getLong("timestamp");
- int color = entry.getInt("color", 0);
- bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
- }
- } else {
- double sgv = dataMap.getDouble("sgvDouble");
- double high = dataMap.getDouble("high");
- double low = dataMap.getDouble("low");
- long timestamp = dataMap.getLong("timestamp");
- int color = dataMap.getInt("color", 0);
-
- final int size = bgDataList.size();
- if (size > 0) {
- if (bgDataList.get(size - 1).timestamp == timestamp)
- return; // Ignore duplicates.
- }
-
- bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color));
- }
-
- for (int i = 0; i < bgDataList.size(); i++) {
- if (bgDataList.get(i).timestamp < (System.currentTimeMillis() - (1000 * 60 * 60 * 5))) {
- bgDataList.remove(i); //Get rid of anything more than 5 hours old
- break;
- }
- }
- }
-
public void setupCharts() {
- if(bgDataList.size() > 0) { //Dont crash things just because we dont have values, people dont like crashy things
+ if(rawData.bgDataList.size() > 0) { //Dont crash things just because we dont have values, people dont like crashy things
int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3"));
if (lowResMode) {
- bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe);
+ bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), rawData, pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe);
} else {
- bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList,predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe);
+ bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), rawData, pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe);
}
chart.setLineChartData(bgGraphBuilder.lineData());
@@ -646,54 +556,4 @@ public abstract class BaseWatchFace extends WatchFace implements SharedPreferen
}
}
- private void loadBasalsAndTemps(DataMap dataMap) {
- ArrayList temps = dataMap.getDataMapArrayList("temps");
- if (temps != null) {
- tempWatchDataList = new ArrayList<>();
- for (DataMap temp : temps) {
- TempWatchData twd = new TempWatchData();
- twd.startTime = temp.getLong("starttime");
- twd.startBasal = temp.getDouble("startBasal");
- twd.endTime = temp.getLong("endtime");
- twd.endBasal = temp.getDouble("endbasal");
- twd.amount = temp.getDouble("amount");
- tempWatchDataList.add(twd);
- }
- }
- ArrayList basals = dataMap.getDataMapArrayList("basals");
- if (basals != null) {
- basalWatchDataList = new ArrayList<>();
- for (DataMap basal : basals) {
- BasalWatchData bwd = new BasalWatchData();
- bwd.startTime = basal.getLong("starttime");
- bwd.endTime = basal.getLong("endtime");
- bwd.amount = basal.getDouble("amount");
- basalWatchDataList.add(bwd);
- }
- }
- ArrayList boluses = dataMap.getDataMapArrayList("boluses");
- if (boluses != null) {
- bolusWatchDataList = new ArrayList<>();
- for (DataMap bolus : boluses) {
- BolusWatchData bwd = new BolusWatchData();
- bwd.date = bolus.getLong("date");
- bwd.bolus = bolus.getDouble("bolus");
- bwd.carbs = bolus.getDouble("carbs");
- bwd.isSMB = bolus.getBoolean("isSMB");
- bwd.isValid = bolus.getBoolean("isValid");
- bolusWatchDataList.add(bwd);
- }
- }
- ArrayList predictions = dataMap.getDataMapArrayList("predictions");
- if (boluses != null) {
- predictionList = new ArrayList<>();
- for (DataMap prediction : predictions) {
- BgWatchData bwd = new BgWatchData();
- bwd.timestamp = prediction.getLong("timestamp");
- bwd.sgv = prediction.getDouble("sgv");
- bwd.color = prediction.getInt("color");
- predictionList.add(bwd);
- }
- }
- }
}
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java
index 4a401489d9..ee17d91e76 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java
@@ -1,7 +1,6 @@
package info.nightscout.androidaps.watchfaces;
import android.content.Context;
-import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.preference.PreferenceManager;
import android.text.format.DateFormat;
@@ -18,6 +17,7 @@ import java.util.TimeZone;
import info.nightscout.androidaps.data.BasalWatchData;
import info.nightscout.androidaps.data.BgWatchData;
import info.nightscout.androidaps.data.BolusWatchData;
+import info.nightscout.androidaps.data.RawDisplayData;
import info.nightscout.androidaps.data.TempWatchData;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
@@ -115,6 +115,42 @@ public class BgGraphBuilder {
this.end_time = (predictionEndTime>end_time)?predictionEndTime:end_time;
}
+ public BgGraphBuilder(Context context, RawDisplayData raw, int aPointSize, int aHighColor, int aLowColor, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) {
+ this(context,
+ raw.bgDataList,
+ raw.predictionList,
+ raw.tempWatchDataList,
+ raw.basalWatchDataList,
+ raw.bolusWatchDataList,
+ aPointSize,
+ aHighColor,
+ aLowColor,
+ aMidColor,
+ gridColour,
+ basalBackgroundColor,
+ basalCenterColor,
+ bolusInvalidColor,
+ carbsColor,
+ timespan);
+ }
+
+ public BgGraphBuilder(Context context, RawDisplayData raw, int aPointSize, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) {
+ this(context,
+ raw.bgDataList,
+ raw.predictionList,
+ raw.tempWatchDataList,
+ raw.basalWatchDataList,
+ raw.bolusWatchDataList,
+ aPointSize,
+ aMidColor,
+ gridColour,
+ basalBackgroundColor,
+ basalCenterColor,
+ bolusInvalidColor,
+ carbsColor,
+ timespan);
+ }
+
public LineChartData lineData() {
LineChartData lineData = new LineChartData(defaultLines());
lineData.setAxisYLeft(yAxis());
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java
index b949e3832a..31d293929a 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java
@@ -48,13 +48,13 @@ public class Cockpit extends BaseWatchFace {
setTextSizes();
if (mHighLight != null && mLowLight != null) {
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mHighLight.setBackgroundResource(R.drawable.airplane_led_yellow_lit);
mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit);
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit);
mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit);
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit);
mLowLight.setBackgroundResource(R.drawable.airplane_led_red_lit);
}
@@ -82,7 +82,7 @@ public class Cockpit extends BaseWatchFace {
protected void setTextSizes() {
if (mIOB2 != null) {
- if (detailedIOB) {
+ if (rawData.detailedIOB) {
if (bIsRound) {
mIOB2.setTextSize(10);
} else {
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java
index 430a3feb47..209e6214e7 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java
@@ -68,15 +68,15 @@ public class Home extends BaseWatchFace {
mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView));
mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime));
mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background));
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
@@ -88,7 +88,7 @@ public class Home extends BaseWatchFace {
mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld));
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBattery));
} else {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty));
@@ -133,15 +133,15 @@ public class Home extends BaseWatchFace {
if (getCurrentWatchMode() == WatchMode.INTERACTIVE) {
mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_stripe_background));
mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background));
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
@@ -153,7 +153,7 @@ public class Home extends BaseWatchFace {
mTimestamp.setTextColor(Color.RED);
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(Color.WHITE);
} else {
mUploaderBattery.setTextColor(Color.RED);
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java
index 41c9fd3029..fbc69f3c1a 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java
@@ -78,13 +78,13 @@ public class Home2 extends BaseWatchFace {
setTextSizes();
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
}
@@ -95,7 +95,7 @@ public class Home2 extends BaseWatchFace {
mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld));
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBattery));
} else {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty));
@@ -176,13 +176,13 @@ public class Home2 extends BaseWatchFace {
setTextSizes();
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
}
@@ -193,7 +193,7 @@ public class Home2 extends BaseWatchFace {
mTimestamp.setTextColor(Color.RED);
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
} else {
mUploaderBattery.setTextColor(Color.RED);
@@ -229,7 +229,7 @@ public class Home2 extends BaseWatchFace {
if (mIOB1 != null && mIOB2 != null) {
- if (detailedIOB) {
+ if (rawData.detailedIOB) {
mIOB1.setTextSize(14);
mIOB2.setTextSize(10);
} else {
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java
index ffb8dce3ad..75b7d995dd 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java
@@ -52,15 +52,15 @@ public class LargeHome extends BaseWatchFace {
mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mLinearLayout));
mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime));
mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background));
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor));
@@ -72,7 +72,7 @@ public class LargeHome extends BaseWatchFace {
mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld));
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBattery));
} else {
mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty));
@@ -86,15 +86,15 @@ public class LargeHome extends BaseWatchFace {
if (getCurrentWatchMode() == WatchMode.INTERACTIVE) {
mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_stripe_background));
mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background));
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor));
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor));
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor));
@@ -106,7 +106,7 @@ public class LargeHome extends BaseWatchFace {
mTimestamp.setTextColor(Color.RED);
}
- if (batteryLevel == 1) {
+ if (rawData.batteryLevel == 1) {
mUploaderBattery.setTextColor(Color.WHITE);
} else {
mUploaderBattery.setTextColor(Color.RED);
@@ -116,15 +116,15 @@ public class LargeHome extends BaseWatchFace {
} else {
mRelativeLayout.setBackgroundColor(Color.BLACK);
mLinearLayout.setBackgroundColor(Color.LTGRAY);
- if (sgvLevel == 1) {
+ if (rawData.sgvLevel == 1) {
mSgv.setTextColor(Color.YELLOW);
mDirection.setTextColor(Color.YELLOW);
mDelta.setTextColor(Color.YELLOW);
- } else if (sgvLevel == 0) {
+ } else if (rawData.sgvLevel == 0) {
mSgv.setTextColor(Color.WHITE);
mDirection.setTextColor(Color.WHITE);
mDelta.setTextColor(Color.WHITE);
- } else if (sgvLevel == -1) {
+ } else if (rawData.sgvLevel == -1) {
mSgv.setTextColor(Color.RED);
mDirection.setTextColor(Color.RED);
mDelta.setTextColor(Color.RED);
diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java
index c42aff1518..a600290a04 100644
--- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java
+++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java
@@ -83,24 +83,24 @@ public class Steampunk extends BaseWatchFace {
}
}
- if (!sSgv.equals("---")) {
+ if (!rawData.sSgv.equals("---")) {
float rotationAngle = 0f; //by default, show ? on the dial (? is at 0 degrees on the dial)
- if (!sUnits.equals("-")) {
+ if (!rawData.sUnits.equals("-")) {
//ensure the glucose dial is the correct units
- if (sUnits.equals("mmol")) {
+ if (rawData.sUnits.equals("mmol")) {
mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mmol);
} else {
mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mgdl);
}
//convert the Sgv to degrees of rotation
- if (sUnits.equals("mmol")) {
- rotationAngle = Float.valueOf(sSgv) * 18f; //convert to mg/dL, which is equivalent to degrees
+ if (rawData.sUnits.equals("mmol")) {
+ rotationAngle = Float.valueOf(rawData.sSgv) * 18f; //convert to mg/dL, which is equivalent to degrees
} else {
- rotationAngle = Float.valueOf(sSgv); //if glucose a value is received, use it to determine the amount of rotation of the dial.
+ rotationAngle = Float.valueOf(rawData.sSgv); //if glucose a value is received, use it to determine the amount of rotation of the dial.
}
}
@@ -122,36 +122,36 @@ public class Steampunk extends BaseWatchFace {
//set the delta gauge and rotate the delta pointer
float deltaIsNegative = 1f; //by default go clockwise
- if (!sAvgDelta.equals("--")) { //if a legitimate delta value is received, then...
- if (sAvgDelta.substring(0,1).equals("-")) deltaIsNegative = -1f; //if the delta is negative, go counter-clockwise
+ if (!rawData.sAvgDelta.equals("--")) { //if a legitimate delta value is received, then...
+ if (rawData.sAvgDelta.substring(0,1).equals("-")) deltaIsNegative = -1f; //if the delta is negative, go counter-clockwise
//ensure the delta gauge is the right units and granularity
- if (!sUnits.equals("-")) {
- if (sUnits.equals("mmol")) {
+ if (!rawData.sUnits.equals("-")) {
+ if (rawData.sUnits.equals("mmol")) {
if (sharedPrefs.getString("delta_granularity", "2").equals("1")) { //low
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_10);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 30f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 30f); //get rid of the sign so it can be converted to float.
}
if (sharedPrefs.getString("delta_granularity", "2").equals("2")) { //medium
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_05);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 60f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 60f); //get rid of the sign so it can be converted to float.
}
if (sharedPrefs.getString("delta_granularity", "2").equals("3")) { //high
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_03);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 100f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 100f); //get rid of the sign so it can be converted to float.
}
} else {
if (sharedPrefs.getString("delta_granularity", "2").equals("1")) { //low
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_20);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 1.5f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 1.5f); //get rid of the sign so it can be converted to float.
}
if (sharedPrefs.getString("delta_granularity", "2").equals("2")) { //medium
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_10);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 3f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 3f); //get rid of the sign so it can be converted to float.
}
if (sharedPrefs.getString("delta_granularity", "2").equals("3")) { //high
mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_5);
- deltaRotationAngle = (Float.valueOf(sAvgDelta.substring(1)) * 6f); //get rid of the sign so it can be converted to float.
+ deltaRotationAngle = (Float.valueOf(rawData.sAvgDelta.substring(1)) * 6f); //get rid of the sign so it can be converted to float.
}
}
}
@@ -213,7 +213,7 @@ public class Steampunk extends BaseWatchFace {
//top row. large font unless text too big (i.e. detailedIOB)
mCOB2.setTextSize(fontLarge);
mBasalRate.setTextSize(fontLarge);
- if (sIOB2.length() < 7) {
+ if (rawData.sIOB2.length() < 7) {
mIOB2.setTextSize(fontLarge);
} else {
mIOB2.setTextSize(fontSmall);
diff --git a/wear/src/main/res/drawable/ic_aaps_dark.xml b/wear/src/main/res/drawable/ic_aaps_dark.xml
new file mode 100644
index 0000000000..4126fec9d9
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_aaps_dark.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/wear/src/main/res/drawable/ic_aaps_full.xml b/wear/src/main/res/drawable/ic_aaps_full.xml
new file mode 100644
index 0000000000..cf9716870c
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_aaps_full.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/wear/src/main/res/drawable/ic_aaps_gray.xml b/wear/src/main/res/drawable/ic_aaps_gray.xml
new file mode 100644
index 0000000000..1797ca3c9a
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_aaps_gray.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/wear/src/main/res/drawable/ic_aaps_light.xml b/wear/src/main/res/drawable/ic_aaps_light.xml
new file mode 100644
index 0000000000..cf9716870c
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_aaps_light.xml
@@ -0,0 +1,12 @@
+
+
+
+
diff --git a/wear/src/main/res/drawable/ic_alert.xml b/wear/src/main/res/drawable/ic_alert.xml
new file mode 100644
index 0000000000..d95c322d47
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_alert.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_alert_burnin.xml b/wear/src/main/res/drawable/ic_alert_burnin.xml
new file mode 100644
index 0000000000..6f7bd23ef0
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_alert_burnin.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_alert_variant_outline.xml b/wear/src/main/res/drawable/ic_battery_alert_variant_outline.xml
new file mode 100644
index 0000000000..516ae49c17
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_alert_variant_outline.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless.xml
new file mode 100644
index 0000000000..bd6bee5fb1
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_10.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_10.xml
new file mode 100644
index 0000000000..932c4e5930
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_10.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_10_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_10_burnin.xml
new file mode 100644
index 0000000000..a47508a1a9
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_10_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_20.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_20.xml
new file mode 100644
index 0000000000..00af480fcd
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_20.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_20_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_20_burnin.xml
new file mode 100644
index 0000000000..e08ff88448
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_20_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_30.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_30.xml
new file mode 100644
index 0000000000..592d0f380c
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_30.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_30_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_30_burnin.xml
new file mode 100644
index 0000000000..eb36861925
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_30_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_40.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_40.xml
new file mode 100644
index 0000000000..f94f85a69b
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_40.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_40_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_40_burnin.xml
new file mode 100644
index 0000000000..8980db2391
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_40_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_50.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_50.xml
new file mode 100644
index 0000000000..f6a4148589
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_50.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_50_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_50_burnin.xml
new file mode 100644
index 0000000000..9a9ee645dc
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_50_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_60.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_60.xml
new file mode 100644
index 0000000000..29192af0ed
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_60.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_60_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_60_burnin.xml
new file mode 100644
index 0000000000..d5191601a6
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_60_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_70.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_70.xml
new file mode 100644
index 0000000000..02c0ae7f58
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_70.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_70_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_70_burnin.xml
new file mode 100644
index 0000000000..9efc928672
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_70_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_80.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_80.xml
new file mode 100644
index 0000000000..21e44f7105
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_80.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_80_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_80_burnin.xml
new file mode 100644
index 0000000000..9f212fad87
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_80_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_90.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_90.xml
new file mode 100644
index 0000000000..1004964eb2
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_90.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_90_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_90_burnin.xml
new file mode 100644
index 0000000000..b6b371fa20
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_90_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_burnin.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_burnin.xml
new file mode 100644
index 0000000000..fd11b20ac9
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_battery_charging_wireless_outline.xml b/wear/src/main/res/drawable/ic_battery_charging_wireless_outline.xml
new file mode 100644
index 0000000000..5fa535e117
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_charging_wireless_outline.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_outline.xml b/wear/src/main/res/drawable/ic_battery_outline.xml
new file mode 100644
index 0000000000..c066289e18
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_outline.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_unknown.xml b/wear/src/main/res/drawable/ic_battery_unknown.xml
new file mode 100644
index 0000000000..0ac1d8a740
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_unknown.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/drawable/ic_battery_unknown_burnin.xml b/wear/src/main/res/drawable/ic_battery_unknown_burnin.xml
new file mode 100644
index 0000000000..e6271cce70
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_battery_unknown_burnin.xml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_br_cob_iob.xml b/wear/src/main/res/drawable/ic_br_cob_iob.xml
new file mode 100644
index 0000000000..39ab3af490
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_br_cob_iob.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_carbs.xml b/wear/src/main/res/drawable/ic_carbs.xml
new file mode 100644
index 0000000000..a1ac753064
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_carbs.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_cob_detailed.xml b/wear/src/main/res/drawable/ic_cob_detailed.xml
new file mode 100644
index 0000000000..fc92be1910
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_cob_detailed.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_cob_iob.xml b/wear/src/main/res/drawable/ic_cob_iob.xml
new file mode 100644
index 0000000000..f029cf0d49
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_cob_iob.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_ins.xml b/wear/src/main/res/drawable/ic_ins.xml
new file mode 100644
index 0000000000..9fbb294190
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_ins.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_ins_burnin.xml b/wear/src/main/res/drawable/ic_ins_burnin.xml
new file mode 100644
index 0000000000..8a3a16c64b
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_ins_burnin.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_iob_detailed.xml b/wear/src/main/res/drawable/ic_iob_detailed.xml
new file mode 100644
index 0000000000..95974f2fed
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_iob_detailed.xml
@@ -0,0 +1,11 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_sgv.xml b/wear/src/main/res/drawable/ic_sgv.xml
new file mode 100644
index 0000000000..e7aefdd542
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_sgv.xml
@@ -0,0 +1,13 @@
+
+
+
diff --git a/wear/src/main/res/drawable/ic_sync_alert.xml b/wear/src/main/res/drawable/ic_sync_alert.xml
new file mode 100644
index 0000000000..bd4ca18d5f
--- /dev/null
+++ b/wear/src/main/res/drawable/ic_sync_alert.xml
@@ -0,0 +1,9 @@
+
+
+
+
\ No newline at end of file
diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml
index d50cb015e6..ca24978853 100644
--- a/wear/src/main/res/values/strings.xml
+++ b/wear/src/main/res/values/strings.xml
@@ -46,6 +46,25 @@
4
+
+ Default
+ Menu
+ Wizard
+ Bolus
+ eCarb
+ Status
+ None
+
+
+
+ default
+ menu
+ wizard
+ bolus
+ ecarb
+ status
+ none
+ AAPSAAPS(Large)
@@ -53,4 +72,13 @@
AAPS(NoChart)AAPS(Circle)
+
+ No data!
+ Old data!
+ Since %1$s
+ Sync with AAPS!
+
+ No data received since %1$s! Check if AAPS on the phone sends data to watch
+ AAPS data is %1$s old! Check your sensor, xDrip+, NS, AAPS config or other!
+
diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml
index 0befaddfd0..aa8a3f6ba2 100644
--- a/wear/src/main/res/xml/preferences.xml
+++ b/wear/src/main/res/xml/preferences.xml
@@ -209,6 +209,20 @@
android:title="Wizard Percentage"
app:wear_iconOff="@drawable/settings_off"
app:wear_iconOn="@drawable/settings_on"/>
+
+ set = new HashSet<>();
+
+ // THEN
+ assertFalse(set.contains(inserted));
+ set.add(inserted);
+ assertTrue(set.contains(inserted));
+ }
+
+ /**
+ * BgWatchData has BIZARRE equals - only timestamp and color are checked!
+ */
+ @Test
+ public void bgWatchDataEqualsTest() {
+ // GIVEN
+ BgWatchData item1 = new BgWatchData(
+ 88.0, 160.0, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1
+ );
+
+ BgWatchData item2sameTimeSameColor = new BgWatchData(
+ 123.0, 190, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1
+ );
+
+ BgWatchData item3sameTimeSameDiffColor = new BgWatchData(
+ 96.0, 190, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 0
+ );
+ BgWatchData item4differentTime = new BgWatchData(
+ 88.0, 160.0, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2, 1
+ );
+
+ // THEN
+ assertEquals(item1, item2sameTimeSameColor);
+ assertNotEquals(item1, item3sameTimeSameDiffColor);
+ assertNotEquals(item1, item4differentTime);
+
+ assertFalse(item1.equals("aa bbb"));
+ }
+
+ /**
+ * BgWatchData is ordered by timestamp, reverse order
+ */
+ @Test
+ public void bgWatchDataCompareTest() {
+ // GIVEN
+ BgWatchData item1 = new BgWatchData(
+ 85, 160.0, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2, 1
+ );
+
+ BgWatchData item2 = new BgWatchData(
+ 80, 190, 90.0,
+ WearUtilMocker.REF_NOW, 1
+ );
+
+ BgWatchData item3 = new BgWatchData(
+ 80, 190, 50.0,
+ WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*5, 0
+ );
+
+ BgWatchData item4 = new BgWatchData(
+ 160, 140, 70.0,
+ WearUtilMocker.REF_NOW, 0
+ );
+
+ // THEN
+ assertThat(item2, lessThan(item1));
+ assertThat(item2, greaterThan(item3));
+ assertThat(item2, comparesEqualTo(item4));
+ }
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java
new file mode 100644
index 0000000000..fa73a0272e
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java
@@ -0,0 +1,148 @@
+package info.nightscout.androidaps.data;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+import info.nightscout.androidaps.testing.mockers.AAPSMocker;
+import info.nightscout.androidaps.testing.mockers.AndroidMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+import info.nightscout.androidaps.testing.mocks.BundleMock;
+import info.nightscout.androidaps.testing.mocks.IntentMock;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
+public class RawDataSgvDisplayDataTest {
+
+ @Before
+ public void mock() throws Exception {
+ AAPSMocker.prepareMock();
+ AAPSMocker.resetMockedSharedPrefs();
+ AndroidMocker.mockBase64();
+ WearUtilMocker.prepareMockNoReal();
+ }
+
+ //==============================================================================================
+ // SGV DATA
+ //==============================================================================================
+
+ private DataMap dataMapForData() {
+ DataMap dataMap = new DataMap();
+ dataMap.putLong("sgvLevel", 1L);
+ dataMap.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS);
+ dataMap.putString("sgvString", "106");
+ dataMap.putString("slopeArrow", "↗");
+ dataMap.putString("delta", "5.4");
+ dataMap.putString("avgDelta", "3.7");
+ dataMap.putString("glucoseUnits", "mg/dl");
+ return dataMap;
+ }
+
+ private void assertDataEmpty(RawDisplayData newRaw) {
+ assertThat(newRaw.sgvLevel, is(0L));
+ assertThat(newRaw.datetime, is(0L));
+ assertThat(newRaw.sSgv, is("---"));
+ assertThat(newRaw.sDirection, is("--"));
+ assertThat(newRaw.sDelta, is("--"));
+ assertThat(newRaw.sAvgDelta, is("--"));
+ assertThat(newRaw.sUnits, is("-"));
+ }
+
+ private void assertDataOk(RawDisplayData newRaw) {
+ assertThat(newRaw.sgvLevel, is(1L));
+ assertThat(newRaw.datetime, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS));
+ assertThat(newRaw.sSgv, is("106"));
+ assertThat(newRaw.sDirection, is("↗"));
+ assertThat(newRaw.sDelta, is("5.4"));
+ assertThat(newRaw.sAvgDelta, is("3.7"));
+ assertThat(newRaw.sUnits, is("mg/dl"));
+ }
+
+ @Test
+ public void updateDataFromEmptyPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertDataEmpty(newRaw);
+ }
+
+ @Test
+ public void updateDataFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMapForData());
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertDataOk(newRaw);
+ }
+
+ @Test
+ public void partialUpdateDataFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMapForData());
+ newRaw.updateForComplicationsFromPersistence(persistence);
+
+ // THEN
+ assertDataOk(newRaw);
+ }
+
+ @Test
+ public void updateDataFromMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ Bundle bundle = BundleMock.mock(dataMapForData());
+
+ intent.putExtra("data", bundle);
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateDataFromMessage(intent, null);
+
+ // THEN
+ assertDataOk(newRaw);
+ }
+
+ @Test
+ public void updateDataFromEmptyMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateDataFromMessage(intent, null);
+
+ // THEN
+ assertDataEmpty(newRaw);
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java
new file mode 100644
index 0000000000..1245d0fbcb
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java
@@ -0,0 +1,265 @@
+package info.nightscout.androidaps.data;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.util.ArrayList;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+import info.nightscout.androidaps.testing.mockers.AAPSMocker;
+import info.nightscout.androidaps.testing.mockers.AndroidMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+import info.nightscout.androidaps.testing.mocks.BundleMock;
+import info.nightscout.androidaps.testing.mocks.IntentMock;
+import info.nightscout.androidaps.testing.utils.BasalWatchDataExt;
+import info.nightscout.androidaps.testing.utils.BgWatchDataExt;
+import info.nightscout.androidaps.testing.utils.BolusWatchDataExt;
+import info.nightscout.androidaps.testing.utils.TempWatchDataExt;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
+public class RawDisplayDataBasalsTest {
+
+ @Before
+ public void mock() throws Exception {
+ AAPSMocker.prepareMock();
+ AAPSMocker.resetMockedSharedPrefs();
+ AndroidMocker.mockBase64();
+ WearUtilMocker.prepareMockNoReal();
+ }
+
+ //==============================================================================================
+ // BASALS for chart
+ //==============================================================================================
+
+ private DataMap dataMapForBasals() {
+
+ DataMap dataMap = new DataMap();
+
+ ArrayList temps = new ArrayList<>();
+ DataMap temp = new DataMap();
+ temp.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20);
+ temp.putDouble("startBasal", 1.5);
+ temp.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10);
+ temp.putDouble("endbasal", 1.5);
+ temp.putDouble("amount", 1.8);
+ temps.add(temp);
+
+ DataMap temp2 = new DataMap();
+ temp2.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10);
+ temp2.putDouble("startBasal", 1.3);
+ temp2.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
+ temp2.putDouble("endbasal", 1.3);
+ temp2.putDouble("amount", 2.3);
+ temps.add(temp2);
+ dataMap.putDataMapArrayList("temps", temps);
+
+ ArrayList basals = new ArrayList<>();
+ DataMap basal = new DataMap();
+ basal.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20);
+ basal.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
+ basal.putDouble("amount", 1.2);
+ basals.add(basal);
+ dataMap.putDataMapArrayList("basals", basals);
+
+ ArrayList boluses = new ArrayList<>();
+ DataMap bolus = new DataMap();
+ bolus.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*17);
+ bolus.putDouble("bolus", 5.5);
+ bolus.putDouble("carbs", 20.0);
+ bolus.putBoolean("isSMB", false);
+ bolus.putBoolean("isValid", true);
+ boluses.add(bolus);
+
+ DataMap bolus2 = new DataMap();
+ bolus2.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*11);
+ bolus2.putDouble("bolus", 3.0);
+ bolus2.putDouble("carbs", 0.0);
+ bolus2.putBoolean("isSMB", false);
+ bolus2.putBoolean("isValid", true);
+ boluses.add(bolus2);
+
+ DataMap bolus3 = new DataMap();
+ bolus3.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*3);
+ bolus3.putDouble("bolus", 0.0);
+ bolus3.putDouble("carbs", 15.0);
+ bolus3.putBoolean("isSMB", true);
+ bolus3.putBoolean("isValid", false);
+ boluses.add(bolus3);
+
+ dataMap.putDataMapArrayList("boluses", boluses);
+
+ ArrayList predictions = new ArrayList<>();
+ for (int i=0; i<10; i++) {
+ DataMap prediction = new DataMap();
+ prediction.putLong("timestamp", WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*i);
+ prediction.putDouble("sgv", 160-4*i);
+ prediction.putInt("color", 0);
+ predictions.add(prediction);
+ }
+ dataMap.putDataMapArrayList("predictions", predictions);
+
+ return dataMap;
+ }
+
+ private void assertBasalsEmpty(RawDisplayData newRaw) {
+ assertThat(newRaw.tempWatchDataList.size(), is(0));
+ assertThat(newRaw.basalWatchDataList.size(), is(0));
+ assertThat(newRaw.bolusWatchDataList.size(), is(0));
+ assertThat(newRaw.predictionList.size(), is(0));
+ }
+
+ private void assertBasalsOk(RawDisplayData newRaw) {
+ assertThat(newRaw.tempWatchDataList.size(), is(2));
+ assertThat(newRaw.basalWatchDataList.size(), is(1));
+ assertThat(newRaw.bolusWatchDataList.size(), is(3));
+ assertThat(newRaw.predictionList.size(), is(10));
+
+ assertThat(new TempWatchDataExt(newRaw.tempWatchDataList.get(0)), is(TempWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20,
+ 1.5,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10,
+ 1.5,
+ 1.8
+ )));
+
+ assertThat(new TempWatchDataExt(newRaw.tempWatchDataList.get(1)), is(TempWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*10,
+ 1.3,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2,
+ 1.3,
+ 2.3
+ )));
+
+ assertThat(new BasalWatchDataExt(newRaw.basalWatchDataList.get(0)), is(BasalWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*20,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2,
+ 1.2
+ )));
+
+ assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(0)), is(BolusWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*17,
+ 5.5,
+ 20,
+ false,
+ true
+ )));
+
+ assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(1)), is(BolusWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*11,
+ 3,
+ 0,
+ false,
+ true
+ )));
+
+ assertThat(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(2)), is(BolusWatchDataExt.build(
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*3,
+ 0,
+ 15,
+ true,
+ false
+ )));
+
+
+ assertThat(new BgWatchDataExt(newRaw.predictionList.get(3)), is(BgWatchDataExt.build(
+ 160-4*3,
+ WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*3,
+ 0
+ )));
+
+ assertThat(new BgWatchDataExt(newRaw.predictionList.get(7)), is(BgWatchDataExt.build(
+ 160-4*7,
+ WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS*7,
+ 0
+ )));
+ }
+
+ @Test
+ public void updateBasalsFromEmptyPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertBasalsEmpty(newRaw);
+ }
+
+ @Test
+ public void updateBasalsFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMapForBasals());
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertBasalsOk(newRaw);
+ }
+
+ @Test
+ public void partialUpdateBasalsFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMapForBasals());
+ newRaw.updateForComplicationsFromPersistence(persistence);
+
+ // THEN
+ assertBasalsEmpty(newRaw);
+ }
+
+ @Test
+ public void updateBasalsFromMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ Bundle bundle = BundleMock.mock(dataMapForBasals());
+
+ intent.putExtra("basals", bundle);
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateBasalsFromMessage(intent, null);
+
+ // THEN
+ assertBasalsOk(newRaw);
+ }
+
+ @Test
+ public void updateBasalsFromEmptyMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateBasalsFromMessage(intent, null);
+
+ // THEN
+ assertBasalsEmpty(newRaw);
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java
new file mode 100644
index 0000000000..c200288213
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java
@@ -0,0 +1,146 @@
+package info.nightscout.androidaps.data;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.util.ArrayList;
+
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+import info.nightscout.androidaps.testing.utils.BgWatchDataExt;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class } )
+public class RawDisplayDataBgEntriesTest {
+
+ @Before
+ public void mock() throws Exception {
+ WearUtilMocker.prepareMockNoReal();
+ }
+
+ //==============================================================================================
+ // ENTRIES for chart
+ //==============================================================================================
+
+ private DataMap dataMapForEntries() {
+
+ DataMap dataMap = new DataMap();
+ ArrayList entries = new ArrayList<>();
+ for (int i=0; i<12; i++) {
+ DataMap entry = new DataMap();
+ entry.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-i));
+ entry.putDouble("sgvDouble", 145.0-5*i);
+ entry.putDouble("high", 170.0);
+ entry.putDouble("low", 80.0);
+ entry.putInt("color", 0);
+ entries.add(entry);
+ }
+ dataMap.putDataMapArrayList("entries", entries);
+
+ return dataMap;
+ }
+
+ private DataMap dataMapForEntries(long timestamp, double sgv) {
+ DataMap entry = new DataMap();
+ entry.putLong("timestamp", timestamp);
+ entry.putDouble("sgvDouble", sgv);
+ entry.putDouble("high", 160.0);
+ entry.putDouble("low", 90.0);
+ entry.putInt("color", 1);
+ return entry;
+ }
+
+ @Test
+ public void addToWatchSetTest() {
+ // GIVEN
+ RawDisplayData newRaw = new RawDisplayData();
+ DataMap multipleEntries = dataMapForEntries();
+ DataMap singleEntry1 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*2,92);
+ DataMap singleEntry2 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*1,88);
+
+ // WHEN, THEN
+ // add list
+ newRaw.addToWatchSet(multipleEntries);
+ assertThat(newRaw.bgDataList.size(), is(12));
+
+ assertThat(new BgWatchDataExt(newRaw.bgDataList.get(5)),
+ is(new BgWatchDataExt(new BgWatchData(
+ 120.0, 170.0, 80.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-5), 0
+ ))));
+
+ assertThat(new BgWatchDataExt(newRaw.bgDataList.get(11)),
+ is(new BgWatchDataExt(new BgWatchData(
+ 90.0, 170.0, 80.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*(16-11), 0
+ ))));
+
+ // add single entries
+ newRaw.addToWatchSet(singleEntry1);
+ newRaw.addToWatchSet(singleEntry2);
+ assertThat(newRaw.bgDataList.size(), is(14));
+
+ assertThat(new BgWatchDataExt(newRaw.bgDataList.get(12)),
+ is(new BgWatchDataExt(new BgWatchData(
+ 92.0, 160.0, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*2, 1
+ ))));
+ assertThat(new BgWatchDataExt(newRaw.bgDataList.get(13)),
+ is(new BgWatchDataExt(new BgWatchData(
+ 88.0, 160.0, 90.0,
+ WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*4*1, 1
+ ))));
+
+ // ignore duplicates
+ newRaw.addToWatchSet(singleEntry2);
+ assertThat(newRaw.bgDataList.size(), is(14));
+ }
+
+ @Test
+ public void addToWatchSetCleanupOldTest() {
+ RawDisplayData newRaw = new RawDisplayData();
+
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),125));
+ assertThat(newRaw.bgDataList.size(), is(1));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*2);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),140));
+ assertThat(newRaw.bgDataList.size(), is(2));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),150));
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1 +Constants.MINUTE_IN_MS*30);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),101));
+ assertThat(newRaw.bgDataList.size(), is(4));
+
+ WearUtilMocker.progressClock(Constants.MINUTE_IN_MS*30);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),90));
+ assertThat(newRaw.bgDataList.size(), is(5));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*1 +Constants.MINUTE_IN_MS*30);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),80));
+ assertThat(newRaw.bgDataList.size(), is(5));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*4);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),92));
+ assertThat(newRaw.bgDataList.size(), is(2));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*5 +Constants.MINUTE_IN_MS*30);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp(),107));
+ assertThat(newRaw.bgDataList.size(), is(1));
+
+ WearUtilMocker.progressClock(Constants.HOUR_IN_MS*6 +Constants.MINUTE_IN_MS*30);
+ newRaw.addToWatchSet(dataMapForEntries(WearUtil.timestamp()-Constants.HOUR_IN_MS*6,138));
+ assertThat(newRaw.bgDataList.size(), is(0));
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java
new file mode 100644
index 0000000000..da0daea608
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java
@@ -0,0 +1,176 @@
+package info.nightscout.androidaps.data;
+
+import android.content.Context;
+import android.content.Intent;
+import android.content.SharedPreferences;
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.Persistence;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+import info.nightscout.androidaps.testing.mockers.AAPSMocker;
+import info.nightscout.androidaps.testing.mockers.AndroidMocker;
+import info.nightscout.androidaps.testing.mockers.RawDataMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+import info.nightscout.androidaps.testing.mocks.BundleMock;
+import info.nightscout.androidaps.testing.mocks.IntentMock;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class, Intent.class } )
+public class RawDisplayDataStatusTest {
+
+ @Before
+ public void mock() throws Exception {
+ AAPSMocker.prepareMock();
+ AAPSMocker.resetMockedSharedPrefs();
+ AndroidMocker.mockBase64();
+ WearUtilMocker.prepareMockNoReal();
+ }
+
+ @Test
+ public void toDebugStringTest() {
+ RawDisplayData raw = RawDataMocker.rawDelta(5, "1.5");
+ raw.externalStatusString = "placeholder-here";
+
+ assertThat(raw.datetime, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*5));
+ assertThat(raw.toDebugString(), containsString("placeholder-here"));
+ }
+
+ //==============================================================================================
+ // STATUS
+ //==============================================================================================
+
+ private DataMap dataMapForStatus() {
+ DataMap dataMap = new DataMap();
+ dataMap.putString("currentBasal", "120%");
+ dataMap.putString("battery", "76");
+ dataMap.putString("rigBattery", "40%");
+ dataMap.putBoolean("detailedIob", true);
+ dataMap.putString("iobSum", "12.5") ;
+ dataMap.putString("iobDetail","(11,2|1,3)");
+ dataMap.putString("cob","5(10)g");
+ dataMap.putString("bgi", "13");
+ dataMap.putBoolean("showBgi", false);
+ dataMap.putString("externalStatusString", "");
+ dataMap.putInt("batteryLevel", 1);
+ dataMap.putLong("openApsStatus", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2);
+ return dataMap;
+ }
+
+ private void assertStatusEmpty(RawDisplayData newRaw) {
+ assertThat(newRaw.sBasalRate, is("-.--U/h"));
+ assertThat(newRaw.sUploaderBattery, is("--"));
+ assertThat(newRaw.sRigBattery, is("--"));
+ assertThat(newRaw.detailedIOB, is(false));
+ assertThat(newRaw.sIOB1, is("IOB"));
+ assertThat(newRaw.sIOB2, is("-.--"));
+ assertThat(newRaw.sCOB1, is("Carb"));
+ assertThat(newRaw.sCOB2, is("--g"));
+ assertThat(newRaw.sBgi, is("--"));
+ assertThat(newRaw.showBGI, is(false));
+ assertThat(newRaw.externalStatusString, is("no status"));
+ assertThat(newRaw.batteryLevel, is(1));
+ assertThat(newRaw.openApsStatus, is(-1L));
+ }
+
+ private void assertStatusOk(RawDisplayData newRaw) {
+ assertThat(newRaw.sBasalRate, is("120%"));
+ assertThat(newRaw.sUploaderBattery, is("76"));
+ assertThat(newRaw.sRigBattery, is("40%"));
+ assertThat(newRaw.detailedIOB, is(true));
+ assertThat(newRaw.sIOB1, is("12.5U"));
+ assertThat(newRaw.sIOB2, is("(11,2|1,3)"));
+ assertThat(newRaw.sCOB1, is("Carb"));
+ assertThat(newRaw.sCOB2, is("5(10)g"));
+ assertThat(newRaw.sBgi, is("13"));
+ assertThat(newRaw.showBGI, is(false));
+ assertThat(newRaw.externalStatusString, is(""));
+ assertThat(newRaw.batteryLevel, is(1));
+ assertThat(newRaw.openApsStatus, is(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS*2));
+ }
+
+ @Test
+ public void updateStatusFromEmptyPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertStatusEmpty(newRaw);
+ }
+
+ @Test
+ public void updateStatusFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMapForStatus());
+ newRaw.updateFromPersistence(persistence);
+
+ // THEN
+ assertStatusOk(newRaw);
+ }
+
+ @Test
+ public void partialUpdateStatusFromPersistenceTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ Persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMapForStatus());
+ newRaw.updateForComplicationsFromPersistence(persistence);
+
+ // THEN
+ assertStatusOk(newRaw);
+ }
+
+ @Test
+ public void updateStatusFromMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ Bundle bundle = BundleMock.mock(dataMapForStatus());
+
+ intent.putExtra("status", bundle);
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateStatusFromMessage(intent, null);
+
+ // THEN
+ assertStatusOk(newRaw);
+ }
+
+ @Test
+ public void updateStatusFromEmptyMessageTest() {
+ // GIVEN
+ Intent intent = IntentMock.mock();
+ RawDisplayData newRaw = new RawDisplayData();
+
+ // WHEN
+ newRaw.updateStatusFromMessage(intent, null);
+
+ // THEN
+ assertStatusEmpty(newRaw);
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java
new file mode 100644
index 0000000000..98fb4fd11b
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java
@@ -0,0 +1,204 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.testing.mockers.AAPSMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+
+import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawCob;
+import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawCobIobBr;
+import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawDelta;
+import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawIob;
+import static info.nightscout.androidaps.testing.mockers.RawDataMocker.rawSgv;
+import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.backInTime;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * This test covers DisplayFormat class (directly)
+ * but also SmallestDoubleString - due to carefully chosen input data to format
+ */
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class } )
+public class DisplayFormatTest {
+
+ @Before
+ public void mock() throws Exception {
+ WearUtilMocker.prepareMock();
+ AAPSMocker.prepareMock();
+ AAPSMocker.resetMockedSharedPrefs();
+ }
+
+ @Test
+ public void shortTimeSinceTest() {
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,0)), is("0'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,5)), is("0'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,0,55)), is("0'"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,1,0)), is("1'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,1,59)), is("1'"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,2,0)), is("2'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,3,0)), is("3'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,4,0)), is("4'"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,10,0)), is("10'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,30,0)), is("30'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,59,0)), is("59'"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,0,59,59)), is("59'"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,0,0)), is("1h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,30,0)), is("1h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,1,59,59)), is("1h"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,2,0,0)), is("2h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,3,0,0)), is("3h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,4,0,0)), is("4h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,5,0,0)), is("5h"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,12,0,0)), is("12h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,18,0,0)), is("18h"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(0,23,59,59)), is("23h"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(1,0,0,0)), is("1d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(1,12,0,0)), is("1d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(1,23,59,59)), is("1d"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(2,0,0,0)), is("2d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(3,0,0,0)), is("3d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(4,0,0,0)), is("4d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(5,0,0,0)), is("5d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(6,0,0,0)), is("6d"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(6,23,59,59)), is("6d"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(7,0,0,0)), is("1w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(8,0,0,0)), is("1w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(9,0,0,0)), is("1w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(13,23,59,59)), is("1w"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(14,0,0,0)), is("2w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(21,0,0,0)), is("3w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(28,0,0,0)), is("4w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(31,0,0,0)), is("4w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(32,0,0,0)), is("4w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(35,0,0,0)), is("5w"));
+
+ assertThat(DisplayFormat.shortTimeSince(backInTime(100,0,0,0)), is("14w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(200,0,0,0)), is("28w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(365,0,0,0)), is("52w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(366,0,0,0)), is("52w"));
+ assertThat(DisplayFormat.shortTimeSince(backInTime(367,0,0,0)), is("52w"));
+ }
+
+ @Test
+ public void shortTrendTest() {
+ RawDisplayData raw = new RawDisplayData();
+ assertThat(DisplayFormat.shortTrend(raw), is("-- Δ--"));
+
+ raw.datetime = backInTime(0, 0, 2, 0);
+ assertThat(DisplayFormat.shortTrend(raw), is("2' Δ--"));
+
+ AAPSMocker.setMockedUnicodeComplicationsOn(true);
+
+ // shortening
+ assertThat(DisplayFormat.shortTrend(rawDelta(2, "1.2")), is("2' Δ1.2"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(11,"1.2")), is("11' 1.2"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(12,"0.7")), is("12' Δ.7"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(10,"1.0")), is("10' Δ1"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(14,"-5.0")), is("14' Δ-5"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(13,"-5.1")), is("13' -5"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(15,"0.87")), is("15' .87"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(10,"-1.78")), is("10' -2"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(3, "2.549")), is("3' 2.55"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(1, "-1.563")), is("1' -1.6"));
+
+ // preserving separator
+ assertThat(DisplayFormat.shortTrend(rawDelta(2, "1,2")), is("2' Δ1,2"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(15,"0,87")), is("15' ,87"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(3, "+2,549")), is("3' 2,55"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(1, "-1,563")), is("1' -1,6"));
+
+ // UTF-off mode - without delta symbol
+ AAPSMocker.setMockedUnicodeComplicationsOn(false);
+ assertThat(DisplayFormat.shortTrend(rawDelta(2, "1.2")), is("2' 1.2"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(12,"0.7")), is("12' 0.7"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(10,"1.0")), is("10' 1.0"));
+ assertThat(DisplayFormat.shortTrend(rawDelta(14,"-5.0")), is("14' -5"));
+ }
+
+ @Test
+ public void longGlucoseLine() {
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("125",2, "1.2")), is("125→ Δ1.2 (2')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("97",11, "5.2")), is("97↗ Δ5.2 (11')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("110",12,"0.7")), is("110→ Δ.7 (12')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("65",10,"7.0")), is("65↗ Δ7 (10')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("215",14,"-5.0")), is("215↘ Δ-5 (14')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("8.3",13,"-5.1")), is("8.3↘ Δ-5.1 (13')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("6.8",15,"10.83")), is("6.8↑ Δ10.83 (15')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("13.2",10,"-11.78")), is("13.2↓ Δ-11.78 (10')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("3.9",3, "2.549")), is("3.9→ Δ2.549 (3')"));
+ assertThat(DisplayFormat.longGlucoseLine(rawSgv("11.1",1, "-15.563")), is("11.1↓ Δ-15.563 (1')"));
+ }
+
+ @Test
+ public void longDetailsLineTest() {
+ AAPSMocker.setMockedUnicodeComplicationsOn(true);
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0g", "0U", "3.5U/h")), is("0g ⁞ 0U ⁞ ⎍ 3.5U/h"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("50g", "7.56U", "0%")), is("50g ⁞ 7.56U ⁞ ⎍ 0%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("12g", "3.23U", "120%")), is("12g ⁞ 3.23U ⁞ 120%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("2(40)g", "-1.5U", "0.55U/h")), is("2(40)g ⁞ -2U ⁞ 0.55U/h"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0(24)g", "0.05U", "160%")), is("0(24)g ⁞ 0.05U ⁞ 160%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("47g", "13.87U", "220%")), is("47g ⁞ 13.87U ⁞ 220%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("13(5)g", "5.90U", "300%")), is("13(5)g ⁞ 5.90U ⁞ 300%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("11(50)g", "0U", "70%")), is("11(50)g ⁞ 0U ⁞ 70%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("7g", "0.54U", "30%")), is("7g ⁞ 0.54U ⁞ ⎍ 30%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), is("19g ⁞ 36U ⁞ 12.9U/h"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("100(1)g", "12.345U", "6.98647U/h")), is("100g 12U 6.98647U/h"));
+
+ AAPSMocker.setMockedUnicodeComplicationsOn(false);
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("0g", "0U", "3.5U/h")), is("0g | 0U | 3.5U/h"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("50g", "7.56U", "0%")), is("50g | 7.56U | 0%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("12g", "3.23U", "120%")), is("12g | 3.23U | 120%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("7g", "0.54U", "30%")), is("7g | 0.54U | 30%"));
+ assertThat(DisplayFormat.longDetailsLine(rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), is("19g | 36U | 12.9U/h"));
+ }
+
+ @Test
+ public void detailedIobTest() {
+ assertThat(DisplayFormat.detailedIob(rawIob("-1.29U", "(0,910|-2,20)")), is(Pair.create("-1.29U", ",91 -2")));
+ assertThat(DisplayFormat.detailedIob(rawIob("3.50U", "")), is(Pair.create("3.50U", "")));
+ assertThat(DisplayFormat.detailedIob(rawIob("12.5U", "(+1,4|-4.78)")), is(Pair.create("12.5U", "1,4 -5")));
+ assertThat(DisplayFormat.detailedIob(rawIob("0.67U", "some junks")), is(Pair.create(".67U", "")));
+ assertThat(DisplayFormat.detailedIob(rawIob("-11.0U", "(broken|data)")), is(Pair.create("-11U", "-- --")));
+ assertThat(DisplayFormat.detailedIob(rawIob("5.52U", "(0,5439|wrong)")), is(Pair.create("5.52U", ",54 --")));
+ assertThat(DisplayFormat.detailedIob(rawIob("-8.1U", "(|-8,1)")), is(Pair.create("-8.1U", "-- -8")));
+ assertThat(DisplayFormat.detailedIob(rawIob("-8.1U", "(|-8,1)")), is(Pair.create("-8.1U", "-- -8")));
+ assertThat(DisplayFormat.detailedIob(rawIob("7.6U", "(malformed)")), is(Pair.create("7.6U", "")));
+ assertThat(DisplayFormat.detailedIob(rawIob("-4.26U", "(6,97|1,3422|too much)")), is(Pair.create("-4.26U", "7 1,3")));
+ }
+
+ @Test
+ public void detailedCobTest() {
+ assertThat(DisplayFormat.detailedCob(rawCob("0g")), is(Pair.create("0g", "")));
+ assertThat(DisplayFormat.detailedCob(rawCob("50g")), is(Pair.create("50g", "")));
+ assertThat(DisplayFormat.detailedCob(rawCob("2(40)g")), is(Pair.create("2g", "40g")));
+ assertThat(DisplayFormat.detailedCob(rawCob("0(24)g")), is(Pair.create("0g", "24g")));
+ assertThat(DisplayFormat.detailedCob(rawCob("13(5)g")), is(Pair.create("13g", "5g")));
+ assertThat(DisplayFormat.detailedCob(rawCob("11(50)g")), is(Pair.create("11g", "50g")));
+ assertThat(DisplayFormat.detailedCob(rawCob("19(38)g")), is(Pair.create("19g", "38g")));
+ assertThat(DisplayFormat.detailedCob(rawCob("100(1)g")), is(Pair.create("100g", "1g")));
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java
new file mode 100644
index 0000000000..ce63330e9c
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java
@@ -0,0 +1,68 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(PowerMockRunner.class)
+public class PairTest {
+
+ @Test
+ public void pairEqualsTest() {
+ // GIVEN
+ Pair left = Pair.create("aa", "bbb");
+ Pair right = Pair.create("ccc", "dd");
+ Pair another = Pair.create("aa", "bbb");
+ Pair samePos1 = Pair.create("aa", "d");
+ Pair samePos2 = Pair.create("zzzzz", "bbb");
+ Pair no1 = Pair.create(12, 345L);
+ Pair no2 = Pair.create(-943, 42);
+ Pair no3 = Pair.create(12L, 345);
+ Pair no4 = Pair.create(12, 345L);
+
+ // THEN
+ assertNotEquals(left, right);
+ assertEquals(left, another);
+ assertNotEquals(left, samePos1);
+ assertNotEquals(left, samePos2);
+ assertNotEquals(no1, no2);
+ assertNotEquals(no1, no3);
+ assertEquals(no1, no4);
+
+ assertFalse(left.equals("aa bbb"));
+ }
+
+ @Test
+ public void pairHashTest() {
+ // GIVEN
+ Pair inserted = Pair.create("aa", "bbb");
+ Set set = new HashSet<>();
+
+ // THEN
+ assertFalse(set.contains(inserted));
+ set.add(inserted);
+ assertTrue(set.contains(inserted));
+ }
+
+ @Test
+ public void toStringTest() {
+ // GIVEN
+ Pair pair = Pair.create("the-first", "2nd");
+
+ assertThat(pair.toString(), containsString("the-first"));
+ assertThat(pair+"", containsString("2nd"));
+ }
+
+
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java
new file mode 100644
index 0000000000..1faa4ddfe7
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java
@@ -0,0 +1,189 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.util.Set;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.testing.mockers.AAPSMocker;
+import info.nightscout.androidaps.testing.mockers.AndroidMocker;
+import info.nightscout.androidaps.testing.mockers.LogMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+
+import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.REF_NOW;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class, SharedPreferences.class, Context.class, aaps.class, android.util.Base64.class} )
+public class PersistenceTest {
+
+ @Before
+ public void mock() throws Exception {
+ WearUtilMocker.prepareMock();
+ LogMocker.prepareMock();
+ AAPSMocker.prepareMock();
+ AAPSMocker.resetMockedSharedPrefs();
+ AndroidMocker.mockBase64();
+ }
+
+ @Test
+ public void putStringTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+
+ // WHEN
+ final String emptyGot = persistence.getString("test-key", "default-value");
+ persistence.putString("test-key", "newValue");
+ final String updatedGot = persistence.getString("test-key", "another-default-value");
+
+ // THEN
+ assertThat(emptyGot, is("default-value"));
+ assertThat(updatedGot, is("newValue"));
+ }
+
+ @Test
+ public void putBooleanTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+
+ // WHEN
+ final boolean emptyGot = persistence.getBoolean("test-key", false);
+ persistence.putBoolean("test-key", true);
+ final boolean updatedGot = persistence.getBoolean("test-key", false);
+
+ // THEN
+ assertFalse(emptyGot);
+ assertTrue(updatedGot);
+ }
+
+ @Test
+ public void whenDataUpdatedTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ DataMap map = new DataMap();
+
+ // WHEN
+ final long whenNotUpdated = persistence.whenDataUpdated();
+
+ Persistence.storeDataMap("data-map", map);
+ final long whenUpdatedFirst = persistence.whenDataUpdated();
+
+ WearUtilMocker.progressClock(60000);
+ Persistence.storeDataMap("data-map", map);
+ final long whenUpdatedNext = persistence.whenDataUpdated();
+
+ // THEN
+ assertThat(whenNotUpdated, is(0L));
+ assertThat(whenUpdatedFirst, is(REF_NOW));
+ assertThat(whenUpdatedNext, is(REF_NOW + 60000));
+ }
+
+ @Test
+ public void getDataMapTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+ DataMap map = new DataMap();
+ map.putByteArray("test-key", new byte[]{9, 42, 127, -5});
+
+ // WHEN
+ DataMap notExisting = persistence.getDataMap("not-there");
+ Persistence.storeDataMap("data-map", map);
+ DataMap restoredMap = persistence.getDataMap("data-map");
+ byte[] restoredMapContents = restoredMap.getByteArray("test-key");
+
+ // THEN
+ assertNull(notExisting);
+ assertNotNull(restoredMap);
+ assertTrue(restoredMap.containsKey("test-key"));
+
+ assertThat(restoredMapContents.length, is(4));
+ assertThat(restoredMapContents[0], is((byte)9));
+ assertThat(restoredMapContents[1], is((byte)42));
+ assertThat(restoredMapContents[2], is((byte)127));
+ assertThat(restoredMapContents[3], is((byte)-5));
+ }
+
+ @Test
+ public void brokenDataMapTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+
+ // WHEN
+ persistence.putString("data-map", "ZmFrZSBkYXRh");
+ DataMap restoredMap = persistence.getDataMap("data-map");
+
+ // THEN
+ assertNull(restoredMap);
+ }
+
+ @Test
+ public void setsTest() {
+ // GIVEN
+ Persistence persistence = new Persistence();
+
+ // WHEN
+ Set emptySet = persistence.getSetOf("some fake id");
+
+ persistence.addToSet("test-set", "element1");
+ persistence.addToSet("test-set", "second-elem");
+ persistence.addToSet("test-set", "3rd");
+ persistence.addToSet("test-set", "czwarty");
+ persistence.addToSet("test-set", "V");
+ persistence.addToSet("test-set", "6");
+
+ Set initialSet = persistence.getSetOf("test-set");
+ Set sameInitialSet = Persistence.setOf("test-set");
+
+ persistence.addToSet("test-set", "second-elem");
+ persistence.addToSet("test-set", "new-one");
+
+ Set extendedSet = persistence.getSetOf("test-set");
+
+ persistence.removeFromSet("test-set", "czwarty");
+ persistence.removeFromSet("test-set", "6");
+ persistence.removeFromSet("test-set", "3rd");
+
+ Set reducedSet = persistence.getSetOf("test-set");
+
+ // THEN
+ assertThat(emptySet.size(), is(0));
+
+ assertThat(initialSet.size(), is(6));
+ assertTrue(initialSet.contains("element1"));
+ assertTrue(initialSet.contains("second-elem"));
+ assertTrue(initialSet.contains("3rd"));
+ assertTrue(initialSet.contains("czwarty"));
+ assertTrue(initialSet.contains("V"));
+ assertTrue(initialSet.contains("6"));
+
+ assertThat(initialSet, is(sameInitialSet));
+
+ assertThat(extendedSet.size(), is(7));
+ assertTrue(extendedSet.contains("new-one"));
+
+ assertThat(reducedSet.size(), is(4));
+ assertTrue(reducedSet.contains("element1"));
+ assertTrue(reducedSet.contains("second-elem"));
+ assertFalse(reducedSet.contains("3rd"));
+ assertFalse(reducedSet.contains("czwarty"));
+ assertTrue(reducedSet.contains("V"));
+ assertFalse(reducedSet.contains("6"));
+ assertTrue(reducedSet.contains("new-one"));
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/SafeParseTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/SafeParseTest.java
new file mode 100644
index 0000000000..62a71e6420
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/SafeParseTest.java
@@ -0,0 +1,128 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
+
+/**
+ * Created by dlvoy on 21.11.2019.
+ */
+@RunWith(PowerMockRunner.class)
+public class SafeParseTest {
+
+ @Test
+ public void stringToDoubleTest() {
+ // correct values
+ assertThat(0.1234, is(SafeParse.stringToDouble("0.1234")));
+ assertThat(0.1234, is(SafeParse.stringToDouble("0,1234")));
+ assertThat(0.5436564812, is(SafeParse.stringToDouble(".5436564812")));
+ assertThat(0.5436564812, is(SafeParse.stringToDouble(",5436564812")));
+ assertThat(1000500100900.0, is(SafeParse.stringToDouble("1000500100900")));
+ assertThat(42.0, is(SafeParse.stringToDouble("42")));
+
+ // units or other extra values are not permitted
+ assertThat(0.0, is(SafeParse.stringToDouble("12 U/h")));
+
+ // strings are not parsable
+ assertThat(0.0, is(SafeParse.stringToDouble("ala ma kota")));
+
+ // separator errors
+ assertThat(0.0, is(SafeParse.stringToDouble("0.1234.5678")));
+ assertThat(0.0, is(SafeParse.stringToDouble("0,1234,5678")));
+
+ // various emptiness
+ assertThat(0.0, is(SafeParse.stringToDouble("")));
+ assertThat(0.0, is(SafeParse.stringToDouble(" ")));
+ assertThat(0.0, is(SafeParse.stringToDouble("\n\r")));
+ }
+
+ @Test
+ public void stringToIntTest() {
+ // correct values
+ assertThat(1052934, is(SafeParse.stringToInt("1052934")));
+ assertThat(-42, is(SafeParse.stringToInt("-42")));
+ assertThat(2147483647, is(SafeParse.stringToInt("2147483647")));
+ assertThat(-2147483648, is(SafeParse.stringToInt("-2147483648")));
+
+ // outside Integer range
+ assertThat(0, is(SafeParse.stringToInt("2147483648")));
+ assertThat(0, is(SafeParse.stringToInt("-2147483649")));
+
+ // units or other extra values are not permitted
+ assertThat(0, is(SafeParse.stringToInt("12 U/h")));
+ assertThat(0, is(SafeParse.stringToInt("0.1234")));
+ assertThat(0, is(SafeParse.stringToInt("0,1234")));
+ assertThat(0, is(SafeParse.stringToInt(".5436564812")));
+ assertThat(0, is(SafeParse.stringToInt(",5436564812")));
+ assertThat(0, is(SafeParse.stringToInt("42.1234")));
+ assertThat(0, is(SafeParse.stringToInt("42,1234")));
+ assertThat(0, is(SafeParse.stringToInt("3212.5436564812")));
+ assertThat(0, is(SafeParse.stringToInt("3212,5436564812")));
+ assertThat(0, is(SafeParse.stringToInt("1000500100900")));
+
+ // strings are not parsable
+ assertThat(0, is(SafeParse.stringToInt("ala ma kota")));
+
+ // various emptiness
+ assertThat(0, is(SafeParse.stringToInt("")));
+ assertThat(0, is(SafeParse.stringToInt(" ")));
+ assertThat(0, is(SafeParse.stringToInt("\n\r")));
+ }
+
+ @Test
+ public void stringToLongTest() {
+ // correct values
+ assertThat(1052934L, is(SafeParse.stringToLong("1052934")));
+ assertThat(-42L, is(SafeParse.stringToLong("-42")));
+ assertThat(2147483647L, is(SafeParse.stringToLong("2147483647")));
+ assertThat(-2147483648L, is(SafeParse.stringToLong("-2147483648")));
+ assertThat(1000500100900L, is(SafeParse.stringToLong("1000500100900")));
+
+ // outside Integer range
+ assertThat(2147483648L, is(SafeParse.stringToLong("2147483648")));
+ assertThat(-2147483649L, is(SafeParse.stringToLong("-2147483649")));
+
+ // units or other extra values are not permitted
+ assertThat(0L, is(SafeParse.stringToLong("12 U/h")));
+ assertThat(0L, is(SafeParse.stringToLong("0.1234")));
+ assertThat(0L, is(SafeParse.stringToLong("0,1234")));
+ assertThat(0L, is(SafeParse.stringToLong(".5436564812")));
+ assertThat(0L, is(SafeParse.stringToLong(",5436564812")));
+ assertThat(0L, is(SafeParse.stringToLong("42.1234")));
+ assertThat(0L, is(SafeParse.stringToLong("42,1234")));
+ assertThat(0L, is(SafeParse.stringToLong("3212.5436564812")));
+ assertThat(0L, is(SafeParse.stringToLong("3212,5436564812")));
+
+ // strings are not parsable
+ assertThat(0L, is(SafeParse.stringToLong("ala ma kota")));
+
+ // various emptiness
+ assertThat(0L, is(SafeParse.stringToLong("")));
+ assertThat(0L, is(SafeParse.stringToLong(" ")));
+ assertThat(0L, is(SafeParse.stringToLong("\n\r")));
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void stringToDoubleNullTest() {
+ SafeParse.stringToDouble(null);
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void stringToIntNullTest() {
+ SafeParse.stringToInt(null);
+ }
+
+ @Test(expected=NullPointerException.class)
+ public void stringToLongNullTest() {
+ SafeParse.stringToLong(null);
+ }
+
+ @Before
+ public void prepareMock() {
+
+ }
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.java
new file mode 100644
index 0000000000..9e60423c6a
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.java
@@ -0,0 +1,186 @@
+package info.nightscout.androidaps.interaction.utils;
+
+import android.os.Bundle;
+import android.util.Log;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.junit4.PowerMockRunner;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import info.nightscout.androidaps.testing.mockers.LogMocker;
+import info.nightscout.androidaps.testing.mockers.WearUtilMocker;
+import info.nightscout.androidaps.testing.mocks.BundleMock;
+
+import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.REF_NOW;
+import static org.hamcrest.CoreMatchers.both;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.Matchers.greaterThan;
+import static org.hamcrest.Matchers.lessThan;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Created by dlvoy on 22.11.2019.
+ */
+@RunWith(PowerMockRunner.class)
+@PrepareForTest( { WearUtil.class, Log.class} )
+public class WearUtilTest {
+
+ @Before
+ public void mock() throws Exception {
+ WearUtilMocker.prepareMock();
+ LogMocker.prepareMock();
+ }
+
+ @Test
+ public void timestampAndTimeDiffsTest() {
+
+ // smoke for mocks - since we freeze "now" to get stable tests
+ assertThat(REF_NOW, is(WearUtil.timestamp()));
+
+ assertThat(0L, is(WearUtil.msTill(REF_NOW)));
+ assertThat(3456L, is(WearUtil.msTill(REF_NOW+3456L)));
+ assertThat(-6294L, is(WearUtil.msTill(REF_NOW-6294L)));
+
+ assertThat(0L, is(WearUtil.msTill(REF_NOW)));
+ assertThat(-3456L, is(WearUtil.msSince(REF_NOW+3456L)));
+ assertThat(6294L, is(WearUtil.msSince(REF_NOW-6294L)));
+ }
+
+ @Test
+ public void joinSetTest() {
+ // GIVEN
+ Set refSet = new HashSet<>();
+ refSet.add("element1");
+ refSet.add("second-elem");
+ refSet.add("3rd");
+
+ // WHEN
+ String joined = WearUtil.joinSet(refSet, "|");
+
+ // THEN
+ // we cannot guarantee order of items in joined string
+ // but all items have to be there
+ assertThat(joined.length(), is("element1".length() + "second-elem".length() + "3rd".length() + "|".length()*2 ));
+
+ assertThat("|"+joined+"|", containsString("|"+"element1"+"|"));
+ assertThat("|"+joined+"|", containsString("|"+"second-elem"+"|"));
+ assertThat("|"+joined+"|", containsString("|"+"3rd"+"|"));
+ }
+
+ @Test
+ public void explodeSetTest() {
+ // GIVEN
+ String serializedSet = "second-elem:element1:3rd";
+
+ // WHEN
+ Set set = WearUtil.explodeSet(serializedSet, ":");
+
+ // THEN
+ assertThat(set.size(), is(3));
+
+ assertTrue(set.contains("element1"));
+ assertTrue(set.contains("second-elem"));
+ assertTrue(set.contains("3rd"));
+ }
+
+ @Test
+ public void explodeSetEmptyElemsTest() {
+ // GIVEN
+ String serializedSet = ",,,,real,,,another,,,";
+
+ // WHEN
+ Set set = WearUtil.explodeSet(serializedSet, ",");
+
+ // THEN
+ assertThat(set.size(), is(2));
+
+ assertThat(true, is(set.contains("real")));
+ assertThat(true, is(set.contains("another")));
+ }
+
+ @Test
+ public void joinExplodeStabilityTest() {
+ // GIVEN
+ Set refSet = new HashSet<>();
+ refSet.add("element1");
+ refSet.add("second-elem");
+ refSet.add("3rd");
+ refSet.add("czwarty");
+ refSet.add("V");
+ refSet.add("6");
+
+ // WHEN
+ String joinedSet = WearUtil.joinSet(refSet, "#");
+ final Set explodedSet = WearUtil.explodeSet(joinedSet, "#");
+
+ // THEN
+ assertThat(explodedSet, is(refSet));
+ }
+
+ @Test
+ public void threadSleepTest() {
+ // GIVEN
+ final long testStart = System.currentTimeMillis();
+ final long requestedSleepDuration = 85L;
+ final long measuringMargin = 100L;
+
+ // WHEN
+ WearUtil.threadSleep(requestedSleepDuration);
+ final long measuredSleepDuration = System.currentTimeMillis() - testStart;
+
+ // THEN
+ // we cannot guarantee to be exact to the millisecond - we add some margin of error
+ assertThat(measuredSleepDuration, is(both(greaterThan(60L)).and(lessThan(requestedSleepDuration+measuringMargin))));
+ }
+
+ @Test
+ public void rateLimitTest() {
+ // WHEN
+ final boolean firstCall = WearUtil.isBelowRateLimit("test-limit", 3);
+ final boolean callAfterward = WearUtil.isBelowRateLimit("test-limit", 3);
+ WearUtilMocker.progressClock(500L);
+ final boolean callTooSoon = WearUtil.isBelowRateLimit("test-limit", 3);
+ WearUtilMocker.progressClock(3100L);
+ final boolean callAfterRateLimit = WearUtil.isBelowRateLimit("test-limit", 3);
+
+ // THEN
+ assertTrue(firstCall);
+ assertFalse(callAfterward);
+ assertFalse(callTooSoon);
+ assertTrue(callAfterRateLimit);
+ }
+
+ /**
+ * It tests if mock for bundleToDataMap is sane,
+ * because original impl. of bundleToDataMap
+ * uses DataMap.fromBundle which need Android SDK runtime
+ */
+ @Test
+ public void bundleToDataMapTest() throws Exception {
+ // GIVEN
+ DataMap refMap = new DataMap();
+ refMap.putString("ala", "ma kota");
+ refMap.putInt("why", 42);
+ refMap.putFloatArray("list", new float[]{0.45f, 3.2f, 6.8f});
+
+ // WHEN
+ WearUtilMocker.prepareMockNoReal();
+ Bundle bundle = BundleMock.mock(refMap);
+ DataMap gotMap = WearUtil.bundleToDataMap(bundle);
+
+ // THEN
+ assertThat(gotMap, is(refMap));
+ }
+
+
+}
\ No newline at end of file
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java
new file mode 100644
index 0000000000..7684d169f1
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AAPSMocker.java
@@ -0,0 +1,58 @@
+package info.nightscout.androidaps.testing.mockers;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+
+import org.junit.Assert;
+import org.mockito.ArgumentMatchers;
+import org.mockito.invocation.InvocationOnMock;
+import org.powermock.api.mockito.PowerMockito;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import info.nightscout.androidaps.aaps;
+import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock;
+
+import static org.mockito.Mockito.mock;
+import static org.powermock.api.mockito.PowerMockito.mockStatic;
+
+public class AAPSMocker {
+
+ private static final Map mockedSharedPrefs = new HashMap<>();
+ private static boolean unicodeComplicationsOn = true;
+
+ public static void prepareMock() throws Exception {
+ Context mockedContext = mock(Context.class);
+ mockStatic(aaps.class, InvocationOnMock::callRealMethod);
+
+ PowerMockito.when(aaps.class, "getAppContext").thenReturn(mockedContext);
+ PowerMockito.when(mockedContext, "getSharedPreferences", ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()).thenAnswer(invocation -> {
+
+ final String key = invocation.getArgument(0);
+ if (mockedSharedPrefs.containsKey(key)) {
+ return mockedSharedPrefs.get(key);
+ } else {
+ SharedPreferencesMock newPrefs = new SharedPreferencesMock();
+ mockedSharedPrefs.put(key, newPrefs);
+ return newPrefs;
+ }
+ });
+ PowerMockito.when(aaps.class, "areComplicationsUnicode").thenAnswer(invocation -> unicodeComplicationsOn);
+
+ setMockedUnicodeComplicationsOn(true);
+ resetMockedSharedPrefs();
+ }
+
+ public static void resetMockedSharedPrefs() {
+ mockedSharedPrefs.clear();
+ }
+
+ public static void resetMockedSharedPrefs(String forKey) {
+ mockedSharedPrefs.remove(forKey);
+ }
+
+ public static void setMockedUnicodeComplicationsOn(boolean setUnicodeOn) {
+ unicodeComplicationsOn = setUnicodeOn;
+ }
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AndroidMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AndroidMocker.java
new file mode 100644
index 0000000000..a1addfdc1d
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/AndroidMocker.java
@@ -0,0 +1,36 @@
+package info.nightscout.androidaps.testing.mockers;
+
+import org.junit.Assert;
+import org.powermock.api.mockito.PowerMockito;
+
+import java.util.Base64;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.powermock.api.mockito.PowerMockito.mockStatic;
+
+public class AndroidMocker {
+
+ public static void mockBase64() throws Exception {
+ mockStatic(android.util.Base64.class);
+
+ PowerMockito.when(android.util.Base64.class, "decode", anyString(), anyInt()).thenAnswer(invocation -> {
+
+ final String payload = invocation.getArgument(0);
+ try {
+ return Base64.getDecoder().decode(payload);
+ } catch (java.lang.IllegalArgumentException ex) {
+ return null;
+ }
+ });
+
+ PowerMockito.when(android.util.Base64.class, "encodeToString", any(), anyInt()).thenAnswer(invocation -> {
+
+ final byte[] payload = invocation.getArgument(0);
+ return Base64.getEncoder().encodeToString(payload);
+
+ });
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/LogMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/LogMocker.java
new file mode 100644
index 0000000000..5c374665bc
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/LogMocker.java
@@ -0,0 +1,11 @@
+package info.nightscout.androidaps.testing.mockers;
+
+import android.util.Log;
+
+import static org.powermock.api.mockito.PowerMockito.mockStatic;
+
+public class LogMocker {
+ public static void prepareMock() {
+ mockStatic(Log.class);
+ }
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java
new file mode 100644
index 0000000000..7d06f00c51
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java
@@ -0,0 +1,65 @@
+package info.nightscout.androidaps.testing.mockers;
+
+import info.nightscout.androidaps.data.RawDisplayData;
+import info.nightscout.androidaps.interaction.utils.SafeParse;
+
+import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.backInTime;
+
+public class RawDataMocker {
+
+ public static RawDisplayData rawSgv(String sgv, int m, String deltaString) {
+ RawDisplayData raw = new RawDisplayData();
+ raw.datetime = backInTime(0, 0, m, 0);
+ raw.sDelta = deltaString;
+ raw.sSgv = sgv;
+
+ double delta = SafeParse.stringToDouble(deltaString);
+
+ if (delta <= (-3.5 * 5)) {
+ raw.sDirection = "\u21ca";
+ } else if (delta <= (-2 * 5)) {
+ raw.sDirection = "\u2193";
+ } else if (delta <= (-1 * 5)) {
+ raw.sDirection = "\u2198";
+ } else if (delta <= (1 * 5)) {
+ raw.sDirection = "\u2192";
+ } else if (delta <= (2 * 5)) {
+ raw.sDirection = "\u2197";
+ } else if (delta <= (3.5 * 5)) {
+ raw.sDirection = "\u2191";
+ } else {
+ raw.sDirection = "\u21c8";
+ }
+
+ return raw;
+ }
+
+ public static RawDisplayData rawDelta(int m, String delta) {
+ RawDisplayData raw = new RawDisplayData();
+ raw.datetime = backInTime(0, 0, m, 0);
+ raw.sDelta = delta;
+ return raw;
+ }
+
+ public static RawDisplayData rawCobIobBr(String cob, String iob, String br) {
+ RawDisplayData raw = new RawDisplayData();
+ raw.sCOB2 = cob;
+ raw.sIOB1 = iob;
+ raw.sBasalRate = br;
+ return raw;
+ }
+
+ public static RawDisplayData rawIob(String iob, String iob2) {
+ RawDisplayData raw = new RawDisplayData();
+ raw.sIOB1 = iob;
+ raw.sIOB2 = iob2;
+ return raw;
+ }
+
+ public static RawDisplayData rawCob(String cob) {
+ RawDisplayData raw = new RawDisplayData();
+ raw.sCOB2 = cob;
+ return raw;
+ }
+
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java
new file mode 100644
index 0000000000..11a89f0699
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java
@@ -0,0 +1,98 @@
+package info.nightscout.androidaps.testing.mockers;
+
+import android.os.Bundle;
+
+import com.google.android.gms.wearable.Asset;
+import com.google.android.gms.wearable.DataMap;
+
+import org.junit.Assert;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.powermock.api.mockito.PowerMockito;
+
+import java.util.ArrayList;
+
+import info.nightscout.androidaps.interaction.utils.Constants;
+import info.nightscout.androidaps.interaction.utils.WearUtil;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.powermock.api.mockito.PowerMockito.mockStatic;
+
+public class WearUtilMocker {
+
+ public static final long REF_NOW = 1572610530000L;
+ private static long clockMsDiff = 0L;
+
+ public static void prepareMock() throws Exception {
+ resetClock();
+ mockStatic(WearUtil.class, InvocationOnMock::callRealMethod);
+
+ // because we cleverly used timestamp() by implementation, we can mock it
+ // and control the time in tests
+ PowerMockito.when(WearUtil.class, "timestamp").then(invocation -> (REF_NOW + clockMsDiff));
+ }
+
+ public static void prepareMockNoReal() throws Exception {
+ resetClock();
+ mockStatic(WearUtil.class);
+
+ PowerMockito.when(WearUtil.class, "timestamp").then(invocation -> REF_NOW + clockMsDiff);
+ PowerMockito.when(WearUtil.class, "getWakeLock", anyString(), anyInt()).then(invocation -> null);
+ PowerMockito.when(WearUtil.class, "bundleToDataMap", any(Bundle.class)).then(bundleToDataMapMock);
+ }
+
+ public static void resetClock() {
+ clockMsDiff = 0L;
+ }
+
+ public static void progressClock(long byMilliseconds) {
+ clockMsDiff = clockMsDiff + byMilliseconds;
+ }
+
+ public static void setClock(long atMillisecondsSinceEpoch) {
+ clockMsDiff = atMillisecondsSinceEpoch - REF_NOW;
+ }
+
+ public static long backInTime(int d, int h, int m, int s) {
+ return REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s);
+ }
+
+ private static Answer bundleToDataMapMock = invocation -> {
+ DataMap map = new DataMap();
+ Bundle bundle = invocation.getArgument(0);
+ for(String key: bundle.keySet()) {
+ Object v = bundle.get(key);
+ if (v instanceof Asset) map.putAsset(key, (Asset)v);
+ if (v instanceof Boolean) map.putBoolean(key, (Boolean)v);
+ if (v instanceof Byte) map.putByte(key, (Byte)v);
+ if (v instanceof byte[]) map.putByteArray(key, (byte[])v);
+ if (v instanceof DataMap) map.putDataMap(key, (DataMap)v);
+ if (v instanceof Double) map.putDouble(key, (Double)v);
+ if (v instanceof Float) map.putFloat(key, (Float)v);
+ if (v instanceof float[]) map.putFloatArray(key, (float[])v);
+ if (v instanceof Integer) map.putInt(key, (Integer)v);
+ if (v instanceof Long) map.putLong(key, (Long)v);
+ if (v instanceof long[]) map.putLongArray(key, (long[])v);
+ if (v instanceof String) map.putString(key, (String)v);
+ if (v instanceof String[]) map.putStringArray(key, (String[])v);
+
+ if (v instanceof ArrayList) {
+ if (!((ArrayList)v).isEmpty()) {
+ if (((ArrayList) v).get(0) instanceof Integer) {
+ map.putIntegerArrayList(key, (ArrayList)v);
+ }
+ if (((ArrayList) v).get(0) instanceof String) {
+ map.putStringArrayList(key, (ArrayList)v);
+ }
+ if (((ArrayList) v).get(0) instanceof DataMap) {
+ map.putDataMapArrayList(key, (ArrayList)v);
+ }
+ }
+ }
+ }
+
+ return map;
+ };
+}
diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/BundleMock.java b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/BundleMock.java
new file mode 100644
index 0000000000..24449dd352
--- /dev/null
+++ b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/BundleMock.java
@@ -0,0 +1,233 @@
+package info.nightscout.androidaps.testing.mocks;
+
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.SparseArray;
+
+import com.google.android.gms.wearable.DataMap;
+
+import org.mockito.Mockito;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyByte;
+import static org.mockito.Matchers.anyChar;
+import static org.mockito.Matchers.anyDouble;
+import static org.mockito.Matchers.anyFloat;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyLong;
+import static org.mockito.Matchers.anyShort;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.when;
+
+public final class BundleMock {
+
+ public static Bundle mock() {
+ return mock(new HashMap());
+ }
+
+ public static Bundle mock(DataMap dataMap) {
+ HashMap hm = new HashMap<>();
+ for (String key : dataMap.keySet()) {
+ hm.put(key, dataMap.get(key));
+ }
+ return mock(hm);
+ }
+
+ public static Bundle mock(final HashMap map) {
+
+ Answer unsupported = new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ throw new UnsupportedOperationException();
+ }
+ };
+ Answer put = new Answer() {
+ @Override
+ public Object answer(InvocationOnMock invocation) throws Throwable {
+ map.put((String)invocation.getArguments()[0], invocation.getArguments()[1]);
+ return null;
+ }
+ };
+ Answer