Merge branch 'dev' into omnipod_eros_dev_upstream_merge

This commit is contained in:
Bart Sopers 2020-12-14 23:36:06 +01:00
commit 7945a2d8bd
388 changed files with 2777 additions and 3712 deletions

View file

@ -120,7 +120,7 @@ android {
targetSdkVersion 28 targetSdkVersion 28
multiDexEnabled true multiDexEnabled true
versionCode 1500 versionCode 1500
version "2.7.1-dev" version "2.7.2-dev"
buildConfigField "String", "VERSION", '"' + version + '"' buildConfigField "String", "VERSION", '"' + version + '"'
buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"' buildConfigField "String", "BUILDVERSION", '"' + generateGitBuild() + '-' + generateDate() + '"'
buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"' buildConfigField "String", "REMOTE", '"' + generateGitRemote() + '"'
@ -135,6 +135,9 @@ android {
kotlinOptions { kotlinOptions {
jvmTarget = '1.8' jvmTarget = '1.8'
} }
buildFeatures {
viewBinding true
}
lintOptions { lintOptions {
checkReleaseBuilds false checkReleaseBuilds false
disable 'MissingTranslation' disable 'MissingTranslation'

View file

@ -28,9 +28,9 @@ import com.google.android.material.tabs.TabLayoutMediator
import com.joanzapata.iconify.Iconify import com.joanzapata.iconify.Iconify
import com.joanzapata.iconify.fonts.FontAwesomeModule import com.joanzapata.iconify.fonts.FontAwesomeModule
import dev.doubledot.doki.ui.DokiActivity import dev.doubledot.doki.ui.DokiActivity
import info.nightscout.androidaps.activities.ProfileHelperActivity
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.activities.ProfileHelperActivity
import info.nightscout.androidaps.activities.SingleFragmentActivity import info.nightscout.androidaps.activities.SingleFragmentActivity
import info.nightscout.androidaps.activities.StatsActivity import info.nightscout.androidaps.activities.StatsActivity
import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventAppExit
@ -71,6 +71,7 @@ import javax.inject.Inject
import kotlin.system.exitProcess import kotlin.system.exitProcess
class MainActivity : NoSplashAppCompatActivity() { class MainActivity : NoSplashAppCompatActivity() {
private val disposable = CompositeDisposable() private val disposable = CompositeDisposable()
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
@ -136,16 +137,17 @@ class MainActivity : NoSplashAppCompatActivity() {
if (it.recreate) recreate() if (it.recreate) recreate()
else setupViews() else setupViews()
setWakeLock() setWakeLock()
}, fabricPrivacy::logException ) }, fabricPrivacy::logException)
) )
disposable.add(rxBus disposable.add(rxBus
.toObservable(EventPreferenceChange::class.java) .toObservable(EventPreferenceChange::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ processPreferenceChange(it) }, fabricPrivacy::logException ) .subscribe({ processPreferenceChange(it) }, fabricPrivacy::logException)
) )
if (!sp.getBoolean(R.string.key_setupwizard_processed, false) && !isRunningRealPumpTest()) { if (!sp.getBoolean(R.string.key_setupwizard_processed, false) && !isRunningRealPumpTest()) {
val intent = Intent(this, SetupWizardActivity::class.java) protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, {
startActivity(intent) startActivity(Intent(this, SetupWizardActivity::class.java))
})
} }
androidPermission.notifyForStoragePermission(this) androidPermission.notifyForStoragePermission(this)
androidPermission.notifyForBatteryOptimizationPermission(this) androidPermission.notifyForBatteryOptimizationPermission(this)
@ -288,7 +290,9 @@ class MainActivity : NoSplashAppCompatActivity() {
} }
R.id.nav_setupwizard -> { R.id.nav_setupwizard -> {
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, {
startActivity(Intent(this, SetupWizardActivity::class.java)) startActivity(Intent(this, SetupWizardActivity::class.java))
})
return true return true
} }

View file

@ -7,9 +7,6 @@ import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.os.Bundle import android.os.Bundle
import androidx.annotation.XmlRes import androidx.annotation.XmlRes
import androidx.preference.* import androidx.preference.*
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection import dagger.android.support.AndroidSupportInjection
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
@ -58,7 +55,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject import javax.inject.Inject
class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener, HasAndroidInjector { class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener {
private var pluginId = -1 private var pluginId = -1
private var filter = "" private var filter = ""
@ -103,11 +100,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var nsSettingStatus: NSSettingsStatus @Inject lateinit var nsSettingStatus: NSSettingsStatus
@Inject lateinit var openHumansUploader: OpenHumansUploader @Inject lateinit var openHumansUploader: OpenHumansUploader
// TODO why?
@Inject lateinit var androidInjector: DispatchingAndroidInjector<Any>
override fun androidInjector(): AndroidInjector<Any> = androidInjector
override fun onAttach(context: Context) { override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this) AndroidSupportInjection.inject(this)
super.onAttach(context) super.onAttach(context)
@ -259,7 +251,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
} }
} }
private fun addPreferencesFromResource(@XmlRes preferencesResId: Int, key: String?, enabled: Boolean) { private fun addPreferencesFromResource(@Suppress("SameParameterValue") @XmlRes preferencesResId: Int, key: String?, enabled: Boolean) {
if (enabled) addPreferencesFromResource(preferencesResId, key) if (enabled) addPreferencesFromResource(preferencesResId, key)
} }
@ -426,7 +418,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
return super.onPreferenceTreeClick(preference) return super.onPreferenceTreeClick(preference)
} }
public fun setFilter(filter: String) { fun setFilter(filter: String) {
this.filter = filter this.filter = filter
updateFilterVisibility(filter, preferenceScreen) updateFilterVisibility(filter, preferenceScreen)
} }

View file

@ -10,7 +10,6 @@ import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.locale.LocaleHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import kotlinx.android.synthetic.main.activity_preferences.* import kotlinx.android.synthetic.main.activity_preferences.*
import kotlinx.android.synthetic.main.local_insight_status_item.view.*
import javax.inject.Inject import javax.inject.Inject
class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback { class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
@ -33,10 +32,6 @@ class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompa
override fun afterTextChanged(s: Editable) {} override fun afterTextChanged(s: Editable) {}
}) })
pref_filter_clear.setOnClickListener() {
pref_filter.setText("");
}
title = resourceHelper.gs(R.string.nav_preferences) title = resourceHelper.gs(R.string.nav_preferences)
supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true)

View file

@ -39,6 +39,7 @@ abstract class AutomationModule {
@ContributesAndroidInjector abstract fun actionLoopResumeInjector(): ActionLoopResume @ContributesAndroidInjector abstract fun actionLoopResumeInjector(): ActionLoopResume
@ContributesAndroidInjector abstract fun actionLoopSuspendInjector(): ActionLoopSuspend @ContributesAndroidInjector abstract fun actionLoopSuspendInjector(): ActionLoopSuspend
@ContributesAndroidInjector abstract fun actionNotificationInjector(): ActionNotification @ContributesAndroidInjector abstract fun actionNotificationInjector(): ActionNotification
@ContributesAndroidInjector abstract fun actionAlarmInjector(): ActionAlarm
@ContributesAndroidInjector abstract fun actionProfileSwitchInjector(): ActionProfileSwitch @ContributesAndroidInjector abstract fun actionProfileSwitchInjector(): ActionProfileSwitch
@ContributesAndroidInjector abstract fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent @ContributesAndroidInjector abstract fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent
@ContributesAndroidInjector abstract fun actionSendSMSInjector(): ActionSendSMS @ContributesAndroidInjector abstract fun actionSendSMSInjector(): ActionSendSMS

View file

@ -122,7 +122,7 @@ class CareDialog : DialogFragmentWithDate() {
} }
} }
val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).getGlucoseStatusData()?.glucose val bg = Profile.fromMgdlToUnits(GlucoseStatus(injector).glucoseStatusData?.glucose
?: 0.0, profileFunction.getUnits()) ?: 0.0, profileFunction.getUnits())
val bgTextWatcher: TextWatcher = object : TextWatcher { val bgTextWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {} override fun afterTextChanged(s: Editable) {}

View file

@ -52,7 +52,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
overview_profileswitch_duration.setParams(savedInstanceState?.getDouble("overview_profileswitch_duration") overview_profileswitch_duration.setParams(savedInstanceState?.getDouble("overview_profileswitch_duration")
?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok) ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok)
overview_profileswitch_percentage.setParams(savedInstanceState?.getDouble("overview_profileswitch_percentage") overview_profileswitch_percentage.setParams(savedInstanceState?.getDouble("overview_profileswitch_percentage")
?: 100.0, Constants.CPP_MIN_PERCENTAGE.toDouble(), Constants.CPP_MAX_PERCENTAGE.toDouble(), 1.0, DecimalFormat("0"), false, ok) ?: 100.0, Constants.CPP_MIN_PERCENTAGE.toDouble(), Constants.CPP_MAX_PERCENTAGE.toDouble(), 5.0, DecimalFormat("0"), false, ok)
overview_profileswitch_timeshift.setParams(savedInstanceState?.getDouble("overview_profileswitch_timeshift") overview_profileswitch_timeshift.setParams(savedInstanceState?.getDouble("overview_profileswitch_timeshift")
?: 0.0, Constants.CPP_MIN_TIMESHIFT.toDouble(), Constants.CPP_MAX_TIMESHIFT.toDouble(), 1.0, DecimalFormat("0"), false, ok) ?: 0.0, Constants.CPP_MIN_TIMESHIFT.toDouble(), Constants.CPP_MAX_TIMESHIFT.toDouble(), 1.0, DecimalFormat("0"), false, ok)

View file

@ -22,6 +22,7 @@ import javax.inject.Singleton;
import dagger.Lazy; import dagger.Lazy;
import dagger.android.HasAndroidInjector; import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainActivity;
import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.MainApp;
@ -55,10 +56,10 @@ import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui;
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification; import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification;
import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper;
import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; 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.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification;
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload;
import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin;
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished;
@ -95,9 +96,8 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final NSUpload nsUpload; private final NSUpload nsUpload;
private final HardLimits hardLimits; private final HardLimits hardLimits;
private Notification notification;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private static final String CHANNEL_ID = "AndroidAPS-Openloop"; private static final String CHANNEL_ID = "AndroidAPS-Openloop";
@ -126,6 +126,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
AAPSLogger aapsLogger, AAPSLogger aapsLogger,
RxBusWrapper rxBus, RxBusWrapper rxBus,
SP sp, SP sp,
Config config,
ConstraintChecker constraintChecker, ConstraintChecker constraintChecker,
ResourceHelper resourceHelper, ResourceHelper resourceHelper,
ProfileFunction profileFunction, ProfileFunction profileFunction,
@ -147,6 +148,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
.pluginName(R.string.loop) .pluginName(R.string.loop)
.shortName(R.string.loop_shortname) .shortName(R.string.loop_shortname)
.preferencesId(R.xml.pref_loop) .preferencesId(R.xml.pref_loop)
.enableByDefault(config.getAPS())
.description(R.string.description_loop), .description(R.string.description_loop),
aapsLogger, resourceHelper, injector aapsLogger, resourceHelper, injector
); );
@ -415,7 +417,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
resultAfterConstraints.smb = 0; resultAfterConstraints.smb = 0;
} }
if (lastRun != null) { if (lastRun != null && lastRun.getConstraintsProcessed() != null) {
prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq; prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq;
} }

View file

