diff --git a/app/build.gradle b/app/build.gradle index 06c13ce5bd..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-i" + version "2.6-dev" buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' 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 9287921879..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; @@ -53,8 +52,8 @@ 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; @@ -70,8 +69,6 @@ public class MainActivity extends NoSplashAppCompatActivity { private static Logger log = LoggerFactory.getLogger(L.CORE); private CompositeDisposable disposable = new CompositeDisposable(); - protected PowerManager.WakeLock mWakeLock; - private ActionBarDrawerToggle actionBarDrawerToggle; private MenuItem pluginPreferencesMenuItem; @@ -81,7 +78,7 @@ public class MainActivity extends NoSplashAppCompatActivity { super.onCreate(savedInstanceState); Iconify.with(new FontAwesomeModule()); - LocaleHelper.onCreate(this, "en"); + LocaleHelper.INSTANCE.update(getApplicationContext()); setContentView(R.layout.activity_main); setSupportActionBar(findViewById(R.id.toolbar)); @@ -120,24 +117,6 @@ public class MainActivity extends NoSplashAppCompatActivity { VersionCheckerUtilsKt.triggerCheckVersion(); FabricPrivacy.setUserStats(); - } - - private void checkPluginPreferences(ViewPager viewPager) { - if (pluginPreferencesMenuItem == null) return; - if (((TabPageAdapter) viewPager.getAdapter()).getPluginAt(viewPager.getCurrentItem()).getPreferencesId() != -1) - pluginPreferencesMenuItem.setEnabled(true); - else pluginPreferencesMenuItem.setEnabled(false); - } - - @Override - public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { - super.onPostCreate(savedInstanceState, persistentState); - actionBarDrawerToggle.syncState(); - } - - @Override - protected void onResume() { - super.onResume(); setupTabs(); setupViews(); @@ -146,20 +125,14 @@ public class MainActivity extends NoSplashAppCompatActivity { .toObservable(EventRebuildTabs.class) .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> { - String lang = SP.getString(R.string.key_language, "en"); - LocaleHelper.setLocale(getApplicationContext(), lang); + LocaleHelper.INSTANCE.update(getApplicationContext()); if (event.getRecreate()) { recreate(); } else { setupTabs(); setupViews(); } - - 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); + setWakeLock(); }, FabricPrivacy::logException) ); disposable.add(RxBus.INSTANCE @@ -183,33 +156,36 @@ public class MainActivity extends NoSplashAppCompatActivity { } } - @Override - public void onDestroy() { - if (mWakeLock != null) - if (mWakeLock.isHeld()) - mWakeLock.release(); - super.onDestroy(); + private void checkPluginPreferences(ViewPager viewPager) { + if (pluginPreferencesMenuItem == null) return; + if (((TabPageAdapter) viewPager.getAdapter()).getPluginAt(viewPager.getCurrentItem()).getPreferencesId() != -1) + pluginPreferencesMenuItem.setEnabled(true); + else pluginPreferencesMenuItem.setEnabled(false); } @Override - public void onPause() { - super.onPause(); + public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { + super.onPostCreate(savedInstanceState, persistentState); + actionBarDrawerToggle.syncState(); + } + + @Override + public void onDestroy() { + super.onDestroy(); disposable.clear(); } + 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); + } + public void processPreferenceChange(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(); - } - } + if (ev.isChanged(R.string.key_keep_screen_on)) + setWakeLock(); } private void setupViews() { diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 89f08b908e..7899937a04 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -6,7 +6,6 @@ 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; @@ -36,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; @@ -49,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; @@ -89,9 +88,10 @@ 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 { @@ -125,6 +125,7 @@ public class MainApp extends Application { log.debug("onCreate"); sInstance = this; sResources = getResources(); + LocaleHelper.INSTANCE.update(this); sConstraintsChecker = new ConstraintChecker(); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); @@ -164,7 +165,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()); @@ -177,24 +178,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.INSTANCE); + if (!Config.NSCLIENT) pluginsList.add(SimpleProfilePlugin.getPlugin()); + if (!Config.NSCLIENT) pluginsList.add(LocalProfilePlugin.INSTANCE); 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()); @@ -204,7 +204,7 @@ public class MainApp extends Application { pluginsList.add(SourcePoctechPlugin.getPlugin()); pluginsList.add(SourceTomatoPlugin.getPlugin()); pluginsList.add(SourceEversensePlugin.getPlugin()); - if (Config.SMSCOMMUNICATORENABLED) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); + if (!Config.NSCLIENT) pluginsList.add(SmsCommunicatorPlugin.getPlugin()); pluginsList.add(FoodPlugin.getPlugin()); pluginsList.add(WearPlugin.initPlugin(this)); @@ -380,19 +380,6 @@ public class MainApp extends Application { return newList; } - @Nullable - public static T getSpecificPlugin(Class pluginClass) { - if (pluginsList != null) { - for (PluginBase p : pluginsList) { - if (pluginClass.isAssignableFrom(p.getClass())) - return (T) p; - } - } else { - log.error("pluginsList=null"); - } - return null; - } - public static boolean isEngineeringModeOrRelease() { if (!Config.APS) return true; 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 ed8cc40080..f8a5f3ed2a 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.java @@ -70,8 +70,6 @@ public class PreferencesActivity extends PreferenceActivity implements SharedPre public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { RxBus.INSTANCE.send(new EventPreferenceChange(key)); if (key.equals("language")) { - String lang = sharedPreferences.getString("language", "en"); - LocaleHelper.setLocale(getApplicationContext(), lang); RxBus.INSTANCE.send(new EventRebuildTabs(true)); //recreate() does not update language so better close settings finish(); 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 eed8c697e0..24cdceada6 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -536,11 +536,11 @@ public class TDDStatsActivity extends NoSplashActivity { 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/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index eefeebd0be..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 @@ -50,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; @@ -645,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); } } }); @@ -654,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); } } }); @@ -665,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); } } }); @@ -679,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/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index cd6e6dff4c..aafd877672 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -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.fetch() + if (objectives_fake.isChecked) { + objective.accomplishedOn = DateUtil.now() + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else + SntpClient.ntpTime(object : SntpClient.Callback() { + override fun run() { + activity?.runOnUiThread { + holder.verify.visibility = View.VISIBLE + log.debug("NTP time: $time System time: ${DateUtil.now()}") + if (!networkConnected) { + ToastUtils.showToastInUiThread(context, R.string.notconnected) + } else if (success) { + if (objective.isCompleted(time)) { + objective.accomplishedOn = time + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else { + ToastUtils.showToastInUiThread(context, R.string.requirementnotmet) + } } else { - ToastUtils.showToastInUiThread(context, R.string.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.fetch() + if (objectives_fake.isChecked) { + objective.startedOn = DateUtil.now() + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else + SntpClient.ntpTime(object : SntpClient.Callback() { + override fun run() { + activity?.runOnUiThread { + holder.start.visibility = View.VISIBLE + log.debug("NTP time: $time System time: ${DateUtil.now()}") + if (!networkConnected) { + ToastUtils.showToastInUiThread(context, R.string.notconnected) + } else if (success) { + objective.startedOn = time + scrollToCurrentObjective() + startUpdateTimer() + RxBus.send(EventObjectivesUpdateGui()) + } else { + ToastUtils.showToastInUiThread(context, R.string.failedretrievetime) + } } } - } - }, NetworkChangeReceiver.isConnected()) + }, 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..ca3e1d3126 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -21,8 +21,8 @@ import java.util.* object ObjectivesPlugin : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .fragmentClass(ObjectivesFragment::class.qualifiedName) - .alwaysEnabled(!Config.NSCLIENT) - .showInList(!Config.NSCLIENT) + .alwaysEnabled(Config.APS) + .showInList(Config.APS) .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives)), ConstraintsInterface { 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 58d27308a5..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 @@ -199,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/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/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/food/FoodFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.java index 5e21b6efd7..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 @@ -122,8 +122,7 @@ public class FoodFragment extends Fragment { } }); - RecyclerViewAdapter adapter = new RecyclerViewAdapter(MainApp - .getSpecificPlugin(FoodPlugin.class).getService().getFoodData()); + RecyclerViewAdapter adapter = new RecyclerViewAdapter(FoodPlugin.getPlugin().getService().getFoodData()); recyclerView.setAdapter(adapter); loadData(); @@ -151,7 +150,7 @@ public class FoodFragment extends Fragment { } void loadData() { - unfiltered = MainApp.getSpecificPlugin(FoodPlugin.class).getService().getFoodData(); + unfiltered = FoodPlugin.getPlugin().getService().getFoodData(); } void fillCategories() { @@ -297,7 +296,7 @@ public class FoodFragment extends Fragment { 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/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 785fb1361b..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 @@ -265,10 +265,10 @@ public class NSClientService extends Service { nsAPIhashCode = Hashing.sha1().hashString(nsAPISecret, Charsets.UTF_8).toString(); RxBus.INSTANCE.send(new EventNSClientStatus("Initializing")); - if (!MainApp.getSpecificPlugin(NSClientPlugin.class).isAllowed()) { + if (!NSClientPlugin.getPlugin().isAllowed()) { RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "not allowed")); RxBus.INSTANCE.send(new EventNSClientStatus("Not allowed")); - } else if (MainApp.getSpecificPlugin(NSClientPlugin.class).paused) { + } else if (NSClientPlugin.getPlugin().paused) { RxBus.INSTANCE.send(new EventNSClientNewLog("NSCLIENT", "paused")); RxBus.INSTANCE.send(new EventNSClientStatus("Paused")); } else if (!nsEnabled) { @@ -386,7 +386,7 @@ public class NSClientService extends Service { } 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", ""); 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 bcb8a61ddd..5c2a7cac84 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 @@ -1146,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) { 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 0ac9cbdafd..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 @@ -23,7 +23,7 @@ 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; @@ -101,10 +101,10 @@ public class BolusProgressDialog extends DialogFragment implements View.OnClickL .subscribe(event -> statusView.setText(event.getStatus()), FabricPrivacy::logException) ); disposable.add(RxBus.INSTANCE - .toObservable(EventDismissBolusprogressIfRunning.class) + .toObservable(EventDismissBolusProgressIfRunning.class) .observeOn(AndroidSchedulers.mainThread()) .subscribe(event -> { - if (L.isEnabled(L.UI)) log.debug("EventDismissBolusprogressIfRunning"); + if (L.isEnabled(L.UI)) log.debug("EventDismissBolusProgressIfRunning"); if (BolusProgressDialog.running) dismiss(); }, FabricPrivacy::logException) ); 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 9471747d7c..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 @@ -30,6 +30,7 @@ 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) @@ -69,10 +70,10 @@ class WizardDialog : DialogFragment() { 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?, @@ -94,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,10 +132,13 @@ class WizardDialog : DialogFragment() { treatments_wizard_bgtrendcheckbox.setOnCheckedChangeListener { buttonView, _ -> onCheckedChanged(buttonView) } treatments_wizard_sbcheckbox.setOnCheckedChangeListener { buttonView, _ -> onCheckedChanged(buttonView) } - treatments_wizard_delimiter.visibility = View.GONE - treatments_wizard_resulttable.visibility = View.GONE + 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 } @@ -168,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) @@ -220,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 @@ -263,29 +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) - val c_correction = SafeParse.stringToDouble(treatments_wizard_correctioninput.text) - 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, c_correction, + 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 = String.format(MainApp.gs(R.string.format_bg_isf), BgReading().value(Profile.toMgdl(c_bg, specificProfile.units)).valueToUnitsToString(specificProfile.units), 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 = String.format(MainApp.gs(R.string.format_carbs_ic), c_carbs.toDouble(), 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 = String.format(MainApp.gs(R.string.format_cob_ic), c_cob, 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 similarity index 68% rename from app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusprogressIfRunning.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventDismissBolusProgressIfRunning.kt index 94482729b6..53ab699d9c 100644 --- 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 @@ -3,4 +3,4 @@ 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 +class EventDismissBolusProgressIfRunning(val result: PumpEnactResult?) : Event() \ 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 index b10a0b5ed0..264d7c3e52 100644 --- 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 @@ -310,8 +310,8 @@ public class SmsCommunicatorPlugin extends PluginBase { switch (splitted[1].toUpperCase()) { case "DISABLE": case "STOP": - LoopPlugin loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); - if (loopPlugin != null && loopPlugin.isEnabled(PluginType.LOOP)) { + LoopPlugin loopPlugin = LoopPlugin.getPlugin(); + if (loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, false); ConfigBuilderPlugin.getPlugin().getCommandQueue().cancelTempBasal(true, new Callback() { @Override @@ -329,8 +329,8 @@ public class SmsCommunicatorPlugin extends PluginBase { break; case "ENABLE": case "START": - loopPlugin = MainApp.getSpecificPlugin(LoopPlugin.class); - if (loopPlugin != null && !loopPlugin.isEnabled(PluginType.LOOP)) { + loopPlugin = LoopPlugin.getPlugin(); + if (!loopPlugin.isEnabled(PluginType.LOOP)) { loopPlugin.setPluginEnabled(PluginType.LOOP, true); sendSMS(new Sms(receivedSms.phoneNumber, R.string.smscommunicator_loophasbeenenabled)); RxBus.INSTANCE.send(new EventRefreshOverview("SMS_LOOP_START")); @@ -340,18 +340,16 @@ public class SmsCommunicatorPlugin extends PluginBase { 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)); + loopPlugin = LoopPlugin.getPlugin(); + 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": 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 f60484cb80..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 @@ -18,7 +18,7 @@ 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; @@ -139,7 +139,7 @@ public class WearPlugin extends PluginBase { }, FabricPrivacy::logException )); disposable.add(RxBus.INSTANCE - .toObservable(EventDismissBolusprogressIfRunning.class) + .toObservable(EventDismissBolusProgressIfRunning.class) .observeOn(Schedulers.io()) .subscribe(event -> { if (event.getResult() == null) return; 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 0cd725b5f5..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 @@ -164,7 +164,8 @@ public class IobCobCalculatorPlugin extends PluginBase { 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_openapsama_autosens_min) || + event.isChanged(R.string.key_insulin_oref_peak) ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { 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 6544b1b0b4..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 @@ -34,6 +34,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB 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; @@ -415,6 +416,9 @@ public abstract class PumpPluginAbstract extends PluginBase implements PumpInter // 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); 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/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/activities/DanaRUserOptionsActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.java index 23520f3491..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 @@ -51,9 +51,9 @@ 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 synchronized void onResume() { 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/MsgInitConnStatusTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.java index 516f1f0ff8..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 @@ -31,19 +31,19 @@ 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"); 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 f3243b827a..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 @@ -35,17 +35,17 @@ 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"); 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 e7696836ac..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 @@ -249,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; 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 ad82f41cfe..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 @@ -45,19 +45,19 @@ 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"); @@ -72,15 +72,15 @@ 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"); 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 7c2cc7ede5..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 @@ -471,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; 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/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index 00cda7feca..1eed440cdc 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; @@ -46,6 +50,7 @@ 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.TreatmentsPlugin; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.SP; @@ -59,6 +64,7 @@ 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 { @@ -77,6 +83,13 @@ public class MedtronicHistoryData { 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<>(); @@ -311,6 +324,7 @@ public class MedtronicHistoryData { pumpHistoryEntryType == PumpHistoryEntryType.BasalProfileStart || // pumpHistoryEntryType == PumpHistoryEntryType.Bolus || // pumpHistoryEntryType == PumpHistoryEntryType.Resume || // + pumpHistoryEntryType == PumpHistoryEntryType.BatteryChange || // pumpHistoryEntryType == PumpHistoryEntryType.Prime); if (isLogEnabled()) @@ -353,6 +367,7 @@ public class MedtronicHistoryData { PumpHistoryEntryType.Resume, // PumpHistoryEntryType.Rewind, // PumpHistoryEntryType.NoDeliveryAlarm, // + PumpHistoryEntryType.BatteryChange, // PumpHistoryEntryType.BasalProfileStart); newAndAll2 = filterPumpSuspend(newAndAll2, 10); @@ -382,6 +397,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 +485,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) { + e.printStackTrace(); + } + } + + private void processTDDs(List tddsIn) { List tdds = filterTDDs(tddsIn); @@ -517,23 +591,32 @@ public class MedtronicHistoryData { long oldestTimestamp = getOldestTimestamp(entryList); + Gson gson = MedtronicUtil.getGsonInstance(); + List 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), + gson.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), + gson.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 +625,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 +766,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 entriesFromHistory) { @@ -695,9 +779,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 +825,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 +836,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)); } } } @@ -785,6 +893,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 +907,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 +932,9 @@ public class MedtronicHistoryData { bolus.setLinkedObject(extendedBolus); + if (doubleBolusDebug) + LOG.debug("DoubleBolusDebug: addBolus(tretament==null): ExtendedBolus={}", extendedBolus); + TreatmentsPlugin.getPlugin().addToHistoryExtendedBolus(extendedBolus); if (isLogEnabled()) @@ -832,8 +948,15 @@ public class MedtronicHistoryData { } else { DetailedBolusInfo detailedBolusInfo = DetailedBolusInfoStorage.INSTANCE.findDetailedBolusInfo(treatment.date, bolusDTO.getDeliveredAmount()); + + if (doubleBolusDebug) + LOG.debug("DoubleBolusDebug: addBolus(tretament={}): Bolus={}, DetailedBolusInfo={}", treatment, bolusDTO, detailedBolusInfo); + if (detailedBolusInfo == null) { detailedBolusInfo = new DetailedBolusInfo(); + + if (doubleBolusDebug) + LOG.debug("DoubleBolusDebug: detailedBolusInfoCouldNotBeRetrived !"); } detailedBolusInfo.date = treatment.date; @@ -844,6 +967,9 @@ public class MedtronicHistoryData { addCarbsFromEstimate(detailedBolusInfo, bolus); + if (doubleBolusDebug) + LOG.debug("DoubleBolusDebug: addBolus(tretament!=null): DetailedBolusInfo(New)={}", detailedBolusInfo); + boolean newRecord = TreatmentsPlugin.getPlugin().addToHistoryTreatment(detailedBolusInfo, false); bolus.setLinkedObject(detailedBolusInfo); @@ -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/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/virtual/VirtualPumpFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java deleted file mode 100644 index 35e95d66b7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.java +++ /dev/null @@ -1,122 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.virtual; - - -import android.app.Activity; -import android.os.Bundle; -import android.os.Handler; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; - -import androidx.annotation.Nullable; -import androidx.fragment.app.Fragment; - -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.bus.RxBus; -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; -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; - - -public class VirtualPumpFragment extends Fragment { - private static Logger log = LoggerFactory.getLogger(VirtualPumpFragment.class); - private CompositeDisposable disposable = new CompositeDisposable(); - - 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 = () -> { - Activity activity = getActivity(); - if (activity != null) - activity.runOnUiThread(this::updateGui); - sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); - }; - sLoopHandler.postDelayed(sRefreshLoop, 60 * 1000L); - } - } - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - 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; - } - - @Override - public synchronized void onResume() { - super.onResume(); - disposable.add(RxBus.INSTANCE - .toObservable(EventVirtualPumpUpdateGui.class) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(event -> updateGui(), FabricPrivacy::logException) - ); - updateGui(); - } - - @Override - public synchronized void onPause() { - super.onPause(); - disposable.clear(); - } - - protected void updateGui() { - 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/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index 0af516678a..7123b6c96b 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 @@ -39,6 +39,7 @@ 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; @@ -249,10 +250,14 @@ 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); + createOrUpdateMedtronic(treatment, true); } else log.error("Date is null: " + treatment.toString()); } catch (JSONException e) { @@ -392,11 +397,18 @@ 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 (MedtronicHistoryData.doubleBolusDebug) + log.debug("DoubleBolusDebug: createOrUpdateMedtronic:: existingTreatment={}", treatment); + if (existingTreatment == null) { getDao().create(treatment); if (L.isEnabled(L.DATATREATMENTS)) @@ -407,6 +419,9 @@ public class TreatmentService extends OrmLiteBaseService { } else { 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); @@ -416,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); 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 881d14b9cd..28181da190 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 @@ -51,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; @@ -344,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.getGsonInstance().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.getGsonInstance().toJson(in5minback)); + return in5minback; } } @@ -623,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; @@ -637,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 @@ -645,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 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 18e98dc4f9..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; @@ -275,7 +275,7 @@ public class CommandQueue { public synchronized void cancelAllBoluses() { if (!isRunning(Command.CommandType.BOLUS)) { - RxBus.INSTANCE.send(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); 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 9676a04196..85823c2c30 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.java @@ -16,7 +16,7 @@ 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; @@ -68,7 +68,7 @@ public class QueueThread extends Thread { long secondsElapsed = (System.currentTimeMillis() - connectionStartTime) / 1000; if (!pump.isConnected() && secondsElapsed > Constants.PUMP_MAX_CONNECTION_TIME_IN_SECONDS) { - RxBus.INSTANCE.send(new EventDismissBolusprogressIfRunning(null)); + 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"); 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 f49a37612a..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,14 +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; @@ -34,7 +33,7 @@ public class CommandBolus extends Command { PumpEnactResult r = ConfigBuilderPlugin.getPlugin().getActivePump().deliverTreatment(detailedBolusInfo); BolusProgressDialog.bolusEnded = true; - RxBus.INSTANCE.send(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..62e14285eb 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.getPlugin(); + 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/NetworkChangeReceiver.java b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java index a920d13698..3f12d75fce 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/receivers/NetworkChangeReceiver.java @@ -24,6 +24,13 @@ public class NetworkChangeReceiver extends BroadcastReceiver { private static EventNetworkChange lastEvent = null; + public static final NetworkChangeReceiver instance = new NetworkChangeReceiver(); + + // TODO: Split NSClient into network state component that can be used by several plugins and logic for plugin + public static void fetch() { + new NetworkChangeReceiver().grabNetworkStatus(MainApp.instance().getApplicationContext()); + } + @Override public void onReceive(final Context context, final Intent intent) { EventNetworkChange event = grabNetworkStatus(context); @@ -72,11 +79,11 @@ public class NetworkChangeReceiver extends BroadcastReceiver { return lastEvent != null && lastEvent.getWifiConnected(); } - public static boolean isConnected() { + 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/setupwizard/SWDefinition.java b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java index 5ebfcefcbf..e67787ccfd 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.java @@ -91,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); }); 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 721978b291..e6a4831693 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.java @@ -51,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); 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/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:textColor="@color/colorCalculatorButton" /> @@ -55,7 +56,7 @@ android:textStyle="bold" /> @@ -85,7 +86,7 @@ android:textStyle="bold" /> @@ -116,7 +117,7 @@ android:textStyle="bold" /> @@ -146,7 +147,7 @@ android:textStyle="bold" /> diff --git a/app/src/main/res/values-af-rZA/strings.xml b/app/src/main/res/values-af-rZA/strings.xml index 1df78ea55f..ef13ded20b 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 veiligheid Maks toelaatbare Bolus [U] Maks Toelaatbare karbs [g] @@ -33,6 +32,7 @@ Mees onlangse algoritme vir gevorderde gebruikers Wys die huidige staat van jou lus en knoppies vir mees algemene optrede Toon \'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 Nightscout Definieer \'n profiel met net een tydblok. Pomp Integrasie met Accu-Chek Combo pompe, vereis dat ruffy geïnstalleer is @@ -214,7 +214,6 @@ TydelikeBasaal Verlengde Bolus Nightscout-weergawe: - Ontbreek Voorkeure uitgevoer Uitvoer instellings na Voer instellings in vanaf @@ -544,8 +543,6 @@ Wys status vlae op tuisskerm Drempel waarskuwings stoor vlak [U] Drempel kritieke stoor vlak [U] - Drempel waarskuwing battery vlak [%%] - Drempel kritieke battery vlak [%%] IAB KOB Firmware @@ -1336,6 +1333,27 @@ Verkry Tydelike Basale Stel Tydelike Basale Stel 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 teks Bolus beperking aangewend: %2$.2fU to %3$.2fU]]> %1$.0f / %2$d U + 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 index 9deb74ddec..a691b4bff0 100644 --- a/app/src/main/res/values-bg-rBG/objectives.xml +++ b/app/src/main/res/values-bg-rBG/objectives.xml @@ -41,7 +41,6 @@ Неправилен код Докажете знанията си Отговорете правилно на въпросите - Изключено до: %1$s Грешен отговор! Следващия неотговорен Код (request code): %1$s diff --git a/app/src/main/res/values-bg-rBG/strings.xml b/app/src/main/res/values-bg-rBG/strings.xml index 7d66bad159..ee3fcd4eea 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 @@ - Настройки на сигурността Максимален инсулин при болус [единици] Максимални въглехидрати [гр] @@ -216,7 +215,6 @@ Временен базал Удължен болус Nightscout версия: - Липсва Настройките са експортирани Експортирай настройките в Импорт на настройки от @@ -548,8 +546,6 @@ Показвай подробни статус светлини за канула, инсулин, сензор, резервоар и батерията на началния екран. Ниво за аларма за останал инсулин в резервоара [Е] Критично ниво на останал инсулин в резервоар [Е] - Ниско ниво на батерията под [%%] - Критично ниво на батерията под [%%] IOB СОВ Фърмуер @@ -1368,6 +1364,7 @@ %1$s ISF: %2$.1f %1$.0fгр Чувств: %2$.1f %1$.1fгр Чувств: %2$.1f + %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 ee99a2bd3a..a65151aee8 100644 --- a/app/src/main/res/values-cs-rCZ/exam.xml +++ b/app/src/main/res/values-cs-rCZ/exam.xml @@ -163,4 +163,7 @@ K Vašemu lékaři Google Facebook + 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 index 69c2678c1a..518ea0965c 100644 --- a/app/src/main/res/values-cs-rCZ/objectives.xml +++ b/app/src/main/res/values-cs-rCZ/objectives.xml @@ -30,7 +30,7 @@ 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 + ...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 diff --git a/app/src/main/res/values-cs-rCZ/strings.xml b/app/src/main/res/values-cs-rCZ/strings.xml index 13c65531e5..1b72aaf6a5 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řeni Maximální povolený bolus [U] Maximální počet sacharidů [g] @@ -99,6 +98,7 @@ Profil Data o jídle Výsledek + Výsledek: %1$s %2$s Nedostupná data o glykémiích Změna nepožadována Požadavek @@ -216,7 +216,7 @@ Dočasný bazál Prodloužený bolus Verze Nightscoutu: - Chybí + Chybí %1$dg Nastavení exportováno Exportovat nastavení do Importovat nastavení z @@ -548,8 +548,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 [%] IOB COB Firmware @@ -988,7 +988,7 @@ Poslat logy e-mailem Smazat logy Oš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 m Nedostupná data o glykémiích Nastavení logování Obnovit výchozí @@ -1236,6 +1236,8 @@ Nevybráno (Jednoduché) Alkalické (Rozšířené) Lithiové (Rozšířené) + NiZn (Rozšířené) + Bolus/Ošetření ladění VYHLEDAT ZASTAVIT @@ -1369,6 +1371,10 @@ %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 9738d50527..7d83ac2db7 100644 --- a/app/src/main/res/values-de-rDE/exam.xml +++ b/app/src/main/res/values-de-rDE/exam.xml @@ -163,4 +163,7 @@ 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 index 57fb21fcf0..e92e116e1a 100644 --- a/app/src/main/res/values-de-rDE/objectives.xml +++ b/app/src/main/res/values-de-rDE/objectives.xml @@ -42,7 +42,7 @@ die Formel maxIOB = durchschnittlicher Essensbolus + 3 x höchste BasalrateCode ungültig Prüfe Dein Wissen Lies und beantworte die Fragen richtig - Beantwortung deaktiviert bis: %1$s + Frage gesperrt bis: %1$s Falsch! Nächste offene Code anfordern: %1$s diff --git a/app/src/main/res/values-de-rDE/strings.xml b/app/src/main/res/values-de-rDE/strings.xml index df441a07d4..b9f17dd119 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 Behandlungen Max. erlaubter Bolus [IE] Max. erlaubte Kohlenhydrate [g] @@ -99,6 +98,7 @@ Profil Mahlzeiten-Daten Ergebnis + Ergebnis: %1$s %2$s Keine BZ-Werte verfügbar Keine Anpassung benötigt Anfrage @@ -216,7 +216,7 @@ TBR Verzögerter Bolus Nightscout-Version: - Fehlend + Fehlend %1$dg Einstellungen exportiert Einstellungen exportieren nach Importiere Einstellungen von @@ -478,7 +478,7 @@ Passwort für die Einstellungen Einstellungen freischalten Tagesinsulin-Limit wird bald erreicht - Nighscout-Client + Nightscout-Client NSCl URL: Auto-Scrollen @@ -548,8 +548,8 @@ Erweiterte 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 [%] IOB COB Firmware @@ -1237,6 +1237,8 @@ Unerwartetes Verhalten. Nicht ausgewählt (Einfache Ansicht) Alkaline Batterie (erweiterte Ansicht) Lithium Batterie (erweiterte Ansicht) + Nickel-Zink-Akku (erweiterte Ansicht) + Fehlersuche Bolus/Behandlungen SCANNEN STOP @@ -1370,6 +1372,10 @@ Unerwartetes Verhalten. %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/strings.xml b/app/src/main/res/values-el-rGR/strings.xml index 81b47d6c80..e15480ce10 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] @@ -99,6 +98,7 @@ Προφίλ Δεδομένα Γεύματος Αποτέλεσμα + Αποτέλεσμα: %1$s %2$s Μη διαθέσιμα δεδομένα γλυκόζης Δεν απαιτείται αλλαγή Αίτημα @@ -216,7 +216,7 @@ Προσ Ρυθμός Εκτεταμμένο Bolus Έκδοση Nightscout: - Χαμένες + Λείπει %1$dg Επιλογές εξήχθησαν Εξαγωγή ρυθμίσεων σε Εισαγωγή ρυθμίσεων από @@ -548,8 +548,8 @@ Ενεργοποίηση του φωτισμού κατάστασης για cage, iage, sage, reservoir και επίπεδο μπαταρίας στην αρχική οθόνη. Όριο προειδοποίησης χαμηλής αμπούλας [U] Όριο προειδοποίησης πολύ χαμηλής αμπούλας [U] - Όριο προειδοποίησης χαμηλής μπαταρίας [%%] - Όριο προειδοποίησης πολύ χαμηλής μπαταρίας [%%] + Όριο προειδοποίησης χαμηλής μπαταρίας [%] + Όριο προειδοποίησης πολύ χαμηλής μπαταρίας [%] IOB COB Έκδοση @@ -1369,6 +1369,8 @@ %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 d6ab521b09..d0b8dce294 100644 --- a/app/src/main/res/values-es-rES/exam.xml +++ b/app/src/main/res/values-es-rES/exam.xml @@ -11,38 +11,58 @@ Tema: Hypo Temp-Objetivo ¿Cuál es la razón principal para establecer un hipo TT? Para evitar que BG caiga si ya hay basal temporal a cero corriendo. + 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. @@ -50,12 +70,15 @@ 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. @@ -63,19 +86,27 @@ 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? @@ -83,6 +114,7 @@ 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). @@ -92,10 +124,17 @@ 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 @@ -112,7 +151,12 @@ 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. diff --git a/app/src/main/res/values-es-rES/objectives.xml b/app/src/main/res/values-es-rES/objectives.xml index 88c8ef2f76..6252812668 100644 --- a/app/src/main/res/values-es-rES/objectives.xml +++ b/app/src/main/res/values-es-rES/objectives.xml @@ -53,8 +53,16 @@ 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 b66b9b1916..7ff5910adf 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -5,9 +5,10 @@ - Seguridad tratamientos + Máximo Bolo permitido [U] Máximos carbohidratos permitidos [g] + Preferencias Actualizar los tratamientos desde NS Restablecer las bases de datos ¿Realmente quiere restablecer las bases de datos? @@ -97,6 +98,7 @@ Perfil Datos de comidas Resultado + Resultado: %1$s %2$ss No hay disponibles datos de glucosa Ninguna acción requerida Solicitud @@ -214,7 +216,7 @@ Basal Temporal Bolo extendido Nightscout versión: - Faltan + Falta %1$dg Preferencias exportadas Exportar ajustes a Importar configuración de @@ -546,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 [%] IOB COB Firmware @@ -1364,4 +1366,11 @@ Cerrar 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 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 b497caaf1a..c908bb5b59 100644 --- a/app/src/main/res/values-fr-rFR/exam.xml +++ b/app/src/main/res/values-fr-rFR/exam.xml @@ -163,4 +163,7 @@ 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/strings.xml b/app/src/main/res/values-fr-rFR/strings.xml index 57cbe86793..df7a45cd62 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 traitements Maximum Bolus autorisé [U] Maximum de Glucides autorisé [g] @@ -59,7 +58,7 @@ Commander à distance AndroidAPS en utilisant les commandes SMS. Unités DAI - G:I (Ratio Glucides/Insuline, g/U) + G/I (g/U) SI Sensibilité Insuline Basal Cible @@ -99,6 +98,7 @@ Profil Données repas Résultats + Résultat: %1$s %2$s Pas de données glycémiques disponibles Pas de changement demandé Requête @@ -216,7 +216,7 @@ Basal Temporaire Bolus étendu Version Nightscout : - Manque + Manquant %1$dg Préférences exportées Exporter les paramètres au Importer les paramètres depuis @@ -271,7 +271,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Doigt Capteur Manuel - Cible temporaire + Cible temp. Annulation Cible Temporaire Paramètres du profil DanaR Durée d\'Action [h] @@ -426,13 +426,13 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S ACT CONF BOUCLE - SP + P.S. OAPS - LP + P.L. DANA ACCUEIL POMPEV - PROFIL NS + P.NS TRAIT CP OBJ @@ -549,8 +549,8 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Activer les lumières d\'état prolongées 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 [%] IA GA Firmware @@ -772,13 +772,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 bolus Erreur administration bolus étendu - Vue + AC-I passé(e)s %1$.2f h Activer en permanence les SMB Activer 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 G5 Activer 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 G5 Activer SMB avec les glucides Activer SMB tant que des Glucides sont actifs. Activer SMB avec les cibles temporaires @@ -1237,6 +1237,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/Traitements SCANNER ARRÊT @@ -1353,7 +1355,7 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S Envoyer SMS : %1$s Envoyer SMS à tous les numéros dans les préférences Envoyer SMS avec du texte - %2$+.2fU]]> + %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 @@ -1370,6 +1372,10 @@ L\'ENSEMBLE DES RISQUES LIÉS À LA QUALITÉ ET À LA PERFORMANCE DU PROGRAMME S %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/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/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 feb9844caf..5240fa0c8f 100644 --- a/app/src/main/res/values-it-rIT/exam.xml +++ b/app/src/main/res/values-it-rIT/exam.xml @@ -163,4 +163,7 @@ 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/strings.xml b/app/src/main/res/values-it-rIT/strings.xml index a4574176ef..49c7dcab6b 100644 --- a/app/src/main/res/values-it-rIT/strings.xml +++ b/app/src/main/res/values-it-rIT/strings.xml @@ -5,7 +5,6 @@ - Sicurezza trattamenti Max bolo consentito [U] Max carboidrati consentiti [g] @@ -99,6 +98,7 @@ Profilo Dati pasto Esito + Risultato: %1$s %2$s Dati glicemia non disponibili Nessun cambiamento richiesto Richiesta @@ -216,7 +216,7 @@ Basale temporanea Bolo esteso Versione Nightscout: - Mancante + Mancanti %1$dg Preferenze esportate Esporta impostazioni su Importa impostazioni da @@ -548,8 +548,8 @@ 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 batteria a cui prestare attenzione [%] + Soglia livello batteria critico [%] IOB COB Firmware @@ -1236,6 +1236,8 @@ Non selezionato (Simple view) Alcalina (Extended view) Litio (Extended view) + NiZn (Extended view) + Debug Bolo/Trattamenti SCAN STOP @@ -1369,6 +1371,10 @@ %1$s ISF: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Bolus wizard min + %1$dg + On + Off 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/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/strings.xml b/app/src/main/res/values-ko-rKR/strings.xml index 614d3614f2..6fc3797b17 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] @@ -216,7 +215,6 @@ 임시Basal 확장 Bolus Nightscout 버전: - 누락 설정이 저장되었습니다 다음 위치에 설정을 저장하시겠습니까 다음 위치에서 설정을 불러오시겠습니까 @@ -546,8 +544,6 @@ 홈화면에 상태 표시등 보여주기 주사기량 경고 기준값[U] 주사기량 위험 기준값[U] - 배터리량 경고 기준값[%%] - 배터리량 위험 기준값[%%] IOB COB 펌웨어 diff --git a/app/src/main/res/values-lt-rLT/exam.xml b/app/src/main/res/values-lt-rLT/exam.xml index 2a3635343b..634982d1fc 100644 --- a/app/src/main/res/values-lt-rLT/exam.xml +++ b/app/src/main/res/values-lt-rLT/exam.xml @@ -163,4 +163,7 @@ Į 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/strings.xml b/app/src/main/res/values-lt-rLT/strings.xml index 8b47cc4a76..b857748b1a 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 saugumas Maksimalus leistinas bolusas [U] Maks. leistini angliavandeniai [g] @@ -65,7 +64,7 @@ Tikslas Nenustatytas profilis Insulinas: - Angliavandeniai: + AV: AIO: AIO: Visas AIO: @@ -76,10 +75,10 @@ AIO: Visas AIO: Insulinas - Angliavandeniai + AV KG LT - Angliavandeniai + AV Korekcija vv Bolusų AIO @@ -99,6 +98,7 @@ Profilis Maisto duomenys Rezultatas + Rezultatas: %1$s %2$s Nėra gliukozės duomenų Pakeitimai nereikalingi Užklausa @@ -158,7 +158,7 @@ Bolusas: Valandinė bazė Valandinė bazė: - Angliavandeniai + AV Pakeiskite įvestus duomenis! Nustatyti naują ištęstą bolusą: KG šaltinis @@ -216,7 +216,7 @@ Laikina bazė Ištęstas bolusas Nightscout versija: - Trūksta + Trūksta %1$dg Nustatymai eksportuoti Eksportuoti nustatymus Importuoti nustatymus iš @@ -341,7 +341,7 @@ Greitasis patarėjas Greitojo patarėjo nustatymai Mygtuko tekstas: - Angliavandeniai: + AV: Galioja: Pridėti Redaguoti @@ -548,8 +548,8 @@ 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 [%] AIO AAO Programinė įranga @@ -787,7 +787,7 @@ Paleisti laikinąją bazę Nutildyti Insulinas - Angliavandeniai + AV Mygtukai Siunčia kalibravimą į xDrip+ arba atidaro G5 kalibravimo dialogą Atidaro xDrip+, o mygtukas ATGAL gražina į AAPS @@ -1369,6 +1369,8 @@ %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 44fb673ece..377eba5335 100644 --- a/app/src/main/res/values-nl-rNL/exam.xml +++ b/app/src/main/res/values-nl-rNL/exam.xml @@ -116,6 +116,7 @@ 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. @@ -130,4 +131,39 @@ 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% hoger. + 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 index cd10de8fdb..f605592027 100644 --- a/app/src/main/res/values-nl-rNL/objectives.xml +++ b/app/src/main/res/values-nl-rNL/objectives.xml @@ -51,4 +51,18 @@ 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 42e9885cfb..5822a1ccaa 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 veiligheid Max toegestane bolus [E] Max toegestane koolhydraten [g] @@ -99,6 +98,7 @@ Profiel Maaltijd gegevens Resultaat + Resultaat: %1$s %2$s Geen BG gegevens beschikbaar Geen aanpassing noodzakelijk Voorstel @@ -216,7 +216,7 @@ Tijdelijk basaal Vertraagde bolus Nightscout versie: - Te weinig + Ontbrekend %1$dg Voorkeuren geëxporteerd Exporteer instellingen naar Importeer instellingen van @@ -544,10 +544,12 @@ Activeer superbolus in de wizard Activeer 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 [%] IOB COB Firmware @@ -617,6 +619,7 @@ Afbreken Niet 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 & FEEDBACK KOOLHYDRATEN & BOLUS @@ -1271,6 +1274,7 @@ Niet gestart RileyLink initialiseren… RileyLink fout + Tuning van RileyLink en Pomp Probleem tijdens verbinden met de pomp Verbonden @@ -1340,6 +1344,15 @@ Ophalen Tijdelijke Basaal Instellen Tijdelijke Basaal Instellen 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 @@ -1347,4 +1360,17 @@ 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 + 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 diff --git a/app/src/main/res/values-pl-rPL/exam.xml b/app/src/main/res/values-pl-rPL/exam.xml index c7f3d95422..cf6cb932dc 100644 --- a/app/src/main/res/values-pl-rPL/exam.xml +++ b/app/src/main/res/values-pl-rPL/exam.xml @@ -31,6 +31,56 @@ 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 @@ -81,4 +131,39 @@ 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 index 49da1c2fb9..17777caf68 100644 --- a/app/src/main/res/values-pl-rPL/objectives.xml +++ b/app/src/main/res/values-pl-rPL/objectives.xml @@ -1,6 +1,24 @@ + 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 @@ -41,4 +59,16 @@ %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 71562a31d9..12c2770669 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 leczenia Maks. dopuszczalny bolus [U] Maks. dopuszczalne węglowodany [g] @@ -99,6 +98,7 @@ Profil Dane posiłku Rezultat + Wynik: %1$s %2$s Brak danych o glukozie Zmiana nie wymagana Żądanie @@ -216,7 +216,7 @@ BazaTymczasowa Bolus Przedłużony Wersja Nightscout: - Brakujące + Brakuje %1$dg Właściwości wyeksportowane Eksportuj ustawienia do Importuj ustawienia z @@ -548,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 [%] IOB COB Firmware @@ -1370,6 +1370,8 @@ %1$s ISF: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Kalkulator bolusa min + %1$dg diff --git a/app/src/main/res/values-pt-rBR/exam.xml b/app/src/main/res/values-pt-rBR/exam.xml index 5c459d43f5..6ca2e5ae4f 100644 --- a/app/src/main/res/values-pt-rBR/exam.xml +++ b/app/src/main/res/values-pt-rBR/exam.xml @@ -6,44 +6,63 @@ 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. @@ -67,6 +86,7 @@ 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. @@ -74,14 +94,19 @@ 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? @@ -99,30 +124,46 @@ 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 index 263e029951..c2c6db7b39 100644 --- a/app/src/main/res/values-pt-rBR/objectives.xml +++ b/app/src/main/res/values-pt-rBR/objectives.xml @@ -16,6 +16,12 @@ 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 @@ -24,13 +30,18 @@ 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 + Insira o código obtido dos programadores para ignorar o resto dos objectivos Código aceite Código inválido Prove seu conhecimento Estude e responda as perguntas correctamente - A resposta está desactivada para: %1$s + Responder desactivado até: %1$s Resposta errada! Próximo inacabado Pedir Código: %1$s diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 5068a68e02..68993b7a55 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 Tratamento Máximo bolus permitido [U] Máximo de carbs permitidos [g] @@ -99,6 +98,7 @@ Perfil Dados de refeição Resultado + Resultado: %1$s %2$ss Sem dados de glicose disponíveis Nenhuma alteração solicitada Solicitar @@ -216,7 +216,7 @@ Basal Temporária Bólus estendido Versão do Nightscout: - Faltando + Falta %1$dg Preferências exportadas Exportar configurações para Importar configurações de @@ -548,8 +548,8 @@ 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 [%] IOB COB Firmware @@ -1348,6 +1348,7 @@ 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 @@ -1368,6 +1369,8 @@ %1$s FSI: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Assistente de Bólus min + %1$dg diff --git a/app/src/main/res/values-pt-rPT/exam.xml b/app/src/main/res/values-pt-rPT/exam.xml index 15a55316bb..9ad55b2946 100644 --- a/app/src/main/res/values-pt-rPT/exam.xml +++ b/app/src/main/res/values-pt-rPT/exam.xml @@ -6,38 +6,63 @@ 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. @@ -69,41 +94,76 @@ 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 index 1e689ce9e0..727c115853 100644 --- a/app/src/main/res/values-pt-rPT/objectives.xml +++ b/app/src/main/res/values-pt-rPT/objectives.xml @@ -7,7 +7,21 @@ %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 @@ -16,13 +30,18 @@ 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 + Insira o código obtido dos programadores para ignorar o resto dos objectivos Código aceite Código inválido Prove seu conhecimento Estude e responda as perguntas correctamente - A resposta está desactivada para: %1$s + Responder desactivado até: %1$s Resposta errada! Próximo inacabado Pedir Código: %1$s diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index fc2b1e0ddb..e186080045 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 tratamentos Max bolus permitido [U] Max hidratos permitidos [g] @@ -99,6 +98,7 @@ Perfil Dados de refeição Resultado + Resultado: %1$s %2$ss Sem dados de glucose disponíveis Nenhuma alteração solicitada Pedido @@ -216,7 +216,7 @@ BasalTemp Bólus estendido Versão Nightscout: - Em falta + Falta %1$dg Preferências exportadas Exportar configurações para Importar configurações de @@ -296,7 +296,7 @@ Insulina diária Erros Glicose - Reabastecimento + Recarregar Suspender A ligar durante %1$d s Senha da bomba @@ -548,8 +548,8 @@ 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 [%] IOB COB Firmware @@ -1236,6 +1236,8 @@ Não seleccionado (Visão simples) Alcalina (Visão estendida) Lithium (visão estendida) + NiZn (Vista Estendida) + Depuração de Bólus/Tratamentos PROCURAR PARAR @@ -1369,6 +1371,10 @@ %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 index e65aa9b15d..76613910c2 100644 --- a/app/src/main/res/values-ro-rRO/objectives.xml +++ b/app/src/main/res/values-ro-rRO/objectives.xml @@ -41,7 +41,6 @@ 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ă Solicită codul: %1$s diff --git a/app/src/main/res/values-ro-rRO/strings.xml b/app/src/main/res/values-ro-rRO/strings.xml index afb70957fc..38d793ffcb 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ță tratament Bolus maxim admis [U] Carbohidrați admiși maxim [g] @@ -216,7 +215,7 @@ Bazală temporară Bolus extins Versiune Nightscout: - Lipsă + Lipsă %1$dg Am exportat preferințele Exportă setările către Importă setările din @@ -548,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 [%%] IOB COB Firmware @@ -1346,6 +1343,12 @@ 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ă !!!!!]]> @@ -1359,4 +1362,12 @@ Între Închide 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 3faaeef1f9..cccb9912e5 100644 --- a/app/src/main/res/values-ru-rRU/exam.xml +++ b/app/src/main/res/values-ru-rRU/exam.xml @@ -165,4 +165,7 @@ Context | Edit Context Ваши эндокринологи Google Facebook + Другие препараты + АА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 index 4541aeade9..ca1f3159d9 100644 --- a/app/src/main/res/values-ru-rRU/objectives.xml +++ b/app/src/main/res/values-ru-rRU/objectives.xml @@ -41,7 +41,7 @@ Неверный код Подтвердите ваши знания Изучите вопросы и дайте точные ответы - Рассмотрение ответов приостановлено на: %1$s + Ответы отключены до: %1$s Неверный ответ! Следующий незавершенный Код запроса: %1$s diff --git a/app/src/main/res/values-ru-rRU/strings.xml b/app/src/main/res/values-ru-rRU/strings.xml index a01225fd0f..de60ad8813 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] ед. макс разрешенные углеводы (г) @@ -99,6 +98,7 @@ профиль данные приема пищи результат + Результат: %1$s %2$s данные гликемии недоступны изменения не запрошены запрос @@ -216,7 +216,7 @@ ВремБазал расширенный болюс версия Nightscout: - отсутствует + Отсутствует %1$dg настройки экспортированы экспортировать настройки в импортировать настройки из @@ -548,8 +548,8 @@ Включить на главном экране подробные индикаторы отработанного времени для канюли помпы, инсулина, сенсора, резервуара, а также уровня заряда батареи. Порог уровня наполненности резервуара для оповещения [ед.] Порог критического уровня наполненности резервуара [U] - Порог предупреждения о разрядке батареи [%%] - Порог предупреждения о критическом уровне разрядки батареи [%%] + Порог предупреждения о разрядке батареи [%] + Порог предупреждения о критическом уровне разрядки батареи [%] IOB акт инс акт углев прошивка @@ -1371,6 +1371,8 @@ Context | Edit Context %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 86c7eb0ef1..6bc806f51d 100644 --- a/app/src/main/res/values-sk-rSK/exam.xml +++ b/app/src/main/res/values-sk-rSK/exam.xml @@ -163,4 +163,7 @@ 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/strings.xml b/app/src/main/res/values-sk-rSK/strings.xml index efa73d3e06..9181d43ee7 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šetrenia Maximálny povolený bolus [JI] Maximálne povolené množstvo sacharidov [g] @@ -99,6 +98,7 @@ Profil Dáta o jedle Výsledok + Výsledok: %1$s %2$s Nedostupné dáta o glykémiách Nepožadovaná žiadna zmena Požiadavka @@ -115,12 +115,12 @@ NS Profil Jednoduchý profil DočasnýBazál - Ošetrenie + Ošetrenia Virtuálna pumpa Starostlivosť Pumpa Akú pumpu chcete používať s AndroidAPS? - Ošetrenie + Ošetrenia Aký modul chcete používať pre spracovanie ošetrení? Profil Aký profil má používať AndroidAPS? @@ -216,7 +216,7 @@ Dočasný bazál Predĺžený bolus Verzia Nightscoutu: - Chýba + Chýba %1$dg Nastavenie exportované Exportovať nastavenia do Importovať nastavenia z @@ -548,8 +548,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 [%] IOB COB Firmware @@ -1236,6 +1236,7 @@ Nevybrané (jednoduché zobrazenie) Alkalické (rozšírené zobrazenie) Líthiové (rozšírené zobrazenie) + NiZn (Rozšírené) VYHĽADAŤ ZASTAVIŤ @@ -1369,6 +1370,8 @@ %1$s ISF: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Bolusová kalkulačka min + %1$dg diff --git a/app/src/main/res/values-sv-rSE/exam.xml b/app/src/main/res/values-sv-rSE/exam.xml index b133650cd9..6c67f14c63 100644 --- a/app/src/main/res/values-sv-rSE/exam.xml +++ b/app/src/main/res/values-sv-rSE/exam.xml @@ -163,4 +163,5 @@ Ditt diabetesteam Google Facebook + Annan medicinering diff --git a/app/src/main/res/values-sv-rSE/strings.xml b/app/src/main/res/values-sv-rSE/strings.xml index 5cee7655ff..66d5e0b734 100644 --- a/app/src/main/res/values-sv-rSE/strings.xml +++ b/app/src/main/res/values-sv-rSE/strings.xml @@ -5,7 +5,6 @@ - Säkerhetsbegränsningar för behandlingar Max tillåten bolus [E] Max tillåtna KH [g] @@ -100,6 +99,7 @@ Eversense-appen. Profil Måltidsdata Resultat + Resultat: %1$s %2$s Ingen BG-data tillänglig Ingen ändring behövs Beräknat behov @@ -217,7 +217,7 @@ Eversense-appen. Temp basal Förlängd bolus Nightscoutversion: - Saknas: + Saknar %1$dg Inställningar exporterade Exportera inställningar till Importera inställningar från @@ -549,8 +549,8 @@ Eversense-appen. Aktivera 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 [%] IOB COB Firmwareversion @@ -591,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 + Pump OpenAPS Uppladdare Känslighetsavkänning @@ -1370,6 +1370,8 @@ Eversense-appen. %1$s ISF: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Kalkylator min + %1$dg diff --git a/app/src/main/res/values-tr-rTR/strings.xml b/app/src/main/res/values-tr-rTR/strings.xml index d6ad5de6b1..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] @@ -210,7 +209,6 @@ Geçici Bazal Yayım Bolus Nightscout sürümü: - Eksik Tercihler dışa aktarıldı Ayarları aktar Ayarları içe aktar diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 25e94c4847..f256f77aa4 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] @@ -214,7 +213,6 @@ 临时基础 扩展大剂量 Nightscout 版本: - 缺少 参数选项导出了 导出配置 导入配置 @@ -542,8 +540,6 @@ 在主屏幕上显示状态指示灯 储药器药量低于阈值[U] 警告 储药器药量低于阈值[U] 严重警告 - 电池电量低于阈值[%%] 警告 - 电池电量低于阈值[%%] 严重警告 IOB活性胰岛素 COB活性碳水 固件 diff --git a/app/src/main/res/values/arrays.xml b/app/src/main/res/values/arrays.xml index 1184f37e54..0133d299e6 100644 --- a/app/src/main/res/values/arrays.xml +++ b/app/src/main/res/values/arrays.xml @@ -33,6 +33,7 @@ @string/ko_lang @string/lt_lang @string/pt_lang + @string/pt_BR_lang @string/ro_lang @string/ru_lang @string/sk_lang @@ -55,6 +56,7 @@ ko lt pt + pt_BR ro ru sk @@ -106,7 +108,7 @@ @string/use_gps_location - + PASSIVE NETWORK GPS @@ -158,7 +160,7 @@ @string/medtronic_pump_frequency_worldwide - + @string/key_medtronic_pump_frequency_us_ca @string/key_medtronic_pump_frequency_worldwide @@ -174,6 +176,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 @@ -183,12 +190,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 ae4fa99587..e9063fd2b1 100644 --- a/app/src/main/res/values/exam.xml +++ b/app/src/main/res/values/exam.xml @@ -162,5 +162,8 @@ Your diabetes team Google Facebook + 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..469db88006 100644 --- a/app/src/main/res/values/objectives.xml +++ b/app/src/main/res/values/objectives.xml @@ -52,7 +52,7 @@ Code invalid Prove your knowledge Study and answer questions correctly - Answering disabled to: %1$s + Answering disabled until: %1$s Wrong answer! Next unfinished Request code: %1$s diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 3570604990..5513d964f8 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -4,20 +4,20 @@ Afrikaans Bulgarian Dutch - + French German Greek - + Chinese - + Italian - + Korean Lithuanian Polish Portuguese - + Portuguese, Brazilian Romanian Russian Slovak @@ -121,6 +121,7 @@ Profile Meal data Result + Result: %1$s %2$s No glucose data available No change requested Request @@ -245,7 +246,7 @@ TempBasal Extended Bolus Nightscout version: - Missing + Missing %1$dg Preferences exported Export settings to Import settings from @@ -611,9 +612,9 @@ key_statuslights_res_critical Threshold 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 [%] IOB COB Firmware @@ -813,7 +814,7 @@ BG upload settings Show detailed delta Show delta with one more decimal place - 45 60 75 90 105 120 + SMB max minutes Max minutes of basal to limit SMB to Unsupported pump firmware Send BG data to xDrip+ @@ -1330,9 +1331,9 @@ Upload BG tests smbmaxminutes - 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 disabled internal storage constraint Free at least %1$d MB from internal storage! Loop disabled! Wrong format @@ -1423,6 +1424,7 @@ pref_medtronic_bolus_delay pref_medtronic_encoding pref_medtronic_battery_type + pref_medtronic_bolus_debug pref_rileylink_mac_address medtronic_pump_frequency_us_ca medtronic_pump_frequency_worldwide @@ -1431,6 +1433,7 @@ medtronic_pump_battery_no medtronic_pump_battery_alkaline medtronic_pump_battery_lithium + medtronic_pump_battery_nizn Pump Serial Number Pump Type @@ -1450,6 +1453,8 @@ Not selected (Simple view) Alkaline (Extended view) Lithium (Extended view) + NiZn (Extended view) + Bolus/Treatments Debugging SCAN @@ -1602,6 +1607,7 @@ %1$s ISF: %2$.1f %1$.0fg IC: %2$.1f %1$.1fg IC: %2$.1f + %1$d%% Bolus wizard min Profile name: @@ -1609,5 +1615,9 @@ Units units Do you want to switch profile and discard changes made to current profile? + 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" /> + + 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/smsCommunicator/SmsCommunicatorPluginTest.java b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPluginTest.java index f97a397e32..bc928ded85 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 @@ -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 { @@ -744,8 +744,9 @@ public class SmsCommunicatorPluginTest { smsCommunicatorPlugin = SmsCommunicatorPlugin.getPlugin(); 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); 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 1b9c937c24..0000000000 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/versionChecker/VersionCheckerUtilsKtTest.kt +++ /dev/null @@ -1,224 +0,0 @@ -package info.nightscout.androidaps.plugins.general.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 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 `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" - | 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(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) - } - -} \ No newline at end of file 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 486a98524d..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; @@ -22,13 +23,6 @@ import static org.junit.Assert.assertEquals; public class MsgInitConnStatusTimeTest { @Test public void runTest() { - AAPSMocker.mockMainApp(); - AAPSMocker.mockApplicationContext(); - AAPSMocker.mockSP(); - AAPSMocker.mockL(); - AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockCommandQueue(); - AAPSMocker.mockDanaRPlugin(); MsgInitConnStatusTime packet = new MsgInitConnStatusTime(); // test message decoding @@ -56,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/danaRv2/comm/MsgCheckValue_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgCheckValue_v2Test.java index e81c5416f1..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,17 +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.mockDanaRPlugin(); - AAPSMocker.mockConfigBuilder(); - AAPSMocker.mockCommandQueue(); Treatment t = new Treatment(); MsgCheckValue_v2 packet = new MsgCheckValue_v2(); // test message decoding @@ -55,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/MsgSetHistoryEntry_v2Test.java b/app/src/test/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgSetHistoryEntry_v2Test.java index 8413f296e1..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,15 +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.mockDanaRPlugin(); MsgSetHistoryEntry_v2 initializerTest = new MsgSetHistoryEntry_v2((byte) 1, System.currentTimeMillis(), 1, 0); MsgSetHistoryEntry_v2 packet = new MsgSetHistoryEntry_v2(); @@ -56,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 b354fe6d49..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,16 +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.mockDanaRPlugin(); - MsgStatusTempBasal_v2 packet = new MsgStatusTempBasal_v2(); DanaRPump pump = DanaRPump.getInstance(); // test message decoding @@ -57,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()); + } + } + + }