@ -40,7 +40,7 @@ import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
public class DetermineBasalAdapterAMAJS { public class DetermineBasalAdapterAMAJS {
private HasAndroidInjector injector; private final HasAndroidInjector injector;
@Inject AAPSLogger aapsLogger; @Inject AAPSLogger aapsLogger;
@Inject ConstraintChecker constraintChecker; @Inject ConstraintChecker constraintChecker;
@Inject SP sp; @Inject SP sp;
@ -48,7 +48,7 @@ public class DetermineBasalAdapterAMAJS {
@Inject TreatmentsPlugin treatmentsPlugin; @Inject TreatmentsPlugin treatmentsPlugin;
@Inject OpenHumansUploader openHumansUploader; @Inject OpenHumansUploader openHumansUploader;
private ScriptReader mScriptReader; private final ScriptReader mScriptReader;
private JSONObject mProfile; private JSONObject mProfile;
private JSONObject mGlucoseStatus; private JSONObject mGlucoseStatus;

View file

@ -55,7 +55,7 @@ public class DetermineBasalAdapterSMBJS {
@Inject OpenHumansUploader openHumansUploader; @Inject OpenHumansUploader openHumansUploader;
private ScriptReader mScriptReader; private final ScriptReader mScriptReader;
private JSONObject mProfile; private JSONObject mProfile;
private JSONObject mGlucoseStatus; private JSONObject mGlucoseStatus;
private JSONArray mIobData; private JSONArray mIobData;

View file

@ -5,12 +5,9 @@ import android.os.Bundle
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.CheckBox import android.widget.*
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.TextView
import androidx.annotation.StringRes import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
@ -129,6 +126,7 @@ class ConfigBuilderFragment : DaggerFragment() {
val baseView: LinearLayout = fragment.layoutInflater.inflate(R.layout.configbuilder_single_plugin, null) as LinearLayout val baseView: LinearLayout = fragment.layoutInflater.inflate(R.layout.configbuilder_single_plugin, null) as LinearLayout
private val enabledExclusive: RadioButton private val enabledExclusive: RadioButton
private val enabledInclusive: CheckBox private val enabledInclusive: CheckBox
private val pluginIcon: ImageView
private val pluginName: TextView private val pluginName: TextView
private val pluginDescription: TextView private val pluginDescription: TextView
private val pluginPreferences: ImageButton private val pluginPreferences: ImageButton
@ -137,6 +135,7 @@ class ConfigBuilderFragment : DaggerFragment() {
init { init {
enabledExclusive = baseView.findViewById(R.id.plugin_enabled_exclusive) enabledExclusive = baseView.findViewById(R.id.plugin_enabled_exclusive)
enabledInclusive = baseView.findViewById(R.id.plugin_enabled_inclusive) enabledInclusive = baseView.findViewById(R.id.plugin_enabled_inclusive)
pluginIcon = baseView.findViewById(R.id.plugin_icon)
pluginName = baseView.findViewById(R.id.plugin_name) pluginName = baseView.findViewById(R.id.plugin_name)
pluginDescription = baseView.findViewById(R.id.plugin_description) pluginDescription = baseView.findViewById(R.id.plugin_description)
pluginPreferences = baseView.findViewById(R.id.plugin_preferences) pluginPreferences = baseView.findViewById(R.id.plugin_preferences)
@ -175,6 +174,12 @@ class ConfigBuilderFragment : DaggerFragment() {
enabledInclusive.isChecked = plugin.isEnabled(pluginType) enabledInclusive.isChecked = plugin.isEnabled(pluginType)
enabledInclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled enabledInclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled
enabledExclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled enabledExclusive.isEnabled = !plugin.pluginDescription.alwaysEnabled
if(plugin.menuIcon != -1) {
pluginIcon.visibility = View.VISIBLE
pluginIcon.setImageDrawable(context?.let { ContextCompat.getDrawable(it, plugin.menuIcon) })
} else {
pluginIcon.visibility = View.GONE
}
pluginName.text = plugin.name pluginName.text = plugin.name
if (plugin.description == null) if (plugin.description == null)
pluginDescription.visibility = View.GONE pluginDescription.visibility = View.GONE

View file

@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.configBuilder.events
import info.nightscout.androidaps.events.EventUpdateGui import info.nightscout.androidaps.events.EventUpdateGui
class EventConfigBuilderUpdateGui : EventUpdateGui() { class EventConfigBuilderUpdateGui : EventUpdateGui()
}

View file

@ -26,9 +26,9 @@ public abstract class Objective {
@Inject public SP sp; @Inject public SP sp;
@Inject public ResourceHelper resourceHelper; @Inject public ResourceHelper resourceHelper;
private String spName; private final String spName;
@StringRes private int objective; @StringRes private final int objective;
@StringRes private int gate; @StringRes private final int gate;
private long startedOn; private long startedOn;
private long accomplishedOn; private long accomplishedOn;
List<Task> tasks = new ArrayList<>(); List<Task> tasks = new ArrayList<>();
@ -116,7 +116,7 @@ public abstract class Objective {
public abstract class Task { public abstract class Task {
@StringRes @StringRes
private int task; private final int task;
private Objective objective; private Objective objective;
ArrayList<Hint> hints = new ArrayList<>(); ArrayList<Hint> hints = new ArrayList<>();
@ -138,8 +138,6 @@ public abstract class Objective {
return isCompleted(); return isCompleted();
} }
;
public String getProgress() { public String getProgress() {
return resourceHelper.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet); return resourceHelper.gs(isCompleted() ? R.string.completed_well_done : R.string.not_completed_yet);
} }
@ -160,7 +158,7 @@ public abstract class Objective {
public class MinimumDurationTask extends Task { public class MinimumDurationTask extends Task {
private long minimumDuration; private final long minimumDuration;
MinimumDurationTask(long minimumDuration) { MinimumDurationTask(long minimumDuration) {
super(R.string.time_elapsed); super(R.string.time_elapsed);
@ -197,7 +195,7 @@ public abstract class Objective {
@StringRes @StringRes
int question; int question;
ArrayList<Option> options = new ArrayList<>(); ArrayList<Option> options = new ArrayList<>();
private String spIdentifier; private final String spIdentifier;
private boolean answered; private boolean answered;
private long disabledTo; private long disabledTo;
@ -274,8 +272,7 @@ public abstract class Objective {
public boolean evaluate() { public boolean evaluate() {
boolean selection = cb.isChecked(); boolean selection = cb.isChecked();
if (selection && isCorrect) return true; if (selection && isCorrect) return true;
if (!selection && !isCorrect) return true; return !selection && !isCorrect;
return false;
} }
} }

View file

@ -78,9 +78,7 @@ public class Objective0 extends Objective {
@Override @Override
public boolean isCompleted() { public boolean isCompleted() {
APSInterface usedAPS = activePlugin.getActiveAPS(); APSInterface usedAPS = activePlugin.getActiveAPS();
if (((PluginBase) usedAPS).isEnabled(PluginType.APS)) return ((PluginBase) usedAPS).isEnabled(PluginType.APS);
return true;
return false;
} }
}); });
tasks.add(new Task(R.string.activate_profile) { tasks.add(new Task(R.string.activate_profile) {

View file

@ -10,6 +10,7 @@ import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.R; import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin; import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin;
import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService;
import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.T;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -50,7 +51,7 @@ public class Objective3 extends Objective {
@Override @Override
public boolean specialActionEnabled() { public boolean specialActionEnabled() {
return nsClientPlugin.nsClientService.isConnected && nsClientPlugin.nsClientService.hasWriteAuth; return NSClientService.isConnected && NSClientService.hasWriteAuth;
} }
@Override @Override

View file

@ -36,12 +36,12 @@ class PhoneCheckerPlugin @Inject constructor(
private fun isDevModeEnabled(): Boolean { private fun isDevModeEnabled(): Boolean {
return android.provider.Settings.Secure.getInt(context.contentResolver, return android.provider.Settings.Secure.getInt(context.contentResolver,
android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0; android.provider.Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0) != 0
} }
override fun onStart() { override fun onStart() {
super.onStart() super.onStart()
phoneRooted = RootBeer(context).isRooted() phoneRooted = RootBeer(context).isRooted
devMode = isDevModeEnabled() devMode = isDevModeEnabled()
} }
} }

View file

@ -273,12 +273,13 @@ class ActionsFragment : DaggerFragment() {
private fun checkPumpCustomActions() { private fun checkPumpCustomActions() {
val activePump = activePlugin.activePump val activePump = activePlugin.activePump
val customActions = activePump.customActions ?: return val customActions = activePump.customActions ?: return
val currentContext = context ?: return
removePumpCustomActions() removePumpCustomActions()
for (customAction in customActions) { for (customAction in customActions) {
if (!customAction.isEnabled) continue if (!customAction.isEnabled) continue
val btn = SingleClickButton(context, null, android.R.attr.buttonStyle) val btn = SingleClickButton(currentContext, null, android.R.attr.buttonStyle)
btn.text = resourceHelper.gs(customAction.name) btn.text = resourceHelper.gs(customAction.name)
val layoutParams = LinearLayout.LayoutParams( val layoutParams = LinearLayout.LayoutParams(

View file

@ -15,12 +15,18 @@ import java.util.*
import javax.inject.Inject import javax.inject.Inject
class AutomationEvent(private val injector: HasAndroidInjector) { class AutomationEvent(private val injector: HasAndroidInjector) {
@Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var aapsLogger: AAPSLogger
var title: String? = null
var isEnabled = true
var systemAction: Boolean = false // true = generated by AAPS, false = entered by user
var readOnly: Boolean = false // removing, editing disabled
var autoRemove: Boolean = false // auto-remove once used
var trigger: Trigger = TriggerConnector(injector) var trigger: Trigger = TriggerConnector(injector)
val actions: MutableList<Action> = ArrayList() val actions: MutableList<Action> = ArrayList()
var title: String? = null
var isEnabled = true
var lastRun: Long = 0 var lastRun: Long = 0
init { init {
@ -43,6 +49,9 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
return JSONObject() return JSONObject()
.put("title", title) .put("title", title)
.put("enabled", isEnabled) .put("enabled", isEnabled)
.put("systemAction", systemAction)
.put("readOnly", readOnly)
.put("autoRemove", autoRemove)
.put("trigger", trigger.toJSON()) .put("trigger", trigger.toJSON())
.put("actions", array) .put("actions", array)
.toString() .toString()
@ -52,6 +61,9 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
val d = JSONObject(data) val d = JSONObject(data)
title = d.optString("title", "") title = d.optString("title", "")
isEnabled = d.optBoolean("enabled", true) isEnabled = d.optBoolean("enabled", true)
systemAction = d.optBoolean("systemAction", false)
readOnly = d.optBoolean("readOnly", false)
autoRemove = d.optBoolean("autoRemove", false)
trigger = TriggerDummy(injector).instantiate(JSONObject(d.getString("trigger"))) trigger = TriggerDummy(injector).instantiate(JSONObject(d.getString("trigger")))
?: TriggerConnector(injector) ?: TriggerConnector(injector)
val array = d.getJSONArray("actions") val array = d.getJSONArray("actions")

View file

@ -9,11 +9,8 @@ import android.view.LayoutInflater
import android.view.MotionEvent import android.view.MotionEvent
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView import android.widget.ImageView
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.annotation.DrawableRes import androidx.annotation.DrawableRes
import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearLayoutManager
@ -21,6 +18,8 @@ import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.AutomationEventItemBinding
import info.nightscout.androidaps.databinding.AutomationFragmentBinding
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog
import info.nightscout.androidaps.plugins.general.automation.dragHelpers.ItemTouchHelperAdapter import info.nightscout.androidaps.plugins.general.automation.dragHelpers.ItemTouchHelperAdapter
@ -34,39 +33,47 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.extensions.toVisibility
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_fragment.*
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
class AutomationFragment : DaggerFragment(), OnStartDragListener { class AutomationFragment : DaggerFragment(), OnStartDragListener {
@Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var mainApp : MainApp @Inject lateinit var mainApp: MainApp
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private lateinit var eventListAdapter: EventListAdapter private lateinit var eventListAdapter: EventListAdapter
private var itemTouchHelper: ItemTouchHelper? = null private var itemTouchHelper: ItemTouchHelper? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { private var _binding: AutomationFragmentBinding? = null
return inflater.inflate(R.layout.automation_fragment, container, false)
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = AutomationFragmentBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
eventListAdapter = EventListAdapter() eventListAdapter = EventListAdapter()
automation_eventListView.layoutManager = LinearLayoutManager(context) binding.eventListView.layoutManager = LinearLayoutManager(context)
automation_eventListView.adapter = eventListAdapter binding.eventListView.adapter = eventListAdapter
automation_logView.movementMethod = ScrollingMovementMethod() binding.logView.movementMethod = ScrollingMovementMethod()
automation_fabAddEvent.setOnClickListener { binding.fabAddEvent.setOnClickListener {
val dialog = EditEventDialog() val dialog = EditEventDialog()
val args = Bundle() val args = Bundle()
args.putString("event", AutomationEvent(mainApp).toJSON()) args.putString("event", AutomationEvent(mainApp).toJSON())
@ -77,7 +84,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter) val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter)
itemTouchHelper = ItemTouchHelper(callback) itemTouchHelper = ItemTouchHelper(callback)
itemTouchHelper?.attachToRecyclerView(automation_eventListView) itemTouchHelper?.attachToRecyclerView(binding.eventListView)
} }
@ -105,13 +112,18 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
disposable.clear() disposable.clear()
} }
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
@Synchronized @Synchronized
private fun updateGui() { private fun updateGui() {
eventListAdapter.notifyDataSetChanged() eventListAdapter.notifyDataSetChanged()
val sb = StringBuilder() val sb = StringBuilder()
for (l in automationPlugin.executionLog.reversed()) for (l in automationPlugin.executionLog.reversed())
sb.append(l).append("<br>") sb.append(l).append("<br>")
automation_logView?.text = HtmlHelper.fromHtml(sb.toString()) binding.logView.text = HtmlHelper.fromHtml(sb.toString())
} }
override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) { override fun onStartDrag(viewHolder: RecyclerView.ViewHolder) {
@ -132,6 +144,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
} }
inner class EventListAdapter : RecyclerView.Adapter<EventListAdapter.ViewHolder>(), ItemTouchHelperAdapter { inner class EventListAdapter : RecyclerView.Adapter<EventListAdapter.ViewHolder>(), ItemTouchHelperAdapter {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.automation_event_item, parent, false) val v = LayoutInflater.from(parent.context).inflate(R.layout.automation_event_item, parent, false)
return ViewHolder(v, parent.context) return ViewHolder(v, parent.context)
@ -147,36 +160,38 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
@SuppressLint("ClickableViewAccessibility") @SuppressLint("ClickableViewAccessibility")
override fun onBindViewHolder(holder: ViewHolder, position: Int) { override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val event = automationPlugin.automationEvents[position] val event = automationPlugin.automationEvents[position]
holder.eventTitle.text = event.title holder.binding.eventTitle.text = event.title
holder.enabled.isChecked = event.isEnabled holder.binding.enabled.isChecked = event.isEnabled
holder.iconLayout.removeAllViews() holder.binding.enabled.isEnabled = !event.readOnly
holder.binding.iconLayout.removeAllViews()
// trigger icons // trigger icons
val triggerIcons = HashSet<Int>() val triggerIcons = HashSet<Int>()
fillIconSet(event.trigger as TriggerConnector, triggerIcons) fillIconSet(event.trigger as TriggerConnector, triggerIcons)
for (res in triggerIcons) { for (res in triggerIcons) {
addImage(res, holder.context, holder.iconLayout) addImage(res, holder.context, holder.binding.iconLayout)
} }
// arrow icon // arrow icon
val iv = ImageView(holder.context) val iv = ImageView(holder.context)
iv.setImageResource(R.drawable.ic_arrow_forward_white_24dp) iv.setImageResource(R.drawable.ic_arrow_forward_white_24dp)
iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24)) iv.layoutParams = LinearLayout.LayoutParams(resourceHelper.dpToPx(24), resourceHelper.dpToPx(24))
iv.setPadding(resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4), 0) iv.setPadding(resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4), 0)
holder.iconLayout.addView(iv) holder.binding.iconLayout.addView(iv)
// action icons // action icons
val actionIcons = HashSet<Int>() val actionIcons = HashSet<Int>()
for (action in event.actions) { for (action in event.actions) {
actionIcons.add(action.icon()) actionIcons.add(action.icon())
} }
for (res in actionIcons) { for (res in actionIcons) {
addImage(res, holder.context, holder.iconLayout) addImage(res, holder.context, holder.binding.iconLayout)
} }
// enabled event // enabled event
holder.enabled.setOnClickListener { holder.binding.enabled.setOnClickListener {
event.isEnabled = holder.enabled.isChecked event.isEnabled = holder.binding.enabled.isChecked
rxBus.send(EventAutomationDataChanged()) rxBus.send(EventAutomationDataChanged())
} }
// edit event // edit event
holder.rootLayout.setOnClickListener { if (!event.readOnly)
holder.binding.rootLayout.setOnClickListener {
val dialog = EditEventDialog() val dialog = EditEventDialog()
val args = Bundle() val args = Bundle()
args.putString("event", event.toJSON()) args.putString("event", event.toJSON())
@ -185,13 +200,26 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
dialog.show(childFragmentManager, "EditEventDialog") dialog.show(childFragmentManager, "EditEventDialog")
} }
// Start a drag whenever the handle view it touched // Start a drag whenever the handle view it touched
holder.iconSort.setOnTouchListener { v: View, motionEvent: MotionEvent -> holder.binding.iconSort.setOnTouchListener { v: View, motionEvent: MotionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) { if (motionEvent.action == MotionEvent.ACTION_DOWN) {
this@AutomationFragment.onStartDrag(holder) this@AutomationFragment.onStartDrag(holder)
return@setOnTouchListener true return@setOnTouchListener true
} }
v.onTouchEvent(motionEvent) v.onTouchEvent(motionEvent)
} }
// remove event
holder.binding.iconTrash.setOnClickListener {
showConfirmation(requireContext(), resourceHelper.gs(R.string.removerecord) + " " + automationPlugin.automationEvents[position].title,
Runnable {
automationPlugin.automationEvents.removeAt(position)
notifyItemRemoved(position)
rxBus.send(EventAutomationDataChanged())
rxBus.send(EventAutomationUpdateGui())
}, Runnable {
rxBus.send(EventAutomationUpdateGui())
})
}
holder.binding.iconTrash.visibility = (!event.readOnly).toVisibility()
} }
override fun getItemCount(): Int = automationPlugin.automationEvents.size override fun getItemCount(): Int = automationPlugin.automationEvents.size
@ -216,11 +244,8 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener {
} }
inner class ViewHolder(view: View, val context: Context) : RecyclerView.ViewHolder(view), ItemTouchHelperViewHolder { inner class ViewHolder(view: View, val context: Context) : RecyclerView.ViewHolder(view), ItemTouchHelperViewHolder {
val rootLayout: RelativeLayout = view.findViewById(R.id.rootLayout)
val iconLayout: LinearLayout = view.findViewById(R.id.iconLayout) val binding = AutomationEventItemBinding.bind(view)
val eventTitle: TextView = view.findViewById(R.id.viewEventTitle)
val iconSort: ImageView = view.findViewById(R.id.iconSort)
val enabled: CheckBox = view.findViewById(R.id.automation_enabled)
override fun onItemSelected() = itemView.setBackgroundColor(Color.LTGRAY) override fun onItemSelected() = itemView.setBackgroundColor(Color.LTGRAY)

View file

@ -239,6 +239,7 @@ class AutomationPlugin @Inject constructor(
ActionStartTempTarget(injector), ActionStartTempTarget(injector),
ActionStopTempTarget(injector), ActionStopTempTarget(injector),
ActionNotification(injector), ActionNotification(injector),
ActionAlarm(injector),
ActionProfileSwitchPercent(injector), ActionProfileSwitchPercent(injector),
ActionProfileSwitch(injector), ActionProfileSwitch(injector),
ActionSendSMS(injector) ActionSendSMS(injector)

View file

@ -0,0 +1,72 @@
package info.nightscout.androidaps.plugins.general.automation.actions
import android.content.Context
import android.content.Intent
import android.widget.LinearLayout
import androidx.annotation.DrawableRes
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.elements.InputString
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.alertDialogs.WarningDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
class ActionAlarm(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var nsUpload: NSUpload
@Inject lateinit var context: Context
var text = InputString(injector)
override fun friendlyName(): Int = R.string.alarm
override fun shortDescription(): String = resourceHelper.gs(R.string.alarm_message, text.value)
@DrawableRes override fun icon(): Int = R.drawable.ic_access_alarm_24dp
override fun doAction(callback: Callback) {
val i = Intent(context, ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.modern_alarm)
i.putExtra("status", text.value)
i.putExtra("title", resourceHelper.gs(R.string.alarm))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context.startActivity(i)
callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run()
}
override fun toJSON(): String {
val data = JSONObject().put("text", text.value)
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
text.value = JsonHelper.safeGetString(o, "text", "")
return this
}
override fun hasDialog(): Boolean = true
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(LabelWithElement(injector, resourceHelper.gs(R.string.alarm_short), "", text))
.build(root)
}
}

View file

@ -37,7 +37,7 @@ class ActionStartTempTarget(injector: HasAndroidInjector) : Action(injector) {
override fun friendlyName(): Int = R.string.starttemptarget override fun friendlyName(): Int = R.string.starttemptarget
override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper) override fun shortDescription(): String = resourceHelper.gs(R.string.starttemptarget) + ": " + tt().friendlyDescription(value.units, resourceHelper)
@DrawableRes override fun icon(): Int = R.drawable.ic_cp_cgm_target @DrawableRes override fun icon(): Int = R.drawable.ic_temptarget_high
override fun doAction(callback: Callback) { override fun doAction(callback: Callback) {
activePlugin.activeTreatments.addToHistoryTempTarget(tt()) activePlugin.activeTreatments.addToHistoryTempTarget(tt())

View file

@ -6,24 +6,30 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.RadioButton import android.widget.RadioButton
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.AutomationDialogChooseActionBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.actions.Action import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationAddAction import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationAddAction
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateGui
import kotlinx.android.synthetic.main.automation_dialog_choose_action.*
import javax.inject.Inject import javax.inject.Inject
import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.primaryConstructor
class ChooseActionDialog : DialogFragmentWithDate() { class ChooseActionDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp : MainApp @Inject lateinit var mainApp: MainApp
private var checkedIndex = -1 private var checkedIndex = -1
private var _binding: AutomationDialogChooseActionBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View? {
// restore checked radio button // restore checked radio button
@ -32,7 +38,8 @@ class ChooseActionDialog : DialogFragmentWithDate() {
} }
onCreateViewGeneral() onCreateViewGeneral()
return inflater.inflate(R.layout.automation_dialog_choose_action, container, false) _binding = AutomationDialogChooseActionBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
@ -42,11 +49,16 @@ class ChooseActionDialog : DialogFragmentWithDate() {
val radioButton = RadioButton(context) val radioButton = RadioButton(context)
radioButton.setText(a.friendlyName()) radioButton.setText(a.friendlyName())
radioButton.tag = a.javaClass.name radioButton.tag = a.javaClass.name
automation_radioGroup.addView(radioButton) binding.radioGroup.addView(radioButton)
} }
if (checkedIndex != -1) if (checkedIndex != -1)
(automation_radioGroup.getChildAt(checkedIndex) as RadioButton).isChecked = true (binding.radioGroup.getChildAt(checkedIndex) as RadioButton).isChecked = true
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
} }
override fun submit(): Boolean { override fun submit(): Boolean {
@ -70,16 +82,16 @@ class ChooseActionDialog : DialogFragmentWithDate() {
} }
private fun getActionClass(): String? { private fun getActionClass(): String? {
val radioButtonID = automation_radioGroup.checkedRadioButtonId val radioButtonID = binding.radioGroup.checkedRadioButtonId
val radioButton = automation_radioGroup.findViewById<RadioButton>(radioButtonID) val radioButton = binding.radioGroup.findViewById<RadioButton>(radioButtonID)
return radioButton?.let { return radioButton?.let {
it.tag as String it.tag as String
} }
} }
private fun determineCheckedIndex(): Int { private fun determineCheckedIndex(): Int {
for (i in 0 until automation_radioGroup.childCount) { for (i in 0 until binding.radioGroup.childCount) {
if ((automation_radioGroup.getChildAt(i) as RadioButton).isChecked) if ((binding.radioGroup.getChildAt(i) as RadioButton).isChecked)
return i return i
} }
return -1 return -1

View file

@ -6,34 +6,42 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.RadioButton import android.widget.RadioButton
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.AutomationDialogChooseTriggerBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import kotlinx.android.synthetic.main.automation_dialog_choose_trigger.*
import javax.inject.Inject import javax.inject.Inject
import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.primaryConstructor
class ChooseTriggerDialog : DialogFragmentWithDate() { class ChooseTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var mainApp : MainApp @Inject lateinit var mainApp: MainApp
private var checkedIndex = -1 private var checkedIndex = -1
private var clickListener: OnClickListener? = null private var clickListener: OnClickListener? = null
private var _binding: AutomationDialogChooseTriggerBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
interface OnClickListener { interface OnClickListener {
fun onClick(newTriggerObject: Trigger) fun onClick(newTriggerObject: Trigger)
} }
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View {
// restore checked radio button // restore checked radio button
savedInstanceState?.let { bundle -> savedInstanceState?.let { bundle ->
checkedIndex = bundle.getInt("checkedIndex") checkedIndex = bundle.getInt("checkedIndex")
} }
onCreateViewGeneral() onCreateViewGeneral()
return inflater.inflate(R.layout.automation_dialog_choose_trigger, container, false) _binding = AutomationDialogChooseTriggerBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
@ -43,11 +51,16 @@ class ChooseTriggerDialog : DialogFragmentWithDate() {
val radioButton = RadioButton(context) val radioButton = RadioButton(context)
radioButton.setText(t.friendlyName()) radioButton.setText(t.friendlyName())
radioButton.tag = t.javaClass.name radioButton.tag = t.javaClass.name
automation_chooseTriggerRadioGroup.addView(radioButton) binding.chooseTriggerRadioGroup.addView(radioButton)
} }
if (checkedIndex != -1) if (checkedIndex != -1)
(automation_chooseTriggerRadioGroup.getChildAt(checkedIndex) as RadioButton).isChecked = true (binding.chooseTriggerRadioGroup.getChildAt(checkedIndex) as RadioButton).isChecked = true
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
} }
override fun submit(): Boolean { override fun submit(): Boolean {
@ -74,16 +87,16 @@ class ChooseTriggerDialog : DialogFragmentWithDate() {
} }
private fun getTriggerClass(): String? { private fun getTriggerClass(): String? {
val radioButtonID = automation_chooseTriggerRadioGroup.checkedRadioButtonId val radioButtonID = binding.chooseTriggerRadioGroup.checkedRadioButtonId
val radioButton = automation_chooseTriggerRadioGroup.findViewById<RadioButton>(radioButtonID) val radioButton = binding.chooseTriggerRadioGroup.findViewById<RadioButton>(radioButtonID)
return radioButton?.let { return radioButton?.let {
it.tag as String it.tag as String
} }
} }
private fun determineCheckedIndex(): Int { private fun determineCheckedIndex(): Int {
for (i in 0 until automation_chooseTriggerRadioGroup.childCount) { for (i in 0 until binding.chooseTriggerRadioGroup.childCount) {
if ((automation_chooseTriggerRadioGroup.getChildAt(i) as RadioButton).isChecked) if ((binding.chooseTriggerRadioGroup.getChildAt(i) as RadioButton).isChecked)
return i return i
} }
return -1 return -1

View file

@ -5,41 +5,48 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.AutomationDialogActionBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.actions.Action import info.nightscout.androidaps.plugins.general.automation.actions.Action
import info.nightscout.androidaps.plugins.general.automation.actions.ActionDummy import info.nightscout.androidaps.plugins.general.automation.actions.ActionDummy
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateAction import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateAction
import kotlinx.android.synthetic.main.automation_dialog_action.*
import org.json.JSONObject import org.json.JSONObject
import javax.inject.Inject import javax.inject.Inject
class EditActionDialog : DialogFragmentWithDate() { class EditActionDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp @Inject lateinit var mainApp: MainApp
private var action: Action? = null private var action: Action? = null
private var actionPosition: Int = -1 private var actionPosition: Int = -1
private var _binding: AutomationDialogActionBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View {
// load data from bundle // load data from bundle
(savedInstanceState ?: arguments)?.let { bundle -> (savedInstanceState ?: arguments)?.let { bundle ->
actionPosition = bundle.getInt("actionPosition", -1) actionPosition = bundle.getInt("actionPosition", -1)
bundle.getString("action")?.let { action = ActionDummy(mainApp).instantiate(JSONObject(it)) } bundle.getString("action")?.let { action = ActionDummy(mainApp).instantiate(JSONObject(it)) }
} }
onCreateViewGeneral() onCreateViewGeneral()
return inflater.inflate(R.layout.automation_dialog_action, container, false) _binding = AutomationDialogActionBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
action?.let { action?.let {
automation_actionTitle.setText(it.friendlyName()) binding.actionTitle.setText(it.friendlyName())
automation_editActionLayout.removeAllViews() binding.editActionLayout.removeAllViews()
it.generateDialog(automation_editActionLayout) it.generateDialog(binding.editActionLayout)
} }
} }

View file

@ -11,6 +11,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.AutomationDialogEventBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationEvent import info.nightscout.androidaps.plugins.general.automation.AutomationEvent
@ -27,10 +28,10 @@ import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_dialog_event.*
import javax.inject.Inject import javax.inject.Inject
class EditEventDialog : DialogFragmentWithDate() { class EditEventDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp @Inject lateinit var mainApp: MainApp
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@ -42,8 +43,14 @@ class EditEventDialog : DialogFragmentWithDate() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private var _binding: AutomationDialogEventBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View {
event = AutomationEvent(mainApp) event = AutomationEvent(mainApp)
// load data from bundle // load data from bundle
(savedInstanceState ?: arguments)?.let { bundle -> (savedInstanceState ?: arguments)?.let { bundle ->
@ -52,16 +59,17 @@ class EditEventDialog : DialogFragmentWithDate() {
} }
onCreateViewGeneral() onCreateViewGeneral()
return inflater.inflate(R.layout.automation_dialog_event, container, false) _binding = AutomationDialogEventBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
automation_inputEventTitle.setText(event.title) binding.inputEventTitle.setText(event.title)
automation_triggerDescription.text = event.trigger.friendlyDescription() binding.triggerDescription.text = event.trigger.friendlyDescription()
automation_editTrigger.setOnClickListener { binding.editTrigger.setOnClickListener {
val args = Bundle() val args = Bundle()
args.putString("trigger", event.trigger.toJSON()) args.putString("trigger", event.trigger.toJSON())
val dialog = EditTriggerDialog() val dialog = EditTriggerDialog()
@ -71,10 +79,10 @@ class EditEventDialog : DialogFragmentWithDate() {
// setup action list view // setup action list view
actionListAdapter = ActionListAdapter() actionListAdapter = ActionListAdapter()
automation_actionListView.layoutManager = LinearLayoutManager(context) binding.actionListView.layoutManager = LinearLayoutManager(context)
automation_actionListView.adapter = actionListAdapter binding.actionListView.adapter = actionListAdapter
automation_addAction.setOnClickListener { ChooseActionDialog().show(childFragmentManager, "ChooseActionDialog") } binding.addAction.setOnClickListener { ChooseActionDialog().show(childFragmentManager, "ChooseActionDialog") }
showPreconditions() showPreconditions()
@ -99,7 +107,7 @@ class EditEventDialog : DialogFragmentWithDate() {
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
event.trigger = it.trigger event.trigger = it.trigger
automation_triggerDescription.text = event.trigger.friendlyDescription() binding.triggerDescription.text = event.trigger.friendlyDescription()
}, { fabricPrivacy.logException(it) } }, { fabricPrivacy.logException(it) }
) )
disposable += rxBus disposable += rxBus
@ -113,7 +121,7 @@ class EditEventDialog : DialogFragmentWithDate() {
override fun submit(): Boolean { override fun submit(): Boolean {
// check for title // check for title
val title = automation_inputEventTitle?.text?.toString() ?: return false val title = binding.inputEventTitle.text?.toString() ?: return false
if (title.isEmpty()) { if (title.isEmpty()) {
ToastUtils.showToastInUiThread(context, R.string.automation_missing_task_name) ToastUtils.showToastInUiThread(context, R.string.automation_missing_task_name)
return false return false
@ -143,6 +151,7 @@ class EditEventDialog : DialogFragmentWithDate() {
override fun onDestroyView() { override fun onDestroyView() {
super.onDestroyView() super.onDestroyView()
disposable.clear() disposable.clear()
_binding = null
} }
override fun onSaveInstanceState(savedInstanceState: Bundle) { override fun onSaveInstanceState(savedInstanceState: Bundle) {
@ -154,12 +163,12 @@ class EditEventDialog : DialogFragmentWithDate() {
private fun showPreconditions() { private fun showPreconditions() {
val forcedTriggers = event.getPreconditions() val forcedTriggers = event.getPreconditions()
if (forcedTriggers.size() > 0) { if (forcedTriggers.size() > 0) {
automation_forcedTriggerDescription.visibility = View.VISIBLE binding.forcedTriggerDescription.visibility = View.VISIBLE
automation_forcedTriggerDescriptionLabel.visibility = View.VISIBLE binding.forcedTriggerDescriptionLabel.visibility = View.VISIBLE
automation_forcedTriggerDescription.text = forcedTriggers.friendlyDescription() binding.forcedTriggerDescription.text = forcedTriggers.friendlyDescription()
} else { } else {
automation_forcedTriggerDescription.visibility = View.GONE binding.forcedTriggerDescription.visibility = View.GONE
automation_forcedTriggerDescriptionLabel.visibility = View.GONE binding.forcedTriggerDescriptionLabel.visibility = View.GONE
} }
} }

View file

@ -5,7 +5,7 @@ import android.view.LayoutInflater
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.AutomationDialogEditTriggerBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateTrigger import info.nightscout.androidaps.plugins.general.automation.events.EventAutomationUpdateTrigger
@ -19,11 +19,11 @@ import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign import info.nightscout.androidaps.utils.extensions.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_dialog_edit_trigger.*
import org.json.JSONObject import org.json.JSONObject
import javax.inject.Inject import javax.inject.Inject
class EditTriggerDialog : DialogFragmentWithDate() { class EditTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp @Inject lateinit var mainApp: MainApp
@Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var fabricPrivacy: FabricPrivacy
@ -32,15 +32,22 @@ class EditTriggerDialog : DialogFragmentWithDate() {
private var triggers: Trigger? = null private var triggers: Trigger? = null
private var _binding: AutomationDialogEditTriggerBinding? = null
// This property is only valid between onCreateView and
// onDestroyView.
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? { savedInstanceState: Bundle?): View {
// load data from bundle // load data from bundle
(savedInstanceState ?: arguments)?.let { bundle -> (savedInstanceState ?: arguments)?.let { bundle ->
bundle.getString("trigger")?.let { triggers = TriggerDummy(mainApp).instantiate(JSONObject(it)) } bundle.getString("trigger")?.let { triggers = TriggerDummy(mainApp).instantiate(JSONObject(it)) }
} }
onCreateViewGeneral() onCreateViewGeneral()
return inflater.inflate(R.layout.automation_dialog_edit_trigger, container, false) _binding = AutomationDialogEditTriggerBinding.inflate(inflater, container, false)
return binding.root
} }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
@ -50,16 +57,16 @@ class EditTriggerDialog : DialogFragmentWithDate() {
.toObservable(EventTriggerChanged::class.java) .toObservable(EventTriggerChanged::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
automation_layoutTrigger.removeAllViews() binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger) triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) }) }, { fabricPrivacy.logException(it) })
disposable += rxBus disposable += rxBus
.toObservable(EventTriggerRemove::class.java) .toObservable(EventTriggerRemove::class.java)
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
findParent(triggers, it.trigger)?.list?.remove(it.trigger) findParent(triggers, it.trigger)?.list?.remove(it.trigger)
automation_layoutTrigger.removeAllViews() binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger) triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) }) }, { fabricPrivacy.logException(it) })
disposable += rxBus disposable += rxBus
@ -67,17 +74,18 @@ class EditTriggerDialog : DialogFragmentWithDate() {
.observeOn(AndroidSchedulers.mainThread()) .observeOn(AndroidSchedulers.mainThread())
.subscribe({ .subscribe({
findParent(triggers, it.trigger)?.list?.add(it.trigger.duplicate()) findParent(triggers, it.trigger)?.list?.add(it.trigger.duplicate())
automation_layoutTrigger.removeAllViews() binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger) triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) }) }, { fabricPrivacy.logException(it) })
// display root trigger // display root trigger
triggers?.generateDialog(automation_layoutTrigger) triggers?.generateDialog(binding.layoutTrigger)
} }
override fun onDestroyView() { override fun onDestroyView() {
super.onDestroyView() super.onDestroyView()
disposable.clear() disposable.clear()
_binding = null
} }
override fun submit(): Boolean { override fun submit(): Boolean {

View file

@ -21,7 +21,7 @@ class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter
} }
override fun isItemViewSwipeEnabled(): Boolean { override fun isItemViewSwipeEnabled(): Boolean {
return true return false
} }
override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { // Set movement flags based on the layout manager override fun getMovementFlags(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder): Int { // Set movement flags based on the layout manager

View file

@ -46,7 +46,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
if (glucoseStatus == null && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { if (glucoseStatus == null && comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
return true return true

View file

@ -58,7 +58,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) {
} }
override fun shouldRun(): Boolean { override fun shouldRun(): Boolean {
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
?: return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { ?: return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) {
aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription())
true true

View file

@ -105,9 +105,7 @@ public class Food {
return false; return false;
if (!Objects.equals(subcategory, other.subcategory)) if (!Objects.equals(subcategory, other.subcategory))
return false; return false;
if (!Objects.equals(units, other.units)) return Objects.equals(units, other.units);
return false;
return true;
} }
public void copyFrom(Food other) { public void copyFrom(Food other) {

View file

@ -49,7 +49,7 @@ class FoodFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(view, savedInstanceState)
food_recyclerview.setHasFixedSize(true) food_recyclerview.setHasFixedSize(true)
food_recyclerview.setLayoutManager(LinearLayoutManager(view.context)) food_recyclerview.layoutManager = LinearLayoutManager(view.context)
food_recyclerview.adapter = RecyclerViewAdapter(foodPlugin.service?.foodData ?: ArrayList()) food_recyclerview.adapter = RecyclerViewAdapter(foodPlugin.service?.foodData ?: ArrayList())
food_clearfilter.setOnClickListener { food_clearfilter.setOnClickListener {
@ -69,7 +69,7 @@ class FoodFragment : DaggerFragment() {
filterData() filterData()
} }
} }
food_subcategory.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener { food_subcategory.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
filterData() filterData()
} }
@ -77,7 +77,7 @@ class FoodFragment : DaggerFragment() {
override fun onNothingSelected(parent: AdapterView<*>?) { override fun onNothingSelected(parent: AdapterView<*>?) {
filterData() filterData()
} }
}) }
food_filter.addTextChangedListener(object : TextWatcher { food_filter.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

View file

@ -48,7 +48,7 @@ public class FoodService extends OrmLiteBaseService<DatabaseHelper> {
@Inject RxBusWrapper rxBus; @Inject RxBusWrapper rxBus;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledFoodEventPost = null; private static ScheduledFuture<?> scheduledFoodEventPost = null;

View file

@ -208,10 +208,10 @@ class ImportExportPrefs @Inject constructor(
// import is OK when we do not have errors (warnings are allowed) // import is OK when we do not have errors (warnings are allowed)
val importOkCheckedAgain = checkIfImportIsOk(prefsReloaded) val importOkCheckedAgain = checkIfImportIsOk(prefsReloaded)
then(prefsReloaded, importOkCheckedAgain); then(prefsReloaded, importOkCheckedAgain)
} }
} else { } else {
then(prefs, importOk); then(prefs, importOk)
} }
} }
@ -278,7 +278,7 @@ class ImportExportPrefs @Inject constructor(
} }
} }
public fun importSharedPreferences(activity: FragmentActivity, importFile: PrefsFile) { fun importSharedPreferences(activity: FragmentActivity, importFile: PrefsFile) {
askToConfirmImport(activity, importFile) { password -> askToConfirmImport(activity, importFile) { password ->
@ -335,7 +335,7 @@ class ImportExportPrefs @Inject constructor(
for ((_, value) in prefs.metadata) { for ((_, value) in prefs.metadata) {
if (value.status == PrefsStatus.ERROR) if (value.status == PrefsStatus.ERROR)
importOk = false; importOk = false
} }
return importOk return importOk
} }

View file

@ -167,10 +167,10 @@ class PrefFileListProvider @Inject constructor(
meta[PrefsMetadataKey.CREATED_AT]?.let { createdAt -> meta[PrefsMetadataKey.CREATED_AT]?.let { createdAt ->
try { try {
val date1 = DateTime.parse(createdAt.value); val date1 = DateTime.parse(createdAt.value)
val date2 = DateTime.now() val date2 = DateTime.now()
val daysOld = Days.daysBetween(date1.toLocalDate(), date2.toLocalDate()).getDays() val daysOld = Days.daysBetween(date1.toLocalDate(), date2.toLocalDate()).days
if (daysOld > IMPORT_AGE_NOT_YET_OLD_DAYS) { if (daysOld > IMPORT_AGE_NOT_YET_OLD_DAYS) {
createdAt.status = PrefsStatus.WARN createdAt.status = PrefsStatus.WARN

View file

@ -244,7 +244,7 @@ class EncryptedPrefsFormat @Inject constructor(
metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR) metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR)
} }
return metadata; return metadata
} }
} }

View file

@ -37,7 +37,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList
@Inject UploadQueue uploadQueue; @Inject UploadQueue uploadQueue;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private TextView logTextView; private TextView logTextView;
private TextView queueTextView; private TextView queueTextView;

View file

@ -51,7 +51,7 @@ import io.reactivex.schedulers.Schedulers;
@Singleton @Singleton
public class NSClientPlugin extends PluginBase { public class NSClientPlugin extends PluginBase {
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private final AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private final RxBusWrapper rxBus; private final RxBusWrapper rxBus;
@ -73,7 +73,7 @@ public class NSClientPlugin extends PluginBase {
public NSClientService nsClientService = null; public NSClientService nsClientService = null;
private NsClientReceiverDelegate nsClientReceiverDelegate; private final NsClientReceiverDelegate nsClientReceiverDelegate;
@Inject @Inject
public NSClientPlugin( public NSClientPlugin(
@ -209,7 +209,7 @@ public class NSClientPlugin extends PluginBase {
} }
} }
private ServiceConnection mConnection = new ServiceConnection() { private final ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) { public void onServiceDisconnected(ComponentName name) {
aapsLogger.debug(LTag.NSCLIENT, "Service is disconnected"); aapsLogger.debug(LTag.NSCLIENT, "Service is disconnected");
@ -276,7 +276,7 @@ public class NSClientPlugin extends PluginBase {
} }
public boolean hasWritePermission() { public boolean hasWritePermission() {
return nsClientService.hasWriteAuth; return NSClientService.hasWriteAuth;
} }
public void handleClearAlarm(NSAlarm originalAlarm, long silenceTimeInMsec) { public void handleClearAlarm(NSAlarm originalAlarm, long silenceTimeInMsec) {

View file

@ -389,7 +389,7 @@ public class NSDeviceStatus {
// ********* Uploader data *********** // ********* Uploader data ***********
private static HashMap<String, Uploader> uploaders = new HashMap<>(); private static final HashMap<String, Uploader> uploaders = new HashMap<>();
static class Uploader { static class Uploader {
long clock = 0L; long clock = 0L;

View file

@ -10,9 +10,9 @@ import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
public class NSTreatment { public class NSTreatment {
private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); private static final Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT);
private JSONObject data; private final JSONObject data;
private String action = null; // "update", "remove" or null (add) private String action = null; // "update", "remove" or null (add)
public NSTreatment(JSONObject obj) { public NSTreatment(JSONObject obj) {

View file

@ -91,10 +91,10 @@ public class NSClientService extends DaggerService {
@Inject DateUtil dateUtil; @Inject DateUtil dateUtil;
@Inject UploadQueue uploadQueue; @Inject UploadQueue uploadQueue;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
static public PowerManager.WakeLock mWakeLock; static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder(); private final IBinder mBinder = new NSClientService.LocalBinder();
static ProfileStore profileStore; static ProfileStore profileStore;
@ -123,9 +123,9 @@ public class NSClientService extends DaggerService {
private String nsAPIhashCode = ""; private String nsAPIhashCode = "";
private final ArrayList<Long> reconnections = new ArrayList<>(); private final ArrayList<Long> reconnections = new ArrayList<>();
private int WATCHDOG_INTERVAL_MINUTES = 2; private final int WATCHDOG_INTERVAL_MINUTES = 2;
private int WATCHDOG_RECONNECT_IN = 15; private final int WATCHDOG_RECONNECT_IN = 15;
private int WATCHDOG_MAXCONNECTIONS = 5; private final int WATCHDOG_MAXCONNECTIONS = 5;
public NSClientService() { public NSClientService() {
super(); super();
@ -322,7 +322,7 @@ public class NSClientService extends DaggerService {
} }
} }
private Emitter.Listener onConnect = new Emitter.Listener() { private final Emitter.Listener onConnect = new Emitter.Listener() {
@Override @Override
public void call(Object... args) { public void call(Object... args) {
connectCounter++; connectCounter++;
@ -360,7 +360,7 @@ public class NSClientService extends DaggerService {
} }
} }
private Emitter.Listener onDisconnect = new Emitter.Listener() { private final Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override @Override
public void call(Object... args) { public void call(Object... args) {
aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args); aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args);
@ -412,7 +412,7 @@ public class NSClientService extends DaggerService {
nsDevice = sp.getString("careportal_enteredby", ""); nsDevice = sp.getString("careportal_enteredby", "");
} }
private Emitter.Listener onError = new Emitter.Listener() { private final Emitter.Listener onError = new Emitter.Listener() {
@Override @Override
public void call(final Object... args) { public void call(final Object... args) {
String msg = "Unknown Error"; String msg = "Unknown Error";
@ -423,7 +423,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onPing = new Emitter.Listener() { private final Emitter.Listener onPing = new Emitter.Listener() {
@Override @Override
public void call(final Object... args) { public void call(final Object... args) {
rxBus.send(new EventNSClientNewLog("PING", "received")); rxBus.send(new EventNSClientNewLog("PING", "received"));
@ -432,7 +432,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onAnnouncement = new Emitter.Listener() { private final Emitter.Listener onAnnouncement = new Emitter.Listener() {
/* /*
{ {
"level":0, "level":0,
@ -456,7 +456,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onAlarm = new Emitter.Listener() { private final Emitter.Listener onAlarm = new Emitter.Listener() {
/* /*
{ {
"level":1, "level":1,
@ -482,7 +482,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onUrgentAlarm = args -> { private final Emitter.Listener onUrgentAlarm = args -> {
JSONObject data; JSONObject data;
try { try {
data = (JSONObject) args[0]; data = (JSONObject) args[0];
@ -492,7 +492,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onClearAlarm = new Emitter.Listener() { private final Emitter.Listener onClearAlarm = new Emitter.Listener() {
/* /*
{ {
"clear":true, "clear":true,
@ -516,7 +516,7 @@ public class NSClientService extends DaggerService {
} }
}; };
private Emitter.Listener onDataUpdate = new Emitter.Listener() { private final Emitter.Listener onDataUpdate = new Emitter.Listener() {
@Override @Override
public void call(final Object... args) { public void call(final Object... args) {
NSClientService.handler.post(() -> { NSClientService.handler.post(() -> {

View file

@ -579,11 +579,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val glucoseStatus = GlucoseStatus(injector).glucoseStatusData val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
if (glucoseStatus != null) { if (glucoseStatus != null) {
overview_delta_large?.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)
overview_delta_large?.setTextColor(color)
overview_delta?.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) overview_delta?.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)
overview_avgdelta?.text = "${Profile.toSignedUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units)}\n${Profile.toSignedUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units)}" overview_avgdelta?.text = "${Profile.toSignedUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units)}"
overview_long_avgdelta?.text = "${Profile.toSignedUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units)}"
} else { } else {
overview_delta?.text = "Δ " + resourceHelper.gs(R.string.notavailable) overview_delta?.text = "Δ " + resourceHelper.gs(R.string.notavailable)
overview_avgdelta?.text = "" overview_avgdelta?.text = ""
overview_long_avgdelta?.text = ""
} }
// strike through if BG is old // strike through if BG is old
@ -608,16 +612,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_superbolus) overview_apsmode?.setImageResource(R.drawable.ic_loop_superbolus)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
} }
loopPlugin.isDisconnected -> { loopPlugin.isDisconnected -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_disconnected) overview_apsmode?.setImageResource(R.drawable.ic_loop_disconnected)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
} }
loopPlugin.isEnabled() && loopPlugin.isSuspended -> { loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_paused) overview_apsmode?.setImageResource(R.drawable.ic_loop_paused)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
} }
pump.isSuspended -> { pump.isSuspended -> {
@ -628,27 +635,27 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} else { } else {
R.drawable.ic_loop_paused R.drawable.ic_loop_paused
}) })
overview_apsmode_text?.text = "" overview_apsmode_text?.visibility = View.GONE
} }
loopPlugin.isEnabled() && closedLoopEnabled.value() && loopPlugin.isLGS -> { loopPlugin.isEnabled() && closedLoopEnabled.value() && loopPlugin.isLGS -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_lgs) overview_apsmode?.setImageResource(R.drawable.ic_loop_lgs)
overview_apsmode_text?.text = "" overview_apsmode_text?.visibility = View.GONE
} }
loopPlugin.isEnabled() && closedLoopEnabled.value() -> { loopPlugin.isEnabled() && closedLoopEnabled.value() -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_closed) overview_apsmode?.setImageResource(R.drawable.ic_loop_closed)
overview_apsmode_text?.text = "" overview_apsmode_text?.visibility = View.GONE
} }
loopPlugin.isEnabled() && !closedLoopEnabled.value() -> { loopPlugin.isEnabled() && !closedLoopEnabled.value() -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_open) overview_apsmode?.setImageResource(R.drawable.ic_loop_open)
overview_apsmode_text?.text = "" overview_apsmode_text?.visibility = View.GONE
} }
else -> { else -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_disabled) overview_apsmode?.setImageResource(R.drawable.ic_loop_disabled)
overview_apsmode_text?.text = "" overview_apsmode_text?.visibility = View.GONE
} }
} }
} else { } else {

View file

@ -33,7 +33,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
private var disposable: CompositeDisposable = CompositeDisposable() private var disposable: CompositeDisposable = CompositeDisposable()
private inner class RecyclerViewAdapter internal constructor(internal var fragmentManager: FragmentManager) : RecyclerView.Adapter<RecyclerViewAdapter.QuickWizardEntryViewHolder>() { private inner class RecyclerViewAdapter(var fragmentManager: FragmentManager) : RecyclerView.Adapter<RecyclerViewAdapter.QuickWizardEntryViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuickWizardEntryViewHolder { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuickWizardEntryViewHolder {
return QuickWizardEntryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.overview_quickwizardlist_item, parent, false), fragmentManager) return QuickWizardEntryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.overview_quickwizardlist_item, parent, false), fragmentManager)
@ -48,7 +48,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
override fun getItemCount(): Int = quickWizard.size() override fun getItemCount(): Int = quickWizard.size()
private inner class QuickWizardEntryViewHolder internal constructor(itemView: View, internal var fragmentManager: FragmentManager) : RecyclerView.ViewHolder(itemView) { private inner class QuickWizardEntryViewHolder(itemView: View, var fragmentManager: FragmentManager) : RecyclerView.ViewHolder(itemView) {
val buttonText: TextView = itemView.findViewById(R.id.overview_quickwizard_item_buttonText) val buttonText: TextView = itemView.findViewById(R.id.overview_quickwizard_item_buttonText)
val carbs: TextView = itemView.findViewById(R.id.overview_quickwizard_item_carbs) val carbs: TextView = itemView.findViewById(R.id.overview_quickwizard_item_carbs)
val from: TextView = itemView.findViewById(R.id.overview_quickwizard_item_from) val from: TextView = itemView.findViewById(R.id.overview_quickwizard_item_from)

View file

@ -315,7 +315,7 @@ public class AreaGraphSeries<E extends DoubleDataPoint> extends BaseSeries<E> {
canvas.drawPath(mPath, paint); canvas.drawPath(mPath, paint);
canvas.drawPath(mSecondPath, paint); canvas.drawPath(mSecondPath, paint);
if (mStyles.drawBackground) { if (mStyles.drawBackground) {
canvas.drawRect((float)startX, (float)startY2, endX, endY1, mPaintBackground); canvas.drawRect(startX, startY2, endX, endY1, mPaintBackground);
} }
} else if (mStyles.drawDataPoints) { } else if (mStyles.drawDataPoints) {
//fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above) //fix: last value not drawn as datapoint. Draw first point here, and then on every step the end values (above)

View file

@ -11,9 +11,9 @@ import java.io.Serializable;
public class DoubleDataPoint implements DataPointInterface, Serializable { public class DoubleDataPoint implements DataPointInterface, Serializable {
private static final long serialVersionUID=1428267322645L; private static final long serialVersionUID=1428267322645L;
private double x; private final double x;
private double y1; private final double y1;
private double y2; private final double y2;
public DoubleDataPoint(double x, double y1, double y2) { public DoubleDataPoint(double x, double y1, double y2) {
this.x=x; this.x=x;

View file

@ -12,10 +12,10 @@ import java.util.Date;
public class ScaledDataPoint implements DataPointInterface, Serializable { public class ScaledDataPoint implements DataPointInterface, Serializable {
private static final long serialVersionUID=1428263342645L; private static final long serialVersionUID=1428263342645L;
private double x; private final double x;
private double y; private final double y;
private Scale scale; private final Scale scale;
public ScaledDataPoint(double x, double y, Scale scale) { public ScaledDataPoint(double x, double y, Scale scale) {
this.x=x; this.x=x;

View file

@ -137,7 +137,7 @@ class PersistentNotificationPlugin @Inject constructor(
var line1_aa: String var line1_aa: String
val units = profileFunction.getUnits() val units = profileFunction.getUnits()
val lastBG = iobCobCalculatorPlugin.lastBg() val lastBG = iobCobCalculatorPlugin.lastBg()
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
if (lastBG != null) { if (lastBG != null) {
line1_aa = lastBG.valueToUnitsToString(units) line1_aa = lastBG.valueToUnitsToString(units)
line1 = line1_aa line1 = line1_aa

View file

@ -289,7 +289,7 @@ class SmsCommunicatorPlugin @Inject constructor(
val agoMin = (agoMsec / 60.0 / 1000.0).toInt() val agoMin = (agoMsec / 60.0 / 1000.0).toInt()
reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", " reply = resourceHelper.gs(R.string.sms_lastbg) + " " + lastBG.valueToUnitsToString(units) + " " + String.format(resourceHelper.gs(R.string.sms_minago), agoMin) + ", "
} }
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", " if (glucoseStatus != null) reply += resourceHelper.gs(R.string.sms_delta) + " " + Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " " + units + ", "
activePlugin.activeTreatments.updateTotalIOBTreatments() activePlugin.activeTreatments.updateTotalIOBTreatments()
val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round() val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round()
@ -350,7 +350,7 @@ class SmsCommunicatorPlugin @Inject constructor(
"STATUS" -> { "STATUS" -> {
val reply = if (loopPlugin.isEnabled(PluginType.LOOP)) { val reply = if (loopPlugin.isEnabled(PluginType.LOOP)) {
if (loopPlugin.isSuspended()) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) if (loopPlugin.isSuspended) String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend())
else resourceHelper.gs(R.string.smscommunicator_loopisenabled) else resourceHelper.gs(R.string.smscommunicator_loopisenabled)
} else } else
resourceHelper.gs(R.string.smscommunicator_loopisdisabled) resourceHelper.gs(R.string.smscommunicator_loopisdisabled)

View file

@ -35,7 +35,7 @@ class SmsCommunicatorOtpActivity : NoSplashAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) { override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE); window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
setContentView(R.layout.activity_smscommunicator_otp) setContentView(R.layout.activity_smscommunicator_otp)
smscommunicator_otp_verify_edit.addTextChangedListener(object : TextWatcher { smscommunicator_otp_verify_edit.addTextChangedListener(object : TextWatcher {

View file

@ -19,10 +19,10 @@ import java.util.concurrent.locks.ReentrantLock;
* Created by emmablack on 12/26/14. * Created by emmablack on 12/26/14.
*/ */
class SendToDataLayerThread extends AsyncTask<DataMap,Void,Void> { class SendToDataLayerThread extends AsyncTask<DataMap,Void,Void> {
private GoogleApiClient googleApiClient; private final GoogleApiClient googleApiClient;
private static final String TAG = "SendToDataLayerThread"; private static final String TAG = "SendToDataLayerThread";
private String path; private final String path;
private String logPrefix = ""; // "WR: "; private final String logPrefix = ""; // "WR: ";
private static int concurrency = 0; private static int concurrency = 0;
private static int state = 0; private static int state = 0;
private static final ReentrantLock lock = new ReentrantLock(); private static final ReentrantLock lock = new ReentrantLock();

View file

@ -56,6 +56,7 @@ import info.nightscout.androidaps.utils.DefaultValueHelper;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP; import info.nightscout.androidaps.utils.sharedPreferences.SP;
import kotlin.Suppress;
public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
@Inject public HasAndroidInjector injector; @Inject public HasAndroidInjector injector;
@ -768,8 +769,9 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
// Log.d(TAG, "WR: " + source + " " + data); // Log.d(TAG, "WR: " + source + " " + data);
} }
@SuppressWarnings("UNCHECKED")
private void executeTask(AsyncTask task, DataMap... parameters) { private void executeTask(AsyncTask task, DataMap... parameters) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[]) parameters); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, parameters);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); // task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// } else { // } else {

View file

@ -22,8 +22,8 @@ class InsulinFragment : DaggerFragment() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
insulin_name?.setText(activePlugin.activeInsulin.friendlyName) insulin_name?.text = activePlugin.activeInsulin.friendlyName
insulin_comment?.setText(activePlugin.activeInsulin.comment) insulin_comment?.text = activePlugin.activeInsulin.comment
insulin_dia?.text = resourceHelper.gs(R.string.dia) + ": " + activePlugin.activeInsulin.dia + "h" insulin_dia?.text = resourceHelper.gs(R.string.dia) + ": " + activePlugin.activeInsulin.dia + "h"
insulin_graph?.show(activePlugin.activeInsulin) insulin_graph?.show(activePlugin.activeInsulin)
} }

View file

@ -23,7 +23,7 @@ public class GlucoseStatus {
@Inject public AAPSLogger aapsLogger; @Inject public AAPSLogger aapsLogger;
@Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject public IobCobCalculatorPlugin iobCobCalculatorPlugin;
private HasAndroidInjector injector; private final HasAndroidInjector injector;
public double glucose = 0d; public double glucose = 0d;
public double noise = 0d; public double noise = 0d;

View file

@ -72,7 +72,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final DateUtil dateUtil; private final DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private LongSparseArray<IobTotal> iobTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray<IobTotal> iobTable = new LongSparseArray<>(); // oldest at index 0
private LongSparseArray<IobTotal> absIobTable = new LongSparseArray<>(); // oldest at index 0, absolute insulin in the body private LongSparseArray<IobTotal> absIobTable = new LongSparseArray<>(); // oldest at index 0, absolute insulin in the body

View file

@ -73,10 +73,10 @@ public class IobCobOref1Thread extends Thread {
private final HasAndroidInjector injector; private final HasAndroidInjector injector;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; // cannot be injected : HistoryBrowser uses different instance private final IobCobCalculatorPlugin iobCobCalculatorPlugin; // cannot be injected : HistoryBrowser uses different instance
private final TreatmentsPlugin treatmentsPlugin; // cannot be injected : HistoryBrowser uses different instance private final TreatmentsPlugin treatmentsPlugin; // cannot be injected : HistoryBrowser uses different instance
private boolean bgDataReload; private final boolean bgDataReload;
private boolean limitDataToOldestAvailable; private final boolean limitDataToOldestAvailable;
private String from; private final String from;
private long end; private final long end;
private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mWakeLock;
@ -300,10 +300,7 @@ public class IobCobOref1Thread extends Thread {
// If mealCOB is zero but all deviations since hitting COB=0 are positive, exclude from autosens // If mealCOB is zero but all deviations since hitting COB=0 are positive, exclude from autosens
if (autosensData.cob > 0 || autosensData.absorbing || autosensData.mealCarbs > 0) { if (autosensData.cob > 0 || autosensData.absorbing || autosensData.mealCarbs > 0) {
if (deviation > 0) autosensData.absorbing = deviation > 0;
autosensData.absorbing = true;
else
autosensData.absorbing = false;
// stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h // stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h
if (autosensData.mealStartCounter > 60 && autosensData.cob < 0.5) { if (autosensData.mealStartCounter > 60 && autosensData.cob < 0.5) {
autosensData.absorbing = false; autosensData.absorbing = false;
@ -329,10 +326,7 @@ public class IobCobOref1Thread extends Thread {
//if (iob.iob > currentBasal || uam ) { //if (iob.iob > currentBasal || uam ) {
if (iob.iob > 2 * currentBasal || autosensData.uam || autosensData.mealStartCounter < 9) { if (iob.iob > 2 * currentBasal || autosensData.uam || autosensData.mealStartCounter < 9) {
autosensData.mealStartCounter++; autosensData.mealStartCounter++;
if (deviation > 0) autosensData.uam = deviation > 0;
autosensData.uam = true;
else
autosensData.uam = false;
if (!autosensData.type.equals("uam")) { if (!autosensData.type.equals("uam")) {
// process.stderr.write("u("); // process.stderr.write("u(");
} }

View file

@ -70,10 +70,10 @@ public class IobCobThread extends Thread {
private final HasAndroidInjector injector; private final HasAndroidInjector injector;
private final IobCobCalculatorPlugin iobCobCalculatorPlugin; // cannot be injected : HistoryBrowser uses different instance private final IobCobCalculatorPlugin iobCobCalculatorPlugin; // cannot be injected : HistoryBrowser uses different instance
private final TreatmentsPlugin treatmentsPlugin; // cannot be injected : HistoryBrowser uses different instance private final TreatmentsPlugin treatmentsPlugin; // cannot be injected : HistoryBrowser uses different instance
private boolean bgDataReload; private final boolean bgDataReload;
private boolean limitDataToOldestAvailable; private final boolean limitDataToOldestAvailable;
private String from; private final String from;
private long end; private final long end;
private PowerManager.WakeLock mWakeLock; private PowerManager.WakeLock mWakeLock;

View file

@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.profile.local.events
import info.nightscout.androidaps.events.Event import info.nightscout.androidaps.events.Event
class EventLocalProfileChanged : Event() { class EventLocalProfileChanged : Event()
}

View file

@ -40,7 +40,7 @@ public class ComboFragment extends DaggerFragment implements View.OnClickListene
@Inject SP sp; @Inject SP sp;
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private TextView stateView; private TextView stateView;
private TextView activityView; private TextView activityView;

View file

@ -147,6 +147,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
super(new PluginDescription() super(new PluginDescription()
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)
.fragmentClass(ComboFragment.class.getName()) .fragmentClass(ComboFragment.class.getName())
.pluginIcon(R.drawable.ic_combo)
.pluginName(R.string.combopump) .pluginName(R.string.combopump)
.shortName(R.string.combopump_shortname) .shortName(R.string.combopump_shortname)
.description(R.string.description_pump_combo), .description(R.string.description_pump_combo),
@ -451,7 +452,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
} }
} }
private BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> { private final BolusProgressReporter bolusProgressReporter = (state, percent, delivered) -> {
EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE; EventOverviewBolusProgress event = EventOverviewBolusProgress.INSTANCE;
switch (state) { switch (state) {
case PROGRAMMING: case PROGRAMMING:
@ -966,9 +967,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
checkPumpTime(preCheckResult.state); checkPumpTime(preCheckResult.state);
checkBasalRate(preCheckResult.state); checkBasalRate(preCheckResult.state);
CommandResult historyCheckError = checkHistory(); CommandResult historyCheckError = checkHistory();
if (historyCheckError != null) {
return historyCheckError; return historyCheckError;
}
} else { } else {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now); TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);

View file

@ -61,7 +61,7 @@ public class RuffyScripter implements RuffyCommands {
private final Object screenlock = new Object(); private final Object screenlock = new Object();
private IRTHandler mHandler = new IRTHandler.Stub() { private final IRTHandler mHandler = new IRTHandler.Stub() {
@Override @Override
public void log(String message) { public void log(String message) {
if (log.isTraceEnabled()) { if (log.isTraceEnabled()) {
@ -667,7 +667,7 @@ public class RuffyScripter implements RuffyCommands {
synchronized (screenlock) { synchronized (screenlock) {
try { try {
// updates usually come in every ~500, occasionally up to 1100ms // updates usually come in every ~500, occasionally up to 1100ms
screenlock.wait((long) 2000); screenlock.wait(2000);
} catch (InterruptedException e) { } catch (InterruptedException e) {
throw new CommandException("Interrupted"); throw new CommandException("Interrupted");
} }

View file

@ -21,7 +21,7 @@ import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tbr;
import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd;
public class ReadHistoryCommand extends BaseCommand { public class ReadHistoryCommand extends BaseCommand {
private static Logger log = StacktraceLoggerWrapper.getLogger(ReadHistoryCommand.class); private static final Logger log = StacktraceLoggerWrapper.getLogger(ReadHistoryCommand.class);
private final PumpHistoryRequest request; private final PumpHistoryRequest request;
private final PumpHistory history = new PumpHistory(); private final PumpHistory history = new PumpHistory();

View file

@ -44,11 +44,11 @@ public class InsightAlertService extends DaggerService implements InsightConnect
private static final int NOTIFICATION_ID = 31345; private static final int NOTIFICATION_ID = 31345;
private LocalBinder localBinder = new LocalBinder(); private final LocalBinder localBinder = new LocalBinder();
private boolean connectionRequested; private boolean connectionRequested;
private final Object $alertLock = new Object[0]; private final Object $alertLock = new Object[0];
private Alert alert = null; private Alert alert = null;
private MutableLiveData<Alert> alertLiveData = new MutableLiveData<>(); private final MutableLiveData<Alert> alertLiveData = new MutableLiveData<>();
private Thread thread; private Thread thread;
private Vibrator vibrator; private Vibrator vibrator;
private boolean vibrating; private boolean vibrating;
@ -56,7 +56,7 @@ public class InsightAlertService extends DaggerService implements InsightConnect
private long ignoreTimestamp; private long ignoreTimestamp;
private AlertType ignoreType; private AlertType ignoreType;
private ServiceConnection serviceConnection = new ServiceConnection() { private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder binder) { public void onServiceConnected(ComponentName name, IBinder binder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService(); connectionService = ((InsightConnectionService.LocalBinder) binder).getService();

View file

@ -46,7 +46,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@Inject DateUtil dateUtil; @Inject DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private static final boolean ENABLE_OPERATING_MODE_BUTTON = false; private static final boolean ENABLE_OPERATING_MODE_BUTTON = false;

View file

@ -157,11 +157,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert";
private PumpDescription pumpDescription; private final PumpDescription pumpDescription;
private InsightAlertService alertService; private InsightAlertService alertService;
private InsightConnectionService connectionService; private InsightConnectionService connectionService;
private long timeOffset; private long timeOffset;
private ServiceConnection serviceConnection = new ServiceConnection() { private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder binder) { public void onServiceConnected(ComponentName name, IBinder binder) {
if (binder instanceof InsightConnectionService.LocalBinder) { if (binder instanceof InsightConnectionService.LocalBinder) {
@ -219,6 +219,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
DateUtil dateUtil DateUtil dateUtil
) { ) {
super(new PluginDescription() super(new PluginDescription()
.pluginIcon(R.drawable.ic_insight)
.pluginName(R.string.insight_local) .pluginName(R.string.insight_local)
.shortName(R.string.insightpump_shortname) .shortName(R.string.insightpump_shortname)
.mainType(PluginType.PUMP) .mainType(PluginType.PUMP)

View file

@ -37,7 +37,7 @@ public class InsightAlertActivity extends DaggerAppCompatActivity {
private Button mute; private Button mute;
private Button confirm; private Button confirm;
private ServiceConnection serviceConnection = new ServiceConnection() { private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder binder) { public void onServiceConnected(ComponentName name, IBinder binder) {
alertService = ((InsightAlertService.LocalBinder) binder).getService(); alertService = ((InsightAlertService.LocalBinder) binder).getService();

View file

@ -43,11 +43,11 @@ public class InsightPairingActivity extends NoSplashAppCompatActivity implements
private TextView code; private TextView code;
private Button exit; private Button exit;
private RecyclerView deviceList; private RecyclerView deviceList;
private DeviceAdapter deviceAdapter = new DeviceAdapter(); private final DeviceAdapter deviceAdapter = new DeviceAdapter();
private InsightConnectionService service; private InsightConnectionService service;
private ServiceConnection serviceConnection = new ServiceConnection() { private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder binder) { public void onServiceConnected(ComponentName name, IBinder binder) {
service = ((InsightConnectionService.LocalBinder) binder).getService(); service = ((InsightConnectionService.LocalBinder) binder).getService();
@ -199,7 +199,7 @@ public class InsightPairingActivity extends NoSplashAppCompatActivity implements
service.pair(device.getAddress()); service.pair(device.getAddress());
} }
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
String action = intent.getAction(); String action = intent.getAction();
@ -214,7 +214,7 @@ public class InsightPairingActivity extends NoSplashAppCompatActivity implements
private class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> { private class DeviceAdapter extends RecyclerView.Adapter<DeviceAdapter.ViewHolder> {
private List<BluetoothDevice> bluetoothDevices = new ArrayList<>(); private final List<BluetoothDevice> bluetoothDevices = new ArrayList<>();
public void addDevice(BluetoothDevice bluetoothDevice) { public void addDevice(BluetoothDevice bluetoothDevice) {
if (!bluetoothDevices.contains(bluetoothDevice)) { if (!bluetoothDevices.contains(bluetoothDevice)) {
@ -248,7 +248,7 @@ public class InsightPairingActivity extends NoSplashAppCompatActivity implements
public class ViewHolder extends RecyclerView.ViewHolder { public class ViewHolder extends RecyclerView.ViewHolder {
private TextView deviceName; private final TextView deviceName;
public ViewHolder(View itemView) { public ViewHolder(View itemView) {
super(itemView); super(itemView);

View file

@ -29,7 +29,7 @@ public class InsightPairingInformationActivity extends NoSplashAppCompatActivity
private TextView systemIdAppendix; private TextView systemIdAppendix;
private TextView manufacturingDate; private TextView manufacturingDate;
private ServiceConnection serviceConnection = new ServiceConnection() { private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override @Override
public void onServiceConnected(ComponentName name, IBinder binder) { public void onServiceConnected(ComponentName name, IBinder binder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService(); connectionService = ((InsightConnectionService.LocalBinder) binder).getService();

View file

@ -9,7 +9,7 @@ public enum Service {
PARAMETER((short) 0x0200, null), PARAMETER((short) 0x0200, null),
REMOTE_CONTROL((short) 0x0100, "MAbcV2X6PVjxuz+R"); REMOTE_CONTROL((short) 0x0100, "MAbcV2X6PVjxuz+R");
private short version; private final short version;
private String servicePassword; private String servicePassword;
Service(short version, String servicePassword) { Service(short version, String servicePassword) {

View file

@ -6,8 +6,8 @@ import info.nightscout.androidaps.plugins.pump.insight.app_layer.configuration.O
public class ConfigurationMessageRequest<T extends AppLayerMessage> extends MessageRequest<T> { public class ConfigurationMessageRequest<T extends AppLayerMessage> extends MessageRequest<T> {
private MessageRequest<OpenConfigurationWriteSessionMessage> openRequest; private final MessageRequest<OpenConfigurationWriteSessionMessage> openRequest;
private MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest; private final MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest;
public ConfigurationMessageRequest(T request, MessageRequest<OpenConfigurationWriteSessionMessage> openRequest, MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest) { public ConfigurationMessageRequest(T request, MessageRequest<OpenConfigurationWriteSessionMessage> openRequest, MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest) {
super(request); super(request);

View file

@ -95,29 +95,29 @@ public class InsightConnectionService extends DaggerService implements Connectio
private static final int TIMEOUT_DURING_HANDSHAKE_NOTIFICATION_THRESHOLD = 3; private static final int TIMEOUT_DURING_HANDSHAKE_NOTIFICATION_THRESHOLD = 3;
private static final long RESPONSE_TIMEOUT = 6000; private static final long RESPONSE_TIMEOUT = 6000;
private List<StateCallback> stateCallbacks = new ArrayList<>(); private final List<StateCallback> stateCallbacks = new ArrayList<>();
private final List<Object> connectionRequests = new ArrayList<>(); private final List<Object> connectionRequests = new ArrayList<>();
private List<ExceptionCallback> exceptionCallbacks = new ArrayList<>(); private final List<ExceptionCallback> exceptionCallbacks = new ArrayList<>();
private LocalBinder localBinder = new LocalBinder(); private final LocalBinder localBinder = new LocalBinder();
private PairingDataStorage pairingDataStorage; private PairingDataStorage pairingDataStorage;
private InsightState state; private InsightState state;
private PowerManager.WakeLock wakeLock; private PowerManager.WakeLock wakeLock;
private DelayedActionThread disconnectTimer; private DelayedActionThread disconnectTimer;
private DelayedActionThread recoveryTimer; private DelayedActionThread recoveryTimer;
private DelayedActionThread timeoutTimer; private DelayedActionThread timeoutTimer;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); private final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothDevice bluetoothDevice; private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket; private BluetoothSocket bluetoothSocket;
private ConnectionEstablisher connectionEstablisher; private ConnectionEstablisher connectionEstablisher;
private InputStreamReader inputStreamReader; private InputStreamReader inputStreamReader;
private OutputStreamWriter outputStreamWriter; private OutputStreamWriter outputStreamWriter;
private KeyRequest keyRequest; private KeyRequest keyRequest;
private ByteBuf buffer = new ByteBuf(BUFFER_SIZE); private final ByteBuf buffer = new ByteBuf(BUFFER_SIZE);
private String verificationString; private String verificationString;
private KeyPair keyPair; private KeyPair keyPair;
private byte[] randomBytes; private byte[] randomBytes;
private MessageQueue messageQueue = new MessageQueue(); private final MessageQueue messageQueue = new MessageQueue();
private List<info.nightscout.androidaps.plugins.pump.insight.app_layer.Service> activatedServices = new ArrayList<>(); private final List<info.nightscout.androidaps.plugins.pump.insight.app_layer.Service> activatedServices = new ArrayList<>();
private long lastDataTime; private long lastDataTime;
private long lastConnected; private long lastConnected;
private long recoveryDuration = 0; private long recoveryDuration = 0;

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.insight.exceptions;
public class ConnectionFailedException extends InsightException { public class ConnectionFailedException extends InsightException {
private long durationOfConnectionAttempt; private final long durationOfConnectionAttempt;
public ConnectionFailedException(long durationOfConnectionAttempt) { public ConnectionFailedException(long durationOfConnectionAttempt) {
this.durationOfConnectionAttempt = durationOfConnectionAttempt; this.durationOfConnectionAttempt = durationOfConnectionAttempt;

View file

@ -4,7 +4,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.AppLayerExcept
public abstract class AppLayerErrorException extends AppLayerException { public abstract class AppLayerErrorException extends AppLayerException {
private int errorCode; private final int errorCode;
public AppLayerErrorException(int errorCode) { public AppLayerErrorException(int errorCode) {
this.errorCode = errorCode; this.errorCode = errorCode;

View file

@ -148,8 +148,7 @@ public abstract class SatlMessage {
public static boolean hasCompletePacket(ByteBuf byteBuf) { public static boolean hasCompletePacket(ByteBuf byteBuf) {
if (byteBuf.getSize() < 37) return false; if (byteBuf.getSize() < 37) return false;
if (byteBuf.getSize() < byteBuf.getUInt16LE(4) + 8) return false; return byteBuf.getSize() >= byteBuf.getUInt16LE(4) + 8;
return true;
} }
public Nonce getNonce() { public Nonce getNonce() {

View file

@ -6,7 +6,7 @@ import java.nio.charset.StandardCharsets;
public class ByteBuf { public class ByteBuf {
private byte[] bytes; private final byte[] bytes;
private int size = 0; private int size = 0;
public ByteBuf(int length) { public ByteBuf(int length) {

View file

@ -10,10 +10,10 @@ import java.util.UUID;
public class ConnectionEstablisher extends Thread { public class ConnectionEstablisher extends Thread {
private Callback callback; private final Callback callback;
private boolean forPairing; private final boolean forPairing;
private BluetoothAdapter bluetoothAdapter; private final BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice; private final BluetoothDevice bluetoothDevice;
private BluetoothSocket socket; private BluetoothSocket socket;
public ConnectionEstablisher(Callback callback, boolean forPairing, BluetoothAdapter bluetoothAdapter, BluetoothDevice bluetoothDevice, BluetoothSocket socket) { public ConnectionEstablisher(Callback callback, boolean forPairing, BluetoothAdapter bluetoothAdapter, BluetoothDevice bluetoothDevice, BluetoothSocket socket) {

View file

@ -2,8 +2,8 @@ package info.nightscout.androidaps.plugins.pump.insight.utils;
public class DelayedActionThread extends Thread { public class DelayedActionThread extends Thread {
private long duration; private final long duration;
private Runnable runnable; private final Runnable runnable;
private DelayedActionThread(String name, long duration, Runnable runnable) { private DelayedActionThread(String name, long duration, Runnable runnable) {
setName(name); setName(name);

View file

@ -5,8 +5,8 @@ import java.util.Map;
public class IDStorage<T, I> { public class IDStorage<T, I> {
private Map<T, I> types = new HashMap<>(); private final Map<T, I> types = new HashMap<>();
private Map<I, T> ids = new HashMap<>(); private final Map<I, T> ids = new HashMap<>();
public void put(T type, I id) { public void put(T type, I id) {
types.put(type, id); types.put(type, id);

View file

@ -7,8 +7,8 @@ public class InputStreamReader extends Thread {
private static final int BUFFER_SIZE = 1024; private static final int BUFFER_SIZE = 1024;
private InputStream inputStream; private final InputStream inputStream;
private Callback callback; private final Callback callback;
public InputStreamReader(InputStream inputStream, Callback callback) { public InputStreamReader(InputStream inputStream, Callback callback) {
setName(getClass().getSimpleName()); setName(getClass().getSimpleName());

View file

@ -7,8 +7,8 @@ public class OutputStreamWriter extends Thread {
private static final int BUFFER_SIZE = 1024; private static final int BUFFER_SIZE = 1024;
private OutputStream outputStream; private final OutputStream outputStream;
private Callback callback; private final Callback callback;
private final ByteBuf buffer = new ByteBuf(BUFFER_SIZE); private final ByteBuf buffer = new ByteBuf(BUFFER_SIZE);
public OutputStreamWriter(OutputStream outputStream, Callback callback) { public OutputStreamWriter(OutputStream outputStream, Callback callback) {

View file

@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.pump.insight.descriptors.SystemIdentif
public class PairingDataStorage { public class PairingDataStorage {
private SharedPreferences preferences; private final SharedPreferences preferences;
private boolean paired; private boolean paired;
private String macAddress; private String macAddress;

View file

@ -43,8 +43,8 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper;
@Singleton @Singleton
public class MDIPlugin extends PumpPluginBase implements PumpInterface { public class MDIPlugin extends PumpPluginBase implements PumpInterface {
private TreatmentsPlugin treatmentsPlugin; private final TreatmentsPlugin treatmentsPlugin;
private PumpDescription pumpDescription = new PumpDescription(); private final PumpDescription pumpDescription = new PumpDescription();
@Inject @Inject
public MDIPlugin( public MDIPlugin(

View file

@ -42,8 +42,8 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton @Singleton
public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin {
private ProfileFunction profileFunction; private final ProfileFunction profileFunction;
private DateUtil dateUtil; private final DateUtil dateUtil;
@Inject @Inject
public SensitivityAAPSPlugin( public SensitivityAAPSPlugin(

View file

@ -36,9 +36,9 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
@Singleton @Singleton
public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin {
private SP sp; private final SP sp;
private DateUtil dateUtil; private final DateUtil dateUtil;
private ProfileFunction profileFunction; private final ProfileFunction profileFunction;
@Inject @Inject
public SensitivityWeightedAveragePlugin( public SensitivityWeightedAveragePlugin(

View file

@ -46,7 +46,7 @@ class XdripPlugin @Inject constructor(
bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME) bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME)
bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP) bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP)
bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW) bgReading.raw = bundle.getDouble(Intents.EXTRA_RAW)
//if (bundle.containsKey(Intents.EXTRA_SENSOR_BATTERY)) sensorBatteryLevel = bundle.getInt(Intents.EXTRA_SENSOR_BATTERY) if (bundle.containsKey(Intents.EXTRA_SENSOR_BATTERY)) sensorBatteryLevel = bundle.getInt(Intents.EXTRA_SENSOR_BATTERY)
val source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified") val source = bundle.getString(Intents.XDRIP_DATA_SOURCE_DESCRIPTION, "no Source specified")
setSource(source) setSource(source)
MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP") MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP")

View file

@ -66,7 +66,7 @@ public class TreatmentService extends OrmLiteBaseService<DatabaseHelper> {
@Inject DatabaseHelperInterface databaseHelper; @Inject DatabaseHelperInterface databaseHelper;
@Inject OpenHumansUploader openHumansUploader; @Inject OpenHumansUploader openHumansUploader;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor(); private static final ScheduledExecutorService treatmentEventWorker = Executors.newSingleThreadScheduledExecutor();
private static ScheduledFuture<?> scheduledTreatmentEventPost = null; private static ScheduledFuture<?> scheduledTreatmentEventPost = null;

View file

@ -80,7 +80,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface
private final FabricPrivacy fabricPrivacy; private final FabricPrivacy fabricPrivacy;
private final DateUtil dateUtil; private final DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
protected TreatmentService service; protected TreatmentService service;

View file

@ -52,7 +52,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment {
@Inject FabricPrivacy fabricPrivacy; @Inject FabricPrivacy fabricPrivacy;
@Inject DateUtil dateUtil; @Inject DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable(); private final CompositeDisposable disposable = new CompositeDisposable();
private RecyclerView recyclerView; private RecyclerView recyclerView;

View file

@ -24,12 +24,12 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP;
*/ */
public class QueueThread extends Thread { public class QueueThread extends Thread {
private CommandQueue queue; private final CommandQueue queue;
private AAPSLogger aapsLogger; private final AAPSLogger aapsLogger;
private RxBusWrapper rxBus; private final RxBusWrapper rxBus;
private ActivePluginProvider activePlugin; private final ActivePluginProvider activePlugin;
private ResourceHelper resourceHelper; private final ResourceHelper resourceHelper;
private SP sp; private final SP sp;
private boolean connectLogged = false; private boolean connectLogged = false;
boolean waitingForDisconnect = false; boolean waitingForDisconnect = false;

View file

@ -69,7 +69,7 @@ public class DataService extends DaggerIntentService {
aapsLogger.debug(LTag.DATASERVICE, "onHandleIntent " + BundleLogger.log(intent.getExtras())); aapsLogger.debug(LTag.DATASERVICE, "onHandleIntent " + BundleLogger.log(intent.getExtras()));
boolean acceptNSData = !sp.getBoolean(R.string.key_ns_upload_only, true); boolean acceptNSData = !sp.getBoolean(R.string.key_ns_upload_only, true) || config.getNSCLIENT();
final String action = intent.getAction(); final String action = intent.getAction();
if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) {

View file

@ -2,19 +2,15 @@ package info.nightscout.androidaps.setupwizard
import android.Manifest import android.Manifest
import android.content.Context import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config import info.nightscout.androidaps.Config
import info.nightscout.androidaps.Constants import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.dialogs.ProfileSwitchDialog
import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
@ -37,8 +33,6 @@ import info.nightscout.androidaps.setupwizard.events.EventSWUpdate
import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.AndroidPermission
import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.utils.CryptoUtil
import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.extensions.isRunningTest
import info.nightscout.androidaps.utils.locale.LocaleHelper.update
import info.nightscout.androidaps.utils.protection.ProtectionCheck
import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP import info.nightscout.androidaps.utils.sharedPreferences.SP
import java.util.* import java.util.*
@ -61,7 +55,6 @@ class SWDefinition @Inject constructor(
private val loopPlugin: LoopPlugin, private val loopPlugin: LoopPlugin,
private val nsClientPlugin: NSClientPlugin, private val nsClientPlugin: NSClientPlugin,
private val nsProfilePlugin: NSProfilePlugin, private val nsProfilePlugin: NSProfilePlugin,
private val protectionCheck: ProtectionCheck,
private val importExportPrefs: ImportExportPrefs, private val importExportPrefs: ImportExportPrefs,
private val androidPermission: AndroidPermission, private val androidPermission: AndroidPermission,
private val cryptoUtil: CryptoUtil, private val cryptoUtil: CryptoUtil,
@ -83,16 +76,6 @@ class SWDefinition @Inject constructor(
private val screenSetupWizard = SWScreen(injector, R.string.nav_setupwizard) private val screenSetupWizard = SWScreen(injector, R.string.nav_setupwizard)
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.welcometosetupwizard)) .label(R.string.welcometosetupwizard))
private val screenLanguage = SWScreen(injector, R.string.language)
.skippable(false)
.add(SWRadioButton(injector)
.option(R.array.languagesArray, R.array.languagesValues)
.preferenceId(R.string.key_language).label(R.string.language)
.comment(R.string.setupwizard_language_prompt))
.validator(SWValidator {
update(context)
sp.contains(R.string.key_language)
})
private val screenEula = SWScreen(injector, R.string.end_user_license_agreement) private val screenEula = SWScreen(injector, R.string.end_user_license_agreement)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -100,20 +83,20 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.end_user_license_agreement_i_understand) .text(R.string.end_user_license_agreement_i_understand)
.visibility(SWValidator { !sp.getBoolean(R.string.key_i_understand, false) }) .visibility { !sp.getBoolean(R.string.key_i_understand, false) }
.action(Runnable { .action {
sp.putBoolean(R.string.key_i_understand, true) sp.putBoolean(R.string.key_i_understand, true)
rxBus.send(EventSWUpdate(false)) rxBus.send(EventSWUpdate(false))
})) })
.visibility(SWValidator { !sp.getBoolean(R.string.key_i_understand, false) }) .visibility { !sp.getBoolean(R.string.key_i_understand, false) }
.validator(SWValidator { sp.getBoolean(R.string.key_i_understand, false) }) .validator { sp.getBoolean(R.string.key_i_understand, false) }
private val screenUnits = SWScreen(injector, R.string.units) private val screenUnits = SWScreen(injector, R.string.units)
.skippable(false) .skippable(false)
.add(SWRadioButton(injector) .add(SWRadioButton(injector)
.option(R.array.unitsArray, R.array.unitsValues) .option(R.array.unitsArray, R.array.unitsValues)
.preferenceId(R.string.key_units).label(R.string.units) .preferenceId(R.string.key_units).label(R.string.units)
.comment(R.string.setupwizard_units_prompt)) .comment(R.string.setupwizard_units_prompt))
.validator(SWValidator { sp.contains(R.string.key_units) }) .validator { sp.contains(R.string.key_units) }
private val displaySettings = SWScreen(injector, R.string.wear_display_settings) private val displaySettings = SWScreen(injector, R.string.wear_display_settings)
.skippable(false) .skippable(false)
.add(SWEditNumberWithUnits(injector, Constants.LOWMARK * Constants.MGDL_TO_MMOLL, 3.0, 8.0) .add(SWEditNumberWithUnits(injector, Constants.LOWMARK * Constants.MGDL_TO_MMOLL, 3.0, 8.0)
@ -134,10 +117,10 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.askforpermission) .text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }) .visibility { androidPermission.permissionNotGranted(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, AndroidPermission.CASE_BATTERY) })) .action { androidPermission.askForPermission(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, AndroidPermission.CASE_BATTERY) })
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }) .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }
private val screenPermissionBt = SWScreen(injector, R.string.permission) private val screenPermissionBt = SWScreen(injector, R.string.permission)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -145,10 +128,10 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.askforpermission) .text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION, AndroidPermission.CASE_LOCATION) })) .action { androidPermission.askForPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION, AndroidPermission.CASE_LOCATION) })
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }) .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }
private val screenPermissionStore = SWScreen(injector, R.string.permission) private val screenPermissionStore = SWScreen(injector, R.string.permission)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -156,18 +139,18 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.askforpermission) .text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, AndroidPermission.CASE_STORAGE) })) .action { androidPermission.askForPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, AndroidPermission.CASE_STORAGE) })
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }) .visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }) .validator { !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
private val screenImport = SWScreen(injector, R.string.nav_import) private val screenImport = SWScreen(injector, R.string.nav_import)
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.storedsettingsfound)) .label(R.string.storedsettingsfound))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.nav_import) .text(R.string.nav_import)
.action(Runnable { importExportPrefs.importSharedPreferences(activity) })) .action { importExportPrefs.importSharedPreferences(activity) })
.visibility(SWValidator { importExportPrefs.prefsFileExists() && !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }) .visibility { importExportPrefs.prefsFileExists() && !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
private val screenNsClient = SWScreen(injector, R.string.nsclientinternal_title) private val screenNsClient = SWScreen(injector, R.string.nsclientinternal_title)
.skippable(true) .skippable(true)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -175,22 +158,18 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.enable_nsclient) .text(R.string.enable_nsclient)
.action(Runnable { .action {
nsClientPlugin.setPluginEnabled(PluginType.GENERAL, true) configBuilderPlugin.performPluginSwitch(nsClientPlugin, true, PluginType.GENERAL)
nsClientPlugin.setFragmentVisible(PluginType.GENERAL, true)
configBuilderPlugin.processOnEnabledCategoryChanged(nsClientPlugin, PluginType.GENERAL)
configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange())
rxBus.send(EventSWUpdate(true)) rxBus.send(EventSWUpdate(true))
}) }
.visibility(SWValidator { !nsClientPlugin.isEnabled(PluginType.GENERAL) })) .visibility { !nsClientPlugin.isEnabled(PluginType.GENERAL) })
.add(SWEditUrl(injector) .add(SWEditUrl(injector)
.preferenceId(R.string.key_nsclientinternal_url) .preferenceId(R.string.key_nsclientinternal_url)
.updateDelay(5) .updateDelay(5)
.label(R.string.nsclientinternal_url_title) .label(R.string.nsclientinternal_url_title)
.comment(R.string.nsclientinternal_url_dialogmessage)) .comment(R.string.nsclientinternal_url_dialogmessage))
.add(SWEditString(injector) .add(SWEditString(injector)
.validator(SWTextValidator { text: String -> text.length >= 12 }) .validator { text: String -> text.length >= 12 }
.preferenceId(R.string.key_nsclientinternal_api_secret) .preferenceId(R.string.key_nsclientinternal_api_secret)
.updateDelay(5) .updateDelay(5)
.label(R.string.nsclientinternal_secret_dialogtitle) .label(R.string.nsclientinternal_secret_dialogtitle)
@ -200,9 +179,8 @@ class SWDefinition @Inject constructor(
.label(R.string.status) .label(R.string.status)
.initialStatus(nsClientPlugin.status) .initialStatus(nsClientPlugin.status)
) )
.add(SWBreak(injector)) .validator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth }
.validator(SWValidator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth }) .visibility { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) }
.visibility(SWValidator { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) })
private val screenPatientName = SWScreen(injector, R.string.patient_name) private val screenPatientName = SWScreen(injector, R.string.patient_name)
.skippable(true) .skippable(true)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -219,7 +197,7 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.master_password_summary)) .label(R.string.master_password_summary))
.validator(SWValidator { !cryptoUtil.checkPassword("", sp.getString(R.string.key_master_password, "")) }) .validator { !cryptoUtil.checkPassword("", sp.getString(R.string.key_master_password, "")) }
private val screenAge = SWScreen(injector, R.string.patientage) private val screenAge = SWScreen(injector, R.string.patientage)
.skippable(false) .skippable(false)
.add(SWBreak(injector)) .add(SWBreak(injector))
@ -228,51 +206,28 @@ class SWDefinition @Inject constructor(
.preferenceId(R.string.key_age) .preferenceId(R.string.key_age)
.label(R.string.patientage) .label(R.string.patientage)
.comment(R.string.patientage_summary)) .comment(R.string.patientage_summary))
.validator(SWValidator { sp.contains(R.string.key_age) }) .validator { sp.contains(R.string.key_age) }
private val screenInsulin = SWScreen(injector, R.string.configbuilder_insulin) private val screenInsulin = SWScreen(injector, R.string.configbuilder_insulin)
.skippable(false) .skippable(false)
.add(SWPlugin(injector) .add(SWPlugin(injector, this)
.option(PluginType.INSULIN, R.string.configbuilder_insulin_description) .option(PluginType.INSULIN, R.string.configbuilder_insulin_description)
.makeVisible(false) .makeVisible(false)
.label(R.string.configbuilder_insulin)) .label(R.string.configbuilder_insulin))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.diawarning)) .label(R.string.diawarning))
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.insulinsourcesetup)
.action(Runnable {
val plugin = activePlugin.activeInsulin as PluginBase
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
activity.startActivity(i)
}, null)
})
.visibility(SWValidator { (activePlugin.activeInsulin as PluginBase).preferencesId > 0 }))
private val screenBgSource = SWScreen(injector, R.string.configbuilder_bgsource) private val screenBgSource = SWScreen(injector, R.string.configbuilder_bgsource)
.skippable(false) .skippable(false)
.add(SWPlugin(injector) .add(SWPlugin(injector, this)
.option(PluginType.BGSOURCE, R.string.configbuilder_bgsource_description) .option(PluginType.BGSOURCE, R.string.configbuilder_bgsource_description)
.label(R.string.configbuilder_bgsource)) .label(R.string.configbuilder_bgsource))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.bgsourcesetup)
.action(Runnable {
val plugin = activePlugin.activeBgSource as PluginBase
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
activity.startActivity(i)
}, null)
})
.visibility(SWValidator { (activePlugin.activeBgSource as PluginBase).preferencesId > 0 }))
private val screenProfile = SWScreen(injector, R.string.configbuilder_profile) private val screenProfile = SWScreen(injector, R.string.configbuilder_profile)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.setupwizard_profile_description)) .label(R.string.setupwizard_profile_description))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWPlugin(injector) .add(SWPlugin(injector, this)
.option(PluginType.PROFILE, R.string.configbuilder_profile_description) .option(PluginType.PROFILE, R.string.configbuilder_profile_description)
.label(R.string.configbuilder_profile)) .label(R.string.configbuilder_profile))
private val screenNsProfile = SWScreen(injector, R.string.nsprofile) private val screenNsProfile = SWScreen(injector, R.string.nsprofile)
@ -281,69 +236,54 @@ class SWDefinition @Inject constructor(
.label(R.string.adjustprofileinns)) .label(R.string.adjustprofileinns))
.add(SWFragment(injector, this) .add(SWFragment(injector, this)
.add(NSProfileFragment())) .add(NSProfileFragment()))
.validator(SWValidator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") }) .validator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") }
.visibility(SWValidator { nsProfilePlugin.isEnabled(PluginType.PROFILE) }) .visibility { nsProfilePlugin.isEnabled(PluginType.PROFILE) }
private val screenLocalProfile = SWScreen(injector, R.string.localprofile) private val screenLocalProfile = SWScreen(injector, R.string.localprofile)
.skippable(false) .skippable(false)
.add(SWFragment(injector, this) .add(SWFragment(injector, this)
.add(LocalProfileFragment())) .add(LocalProfileFragment()))
.validator(SWValidator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true }) .validator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true }
.visibility(SWValidator { localProfilePlugin.isEnabled(PluginType.PROFILE) }) .visibility { localProfilePlugin.isEnabled(PluginType.PROFILE) }
private val screenProfileSwitch = SWScreen(injector, R.string.careportal_profileswitch) private val screenProfileSwitch = SWScreen(injector, R.string.careportal_profileswitch)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.profileswitch_ismissing)) .label(R.string.profileswitch_ismissing))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.doprofileswitch) .text(R.string.doprofileswitch)
.action(Runnable { ProfileSwitchDialog().show(activity.supportFragmentManager, "SetupWizard") })) .action { ProfileSwitchDialog().show(activity.supportFragmentManager, "SetupWizard") })
.validator(SWValidator { profileFunction.getProfile() != null }) .validator { profileFunction.getProfile() != null }
.visibility(SWValidator { profileFunction.getProfile() == null }) .visibility { profileFunction.getProfile() == null }
private val screenPump = SWScreen(injector, R.string.configbuilder_pump) private val screenPump = SWScreen(injector, R.string.configbuilder_pump)
.skippable(false) .skippable(false)
.add(SWPlugin(injector) .add(SWPlugin(injector, this)
.option(PluginType.PUMP, R.string.configbuilder_pump_description) .option(PluginType.PUMP, R.string.configbuilder_pump_description)
.label(R.string.configbuilder_pump)) .label(R.string.configbuilder_pump))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.pumpsetup)
.action(Runnable {
val plugin = activePlugin.activePump as PluginBase
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
activity.startActivity(i)
}, null)
})
.visibility(SWValidator { (activePlugin.activePump as PluginBase).preferencesId > 0 }))
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.setupwizard_pump_pump_not_initialized) .label(R.string.setupwizard_pump_pump_not_initialized)
.visibility(SWValidator { !isPumpInitialized() })) .visibility { !isPumpInitialized() })
.add( // Omnipod only .add( // Omnipod only
SWInfotext(injector) SWInfotext(injector)
.label(R.string.setupwizard_pump_waiting_for_riley_link_connection) .label(R.string.setupwizard_pump_waiting_for_riley_link_connection)
.visibility(SWValidator { .visibility {
val activePump = activePlugin.activePump val activePump = activePlugin.activePump
activePump is OmnipodPumpPlugin && !activePump.isRileyLinkReady activePump is OmnipodPumpPlugin && !activePump.isRileyLinkReady
})) })
.add( // Omnipod only .add( // Omnipod only
SWEventListener(injector, EventRileyLinkDeviceStatusChange::class.java) SWEventListener(injector, EventRileyLinkDeviceStatusChange::class.java)
.label(R.string.setupwizard_pump_riley_link_status) .label(R.string.setupwizard_pump_riley_link_status)
.visibility(SWValidator { .visibility { activePlugin.activePump is OmnipodPumpPlugin })
activePlugin.activePump is OmnipodPumpPlugin
}))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.readstatus) .text(R.string.readstatus)
.action(Runnable { commandQueue.readStatus("Clicked connect to pump", null) }) .action { commandQueue.readStatus("Clicked connect to pump", null) }
.visibility(SWValidator { .visibility {
// Hide for Omnipod, because as we don't require a Pod to be paired in the setup wizard, // Hide for Omnipod, because as we don't require a Pod to be paired in the setup wizard,
// Getting the status might not be possible // Getting the status might not be possible
activePlugin.activePump !is OmnipodPumpPlugin activePlugin.activePump !is OmnipodPumpPlugin
}))
.add(SWEventListener(injector, EventPumpStatusChanged::class.java)
.visibility(SWValidator { activePlugin.activePump !is OmnipodPumpPlugin }))
.validator(SWValidator {
isPumpInitialized()
}) })
.add(SWEventListener(injector, EventPumpStatusChanged::class.java)
.visibility { activePlugin.activePump !is OmnipodPumpPlugin })
.validator { isPumpInitialized() }
private fun isPumpInitialized(): Boolean { private fun isPumpInitialized(): Boolean {
val activePump = activePlugin.activePump val activePump = activePlugin.activePump
@ -358,31 +298,20 @@ class SWDefinition @Inject constructor(
.add(SWInfotext(injector) .add(SWInfotext(injector)
.label(R.string.setupwizard_aps_description)) .label(R.string.setupwizard_aps_description))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWPlugin(injector, this)
.option(PluginType.APS, R.string.configbuilder_aps_description)
.label(R.string.configbuilder_aps))
.add(SWBreak(injector))
.add(SWHtmlLink(injector) .add(SWHtmlLink(injector)
.label("https://openaps.readthedocs.io/en/latest/")) .label("https://openaps.readthedocs.io/en/latest/"))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWPlugin(injector)
.option(PluginType.APS, R.string.configbuilder_aps_description)
.label(R.string.configbuilder_aps))
.add(SWButton(injector)
.text(R.string.apssetup)
.action(Runnable {
val plugin = activePlugin.activeAPS as PluginBase
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
activity.startActivity(i)
}, null)
})
.visibility(SWValidator { (activePlugin.activeAPS as PluginBase).preferencesId > 0 }))
.visibility(SWValidator { config.APS })
private val screenApsMode = SWScreen(injector, R.string.apsmode_title) private val screenApsMode = SWScreen(injector, R.string.apsmode_title)
.skippable(false) .skippable(false)
.add(SWRadioButton(injector) .add(SWRadioButton(injector)
.option(R.array.aps_modeArray, R.array.aps_modeValues) .option(R.array.aps_modeArray, R.array.aps_modeValues)
.preferenceId(R.string.key_aps_mode).label(R.string.apsmode_title) .preferenceId(R.string.key_aps_mode).label(R.string.apsmode_title)
.comment(R.string.setupwizard_preferred_aps_mode)) .comment(R.string.setupwizard_preferred_aps_mode))
.validator(SWValidator { sp.contains(R.string.key_aps_mode) }) .validator { sp.contains(R.string.key_aps_mode) }
private val screenLoop = SWScreen(injector, R.string.configbuilder_loop) private val screenLoop = SWScreen(injector, R.string.configbuilder_loop)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -390,17 +319,13 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWButton(injector) .add(SWButton(injector)
.text(R.string.enableloop) .text(R.string.enableloop)
.action(Runnable { .action {
loopPlugin.setPluginEnabled(PluginType.LOOP, true) configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP)
loopPlugin.setFragmentVisible(PluginType.LOOP, true)
configBuilderPlugin.processOnEnabledCategoryChanged(loopPlugin, PluginType.LOOP)
configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange())
rxBus.send(EventSWUpdate(true)) rxBus.send(EventSWUpdate(true))
}) }
.visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) })) .visibility { !loopPlugin.isEnabled(PluginType.LOOP) })
.validator(SWValidator { loopPlugin.isEnabled(PluginType.LOOP) }) .validator { loopPlugin.isEnabled(PluginType.LOOP) }
.visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS }) .visibility { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS }
private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity) private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -408,21 +333,9 @@ class SWDefinition @Inject constructor(
.add(SWHtmlLink(injector) .add(SWHtmlLink(injector)
.label(R.string.setupwizard_sensitivity_url)) .label(R.string.setupwizard_sensitivity_url))
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWPlugin(injector) .add(SWPlugin(injector, this)
.option(PluginType.SENSITIVITY, R.string.configbuilder_sensitivity_description) .option(PluginType.SENSITIVITY, R.string.configbuilder_sensitivity_description)
.label(R.string.configbuilder_sensitivity)) .label(R.string.configbuilder_sensitivity))
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.sensitivitysetup)
.action(Runnable {
val plugin = activePlugin.activeSensitivity as PluginBase
protectionCheck.queryProtection(activity, ProtectionCheck.Protection.PREFERENCES, Runnable {
val i = Intent(activity, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
activity.startActivity(i)
}, null)
})
.visibility(SWValidator { (activePlugin.activeSensitivity as PluginBase).preferencesId > 0 }))
private val getScreenObjectives = SWScreen(injector, R.string.objectives) private val getScreenObjectives = SWScreen(injector, R.string.objectives)
.skippable(false) .skippable(false)
.add(SWInfotext(injector) .add(SWInfotext(injector)
@ -430,8 +343,8 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector)) .add(SWBreak(injector))
.add(SWFragment(injector, this) .add(SWFragment(injector, this)
.add(ObjectivesFragment())) .add(ObjectivesFragment()))
.validator(SWValidator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted }) .validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted }
.visibility(SWValidator { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS }) .visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS }
private fun swDefinitionFull() { // List all the screens here private fun swDefinitionFull() { // List all the screens here
add(screenSetupWizard) add(screenSetupWizard)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.setupwizard.elements package info.nightscout.androidaps.setupwizard.elements
import android.os.Bundle
import android.view.View import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.LinearLayout import android.widget.LinearLayout
@ -7,15 +8,17 @@ import android.widget.RadioButton
import android.widget.RadioGroup import android.widget.RadioGroup
import android.widget.TextView import android.widget.TextView
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.MyPreferenceFragment
import info.nightscout.androidaps.events.EventConfigBuilderChange import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.setupwizard.SWDefinition
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.setupwizard.events.EventSWUpdate
import javax.inject.Inject import javax.inject.Inject
class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) { class SWPlugin(injector: HasAndroidInjector, val definition: SWDefinition) : SWItem(injector, Type.PLUGIN) {
@Inject lateinit var pluginStore: PluginStore @Inject lateinit var pluginStore: PluginStore
@Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin @Inject lateinit var configBuilderPlugin: ConfigBuilderPlugin
@ -25,6 +28,8 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
private var pluginDescription = 0 private var pluginDescription = 0
private var makeVisible = true private var makeVisible = true
private var fragment: MyPreferenceFragment? = null
fun option(pType: PluginType, pluginDescription: Int): SWPlugin { fun option(pType: PluginType, pluginDescription: Int): SWPlugin {
this.pType = pType this.pType = pType
this.pluginDescription = pluginDescription this.pluginDescription = pluginDescription
@ -37,26 +42,30 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
} }
override fun generateDialog(layout: LinearLayout) { override fun generateDialog(layout: LinearLayout) {
var selectedPlugin: PluginBase? = null
val context = layout.context val context = layout.context
radioGroup = RadioGroup(context) radioGroup = RadioGroup(context)
radioGroup?.clearCheck() radioGroup?.clearCheck()
val pluginsInCategory = pluginStore.getSpecificPluginsList(pType!!) val pluginsInCategory = pluginStore.getSpecificPluginsList(pType!!)
radioGroup?.orientation = LinearLayout.VERTICAL radioGroup?.orientation = LinearLayout.VERTICAL
radioGroup?.visibility = View.VISIBLE radioGroup?.visibility = View.VISIBLE
val pdesc = TextView(context) val pDesc = TextView(context)
pdesc.setText(pluginDescription) pDesc.setText(pluginDescription)
var params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) var params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.setMargins(0, 0, 0, 40) params.setMargins(0, 0, 0, 40)
pdesc.layoutParams = params pDesc.layoutParams = params
layout.addView(pdesc) layout.addView(pDesc)
for (i in pluginsInCategory.indices) { for (i in pluginsInCategory.indices) {
val rdbtn = RadioButton(context) val rdBtn = RadioButton(context)
val p = pluginsInCategory[i] val p = pluginsInCategory[i]
rdbtn.id = View.generateViewId() rdBtn.id = View.generateViewId()
rdbtn.text = p.name rdBtn.text = p.name
if (p.isEnabled(pType!!)) rdbtn.isChecked = true if (p.isEnabled(pType!!)) {
rdbtn.tag = p rdBtn.isChecked = true
radioGroup?.addView(rdbtn) selectedPlugin = p
}
rdBtn.tag = p
radioGroup?.addView(rdBtn)
params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.setMargins(80, 0, 0, 0) params.setMargins(80, 0, 0, 0)
val desc = TextView(context) val desc = TextView(context)
@ -73,8 +82,27 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
configBuilderPlugin.storeSettings("SetupWizard") configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange()) rxBus.send(EventConfigBuilderChange())
rxBus.send(EventSWUpdate(false)) rxBus.send(EventSWUpdate(false))
addConfiguration(layout, plugin)
} }
layout.addView(radioGroup) layout.addView(radioGroup)
selectedPlugin?.let { addConfiguration(layout, it) }
super.generateDialog(layout) super.generateDialog(layout)
} }
fun addConfiguration(layout: LinearLayout, plugin: PluginBase) {
if (plugin.preferencesId != -1) {
fragment = MyPreferenceFragment()
fragment?.arguments = Bundle().also { it.putInt("id", plugin.preferencesId) }
definition.activity.supportFragmentManager.beginTransaction().run {
replace(layout.id, fragment!!)
commit()
}
} else {
definition.activity.supportFragmentManager.beginTransaction().run {
if (fragment != null) remove(fragment!!)
fragment = null
commit()
}
}
}
} }

View file

@ -51,7 +51,7 @@ interface SkinInterface {
asLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID asLayoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
if (isTablet) { if (isTablet) {
for (v in listOf<TextView>( for (v in listOf<TextView?>(
view.overview_bg, view.overview_bg,
view.overview_time, view.overview_time,
view.overview_timeagoshort, view.overview_timeagoshort,
@ -60,8 +60,8 @@ interface SkinInterface {
view.overview_basebasal, view.overview_basebasal,
view.overview_extendedbolus, view.overview_extendedbolus,
view.overview_sensitivity view.overview_sensitivity
)) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f) )) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f)
for (v in listOf<TextView>( for (v in listOf<TextView?>(
view.overview_pump, view.overview_pump,
view.overview_openaps, view.overview_openaps,
view.overview_uploader, view.overview_uploader,
@ -72,9 +72,13 @@ interface SkinInterface {
view.careportal_sensorage, view.careportal_sensorage,
view.careportal_pbage, view.careportal_pbage,
view.careportal_batterylevel view.careportal_batterylevel
)) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f) )) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
view.overview_time_llayout.orientation = LinearLayout.HORIZONTAL view.overview_time_llayout?.orientation = LinearLayout.HORIZONTAL
view.overview_timeagoshort.setTextSize(COMPLEX_UNIT_PX, view.overview_time.textSize) view.overview_timeagoshort?.setTextSize(COMPLEX_UNIT_PX, view.overview_time.textSize)
view.overview_delta_large?.visibility = View.VISIBLE
} else {
view.overview_delta_large?.visibility = View.GONE
} }
} }
} }

View file

@ -19,7 +19,7 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
* Created by mike on 11.07.2016. * Created by mike on 11.07.2016.
*/ */
public class JSONFormatter { public class JSONFormatter {
private static Logger log = StacktraceLoggerWrapper.getLogger(JSONFormatter.class); private static final Logger log = StacktraceLoggerWrapper.getLogger(JSONFormatter.class);
public static Spanned format(final String jsonString) { public static Spanned format(final String jsonString) {
final JsonVisitor visitor = new JsonVisitor(1, '\t'); final JsonVisitor visitor = new JsonVisitor(1, '\t');

View file

@ -38,26 +38,26 @@ public class TimeListEdit {
private final int ONEHOURINSECONDS = 60 * 60; private final int ONEHOURINSECONDS = 60 * 60;
private View[] intervals = new View[24]; private final View[] intervals = new View[24];
private SpinnerHelper[] spinners = new SpinnerHelper[24]; private final SpinnerHelper[] spinners = new SpinnerHelper[24];
private NumberPicker[] numberPickers1 = new NumberPicker[24]; private final NumberPicker[] numberPickers1 = new NumberPicker[24];
private NumberPicker[] numberPickers2 = new NumberPicker[24]; private final NumberPicker[] numberPickers2 = new NumberPicker[24];
private ImageView[] addButtons = new ImageView[24]; private final ImageView[] addButtons = new ImageView[24];
private ImageView[] removeButtons = new ImageView[24]; private final ImageView[] removeButtons = new ImageView[24];
private ImageView finalAdd; private ImageView finalAdd;
private Context context; private final Context context;
private View view; private final View view;
private int resLayoutId; private final int resLayoutId;
private String tagPrefix; private final String tagPrefix;
private String label; private String label;
private JSONArray data1; private final JSONArray data1;
private JSONArray data2; private final JSONArray data2;
private double step; private final double step;
private double min; private final double min;
private double max; private final double max;
private NumberFormat formatter; private final NumberFormat formatter;
private Runnable save; private final Runnable save;
private LinearLayout layout; private LinearLayout layout;
private TextView textlabel; private TextView textlabel;
private int inflatedUntil = -1; private int inflatedUntil = -1;

View file

@ -53,7 +53,7 @@ object PrefImportSummaryDialog {
for ((metaKey, metaEntry) in prefs.metadata) { for ((metaKey, metaEntry) in prefs.metadata) {
val rowLayout = LayoutInflater.from(themedCtx).inflate(R.layout.import_summary_item, null) val rowLayout = LayoutInflater.from(themedCtx).inflate(R.layout.import_summary_item, null)
val label = (rowLayout.findViewById<View>(R.id.summary_text) as TextView) val label = (rowLayout.findViewById<View>(R.id.summary_text) as TextView)
label.setText(metaKey.formatForDisplay(context, metaEntry.value)) label.text = metaKey.formatForDisplay(context, metaEntry.value)
(rowLayout.findViewById<View>(R.id.summary_icon) as ImageView).setImageResource(metaKey.icon) (rowLayout.findViewById<View>(R.id.summary_icon) as ImageView).setImageResource(metaKey.icon)
(rowLayout.findViewById<View>(R.id.status_icon) as ImageView).setImageResource(metaEntry.status.icon) (rowLayout.findViewById<View>(R.id.status_icon) as ImageView).setImageResource(metaEntry.status.icon)
@ -84,9 +84,9 @@ object PrefImportSummaryDialog {
detailsBtn.setOnClickListener { detailsBtn.setOnClickListener {
val detailsLayout = LayoutInflater.from(context).inflate(R.layout.import_summary_details, null) val detailsLayout = LayoutInflater.from(context).inflate(R.layout.import_summary_details, null)
val wview = detailsLayout.findViewById<View>(R.id.details_webview) as WebView val wview = detailsLayout.findViewById<View>(R.id.details_webview) as WebView
wview.loadData("<!doctype html><html><head><meta charset=\"utf-8\"><style>body { color: white; }</style></head><body>" + details.joinToString("<hr>"), "text/html; charset=utf-8", "utf-8"); wview.loadData("<!doctype html><html><head><meta charset=\"utf-8\"><style>body { color: white; }</style></head><body>" + details.joinToString("<hr>"), "text/html; charset=utf-8", "utf-8")
wview.setBackgroundColor(Color.TRANSPARENT); wview.setBackgroundColor(Color.TRANSPARENT)
wview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null); wview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
AlertDialogHelper.Builder(context, R.style.AppTheme) AlertDialogHelper.Builder(context, R.style.AppTheme)
.setCustomTitle(AlertDialogHelper.buildCustomTitle( .setCustomTitle(AlertDialogHelper.buildCustomTitle(

View file

@ -68,7 +68,7 @@ class TddCalculator @Inject constructor(
val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t) val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t)
tdd.basal += absoluteRate / 60.0 * 5.0 tdd.basal += absoluteRate / 60.0 * 5.0
if (!activePlugin.activePump.isFakingTempsByExtendedBoluses()) { if (!activePlugin.activePump.isFakingTempsByExtendedBoluses) {
// they are not included in TBRs // they are not included in TBRs
val eb = getExtendedBolusFromHistory(t) val eb = getExtendedBolusFromHistory(t)
val absoluteEbRate = eb?.absoluteRate() ?: 0.0 val absoluteEbRate = eb?.absoluteRate() ?: 0.0

View file

@ -172,7 +172,7 @@ class BolusWizard @Inject constructor(
} }
// Insulin from 15 min trend // Insulin from 15 min trend
glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() glucoseStatus = GlucoseStatus(injector).glucoseStatusData
glucoseStatus?.let { glucoseStatus?.let {
if (useTrend) { if (useTrend) {
trend = it.short_avgdelta trend = it.short_avgdelta

View file

@ -107,7 +107,7 @@ class QuickWizardEntry @Inject constructor(private val injector: HasAndroidInjec
} }
if (loopPlugin.isEnabled(loopPlugin.getType()) && loopPlugin.isSuperBolus) superBolus = false if (loopPlugin.isEnabled(loopPlugin.getType()) && loopPlugin.isSuperBolus) superBolus = false
// Trend // Trend
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData() val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
var trend = false var trend = false
if (useTrend() == YES) { if (useTrend() == YES) {
trend = true trend = true

View file

@ -19,8 +19,8 @@ import java.util.Map;
*/ */
public class Menu implements Parcelable{ public class Menu implements Parcelable{
private MenuType type; private final MenuType type;
private Map<MenuAttribute,Object> attributes = new HashMap<>(); private final Map<MenuAttribute,Object> attributes = new HashMap<>();
public Menu(MenuType type) public Menu(MenuType type)
{ {
@ -53,7 +53,7 @@ public class Menu implements Parcelable{
} else if (BolusType.class.toString().equals(clas)) { } else if (BolusType.class.toString().equals(clas)) {
o = BolusType.valueOf(value); o = BolusType.valueOf(value);
} else if (String.class.toString().equals(clas)) { } else if (String.class.toString().equals(clas)) {
o = new String(value); o = value;
} }
if (o != null) { if (o != null) {

View file

@ -1,9 +0,0 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="48dp"
android:height="48dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:pathData="M18.71,11.606h-0.736c-0.198,-3.001 -2.579,-5.382 -5.58,-5.58V5.29c0,-0.218 -0.177,-0.394 -0.394,-0.394s-0.394,0.177 -0.394,0.394v0.736c-3.001,0.198 -5.382,2.579 -5.58,5.58H5.29c-0.218,0 -0.394,0.177 -0.394,0.394s0.177,0.394 0.394,0.394h0.736c0.198,3.001 2.579,5.382 5.58,5.58v0.736c0,0.217 0.177,0.394 0.394,0.394s0.394,-0.177 0.394,-0.394v-0.736c3.001,-0.198 5.382,-2.579 5.58,-5.58h0.736c0.217,0 0.394,-0.177 0.394,-0.394S18.927,11.606 18.71,11.606zM17.143,11.606h-1.944c-0.179,-1.478 -1.331,-2.643 -2.804,-2.841V6.85C14.939,7.044 16.953,9.06 17.143,11.606zM13.542,12.394h0.938c-0.171,1.079 -1.01,1.93 -2.085,2.115v-0.967c0,-0.217 -0.177,-0.394 -0.394,-0.394s-0.394,0.177 -0.394,0.394v0.975c-1.111,-0.156 -1.988,-1.017 -2.163,-2.122h1.016c0.218,0 0.394,-0.177 0.394,-0.394s-0.177,-0.394 -0.394,-0.394H9.442c0.171,-1.111 1.049,-1.978 2.164,-2.134v0.987c0,0.218 0.177,0.394 0.394,0.394s0.394,-0.177 0.394,-0.394v-0.98c1.079,0.185 1.92,1.041 2.086,2.126h-0.939c-0.217,0 -0.394,0.177 -0.394,0.394S13.324,12.394 13.542,12.394zM11.606,6.851v1.906C10.095,8.921 8.903,10.1 8.72,11.606H6.864C7.053,9.062 9.064,7.047 11.606,6.851zM6.866,12.394H8.72c0.183,1.505 1.374,2.684 2.885,2.849v1.884C9.071,16.931 7.065,14.928 6.866,12.394zM12.394,17.128v-1.893c1.473,-0.197 2.625,-1.362 2.804,-2.841h1.942C16.941,14.93 14.932,16.935 12.394,17.128z"
android:fillColor="#36FF00"/>
</vector>

Some files were not shown because too many files have changed in this diff Show more