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

View file

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

View file

@ -7,9 +7,6 @@ import android.content.SharedPreferences.OnSharedPreferenceChangeListener
import android.os.Bundle
import androidx.annotation.XmlRes
import androidx.preference.*
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
@ -58,7 +55,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import javax.inject.Inject
class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener, HasAndroidInjector {
class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChangeListener {
private var pluginId = -1
private var filter = ""
@ -103,11 +100,6 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
@Inject lateinit var nsSettingStatus: NSSettingsStatus
@Inject lateinit var openHumansUploader: OpenHumansUploader
// TODO why?
@Inject lateinit var androidInjector: DispatchingAndroidInjector<Any>
override fun androidInjector(): AndroidInjector<Any> = androidInjector
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
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)
}
@ -426,7 +418,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
return super.onPreferenceTreeClick(preference)
}
public fun setFilter(filter: String) {
fun setFilter(filter: String) {
this.filter = filter
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.resources.ResourceHelper
import kotlinx.android.synthetic.main.activity_preferences.*
import kotlinx.android.synthetic.main.local_insight_status_item.view.*
import javax.inject.Inject
class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompat.OnPreferenceStartScreenCallback {
@ -33,10 +32,6 @@ class PreferencesActivity : NoSplashAppCompatActivity(), PreferenceFragmentCompa
override fun afterTextChanged(s: Editable) {}
})
pref_filter_clear.setOnClickListener() {
pref_filter.setText("");
}
title = resourceHelper.gs(R.string.nav_preferences)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)

View file

@ -39,6 +39,7 @@ abstract class AutomationModule {
@ContributesAndroidInjector abstract fun actionLoopResumeInjector(): ActionLoopResume
@ContributesAndroidInjector abstract fun actionLoopSuspendInjector(): ActionLoopSuspend
@ContributesAndroidInjector abstract fun actionNotificationInjector(): ActionNotification
@ContributesAndroidInjector abstract fun actionAlarmInjector(): ActionAlarm
@ContributesAndroidInjector abstract fun actionProfileSwitchInjector(): ActionProfileSwitch
@ContributesAndroidInjector abstract fun actionProfileSwitchPercentInjector(): ActionProfileSwitchPercent
@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())
val bgTextWatcher: TextWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {}

View file

@ -52,7 +52,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
overview_profileswitch_duration.setParams(savedInstanceState?.getDouble("overview_profileswitch_duration")
?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok)
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")
?: 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.android.HasAndroidInjector;
import info.nightscout.androidaps.BuildConfig;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainActivity;
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.bus.RxBusWrapper;
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.EventNewNotification;
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.iob.iobCobCalculator.IobCobCalculatorPlugin;
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 NSUpload nsUpload;
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";
@ -126,6 +126,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
AAPSLogger aapsLogger,
RxBusWrapper rxBus,
SP sp,
Config config,
ConstraintChecker constraintChecker,
ResourceHelper resourceHelper,
ProfileFunction profileFunction,
@ -147,6 +148,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
.pluginName(R.string.loop)
.shortName(R.string.loop_shortname)
.preferencesId(R.xml.pref_loop)
.enableByDefault(config.getAPS())
.description(R.string.description_loop),
aapsLogger, resourceHelper, injector
);
@ -415,7 +417,7 @@ public class LoopPlugin extends PluginBase implements LoopInterface {
resultAfterConstraints.smb = 0;
}
if (lastRun != null) {
if (lastRun != null && lastRun.getConstraintsProcessed() != null) {
prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq;
}

View file

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

View file

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

View file

@ -5,12 +5,9 @@ import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.TextView
import android.widget.*
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.Config
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
private val enabledExclusive: RadioButton
private val enabledInclusive: CheckBox
private val pluginIcon: ImageView
private val pluginName: TextView
private val pluginDescription: TextView
private val pluginPreferences: ImageButton
@ -137,6 +135,7 @@ class ConfigBuilderFragment : DaggerFragment() {
init {
enabledExclusive = baseView.findViewById(R.id.plugin_enabled_exclusive)
enabledInclusive = baseView.findViewById(R.id.plugin_enabled_inclusive)
pluginIcon = baseView.findViewById(R.id.plugin_icon)
pluginName = baseView.findViewById(R.id.plugin_name)
pluginDescription = baseView.findViewById(R.id.plugin_description)
pluginPreferences = baseView.findViewById(R.id.plugin_preferences)
@ -175,6 +174,12 @@ class ConfigBuilderFragment : DaggerFragment() {
enabledInclusive.isChecked = plugin.isEnabled(pluginType)
enabledInclusive.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
if (plugin.description == null)
pluginDescription.visibility = View.GONE

View file

@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.configBuilder.events
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 ResourceHelper resourceHelper;
private String spName;
@StringRes private int objective;
@StringRes private int gate;
private final String spName;
@StringRes private final int objective;
@StringRes private final int gate;
private long startedOn;
private long accomplishedOn;
List<Task> tasks = new ArrayList<>();
@ -116,7 +116,7 @@ public abstract class Objective {
public abstract class Task {
@StringRes
private int task;
private final int task;
private Objective objective;
ArrayList<Hint> hints = new ArrayList<>();
@ -138,8 +138,6 @@ public abstract class Objective {
return isCompleted();
}
;
public String getProgress() {
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 {
private long minimumDuration;
private final long minimumDuration;
MinimumDurationTask(long minimumDuration) {
super(R.string.time_elapsed);
@ -197,7 +195,7 @@ public abstract class Objective {
@StringRes
int question;
ArrayList<Option> options = new ArrayList<>();
private String spIdentifier;
private final String spIdentifier;
private boolean answered;
private long disabledTo;
@ -274,8 +272,7 @@ public abstract class Objective {
public boolean evaluate() {
boolean selection = cb.isChecked();
if (selection && isCorrect) return true;
if (!selection && !isCorrect) return true;
return false;
return !selection && !isCorrect;
}
}

View file

@ -78,9 +78,7 @@ public class Objective0 extends Objective {
@Override
public boolean isCompleted() {
APSInterface usedAPS = activePlugin.getActiveAPS();
if (((PluginBase) usedAPS).isEnabled(PluginType.APS))
return true;
return false;
return ((PluginBase) usedAPS).isEnabled(PluginType.APS);
}
});
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.plugins.constraints.objectives.ObjectivesPlugin;
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.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
@ -50,7 +51,7 @@ public class Objective3 extends Objective {
@Override
public boolean specialActionEnabled() {
return nsClientPlugin.nsClientService.isConnected && nsClientPlugin.nsClientService.hasWriteAuth;
return NSClientService.isConnected && NSClientService.hasWriteAuth;
}
@Override

View file

@ -36,12 +36,12 @@ class PhoneCheckerPlugin @Inject constructor(
private fun isDevModeEnabled(): Boolean {
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() {
super.onStart()
phoneRooted = RootBeer(context).isRooted()
phoneRooted = RootBeer(context).isRooted
devMode = isDevModeEnabled()
}
}

View file

@ -273,12 +273,13 @@ class ActionsFragment : DaggerFragment() {
private fun checkPumpCustomActions() {
val activePump = activePlugin.activePump
val customActions = activePump.customActions ?: return
val currentContext = context ?: return
removePumpCustomActions()
for (customAction in customActions) {
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)
val layoutParams = LinearLayout.LayoutParams(

View file

@ -15,12 +15,18 @@ import java.util.*
import javax.inject.Inject
class AutomationEvent(private val injector: HasAndroidInjector) {
@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)
val actions: MutableList<Action> = ArrayList()
var title: String? = null
var isEnabled = true
var lastRun: Long = 0
init {
@ -43,6 +49,9 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
return JSONObject()
.put("title", title)
.put("enabled", isEnabled)
.put("systemAction", systemAction)
.put("readOnly", readOnly)
.put("autoRemove", autoRemove)
.put("trigger", trigger.toJSON())
.put("actions", array)
.toString()
@ -52,6 +61,9 @@ class AutomationEvent(private val injector: HasAndroidInjector) {
val d = JSONObject(data)
title = d.optString("title", "")
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")))
?: TriggerConnector(injector)
val array = d.getJSONArray("actions")

View file

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

View file

@ -239,6 +239,7 @@ class AutomationPlugin @Inject constructor(
ActionStartTempTarget(injector),
ActionStopTempTarget(injector),
ActionNotification(injector),
ActionAlarm(injector),
ActionProfileSwitchPercent(injector),
ActionProfileSwitch(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 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) {
activePlugin.activeTreatments.addToHistoryTempTarget(tt())

View file

@ -6,24 +6,30 @@ import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
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.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin
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.EventAutomationUpdateGui
import kotlinx.android.synthetic.main.automation_dialog_choose_action.*
import javax.inject.Inject
import kotlin.reflect.full.primaryConstructor
class ChooseActionDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp : MainApp
@Inject lateinit var mainApp: MainApp
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?,
savedInstanceState: Bundle?): View? {
// restore checked radio button
@ -32,7 +38,8 @@ class ChooseActionDialog : DialogFragmentWithDate() {
}
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?) {
@ -42,11 +49,16 @@ class ChooseActionDialog : DialogFragmentWithDate() {
val radioButton = RadioButton(context)
radioButton.setText(a.friendlyName())
radioButton.tag = a.javaClass.name
automation_radioGroup.addView(radioButton)
binding.radioGroup.addView(radioButton)
}
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 {
@ -70,16 +82,16 @@ class ChooseActionDialog : DialogFragmentWithDate() {
}
private fun getActionClass(): String? {
val radioButtonID = automation_radioGroup.checkedRadioButtonId
val radioButton = automation_radioGroup.findViewById<RadioButton>(radioButtonID)
val radioButtonID = binding.radioGroup.checkedRadioButtonId
val radioButton = binding.radioGroup.findViewById<RadioButton>(radioButtonID)
return radioButton?.let {
it.tag as String
}
}
private fun determineCheckedIndex(): Int {
for (i in 0 until automation_radioGroup.childCount) {
if ((automation_radioGroup.getChildAt(i) as RadioButton).isChecked)
for (i in 0 until binding.radioGroup.childCount) {
if ((binding.radioGroup.getChildAt(i) as RadioButton).isChecked)
return i
}
return -1

View file

@ -6,34 +6,42 @@ import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
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.plugins.general.automation.AutomationPlugin
import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger
import kotlinx.android.synthetic.main.automation_dialog_choose_trigger.*
import javax.inject.Inject
import kotlin.reflect.full.primaryConstructor
class ChooseTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var automationPlugin: AutomationPlugin
@Inject lateinit var mainApp : MainApp
@Inject lateinit var mainApp: MainApp
private var checkedIndex = -1
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 {
fun onClick(newTriggerObject: Trigger)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
// restore checked radio button
savedInstanceState?.let { bundle ->
checkedIndex = bundle.getInt("checkedIndex")
}
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?) {
@ -43,11 +51,16 @@ class ChooseTriggerDialog : DialogFragmentWithDate() {
val radioButton = RadioButton(context)
radioButton.setText(t.friendlyName())
radioButton.tag = t.javaClass.name
automation_chooseTriggerRadioGroup.addView(radioButton)
binding.chooseTriggerRadioGroup.addView(radioButton)
}
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 {
@ -74,16 +87,16 @@ class ChooseTriggerDialog : DialogFragmentWithDate() {
}
private fun getTriggerClass(): String? {
val radioButtonID = automation_chooseTriggerRadioGroup.checkedRadioButtonId
val radioButton = automation_chooseTriggerRadioGroup.findViewById<RadioButton>(radioButtonID)
val radioButtonID = binding.chooseTriggerRadioGroup.checkedRadioButtonId
val radioButton = binding.chooseTriggerRadioGroup.findViewById<RadioButton>(radioButtonID)
return radioButton?.let {
it.tag as String
}
}
private fun determineCheckedIndex(): Int {
for (i in 0 until automation_chooseTriggerRadioGroup.childCount) {
if ((automation_chooseTriggerRadioGroup.getChildAt(i) as RadioButton).isChecked)
for (i in 0 until binding.chooseTriggerRadioGroup.childCount) {
if ((binding.chooseTriggerRadioGroup.getChildAt(i) as RadioButton).isChecked)
return i
}
return -1

View file

@ -5,41 +5,48 @@ import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
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.plugins.bus.RxBusWrapper
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.events.EventAutomationUpdateAction
import kotlinx.android.synthetic.main.automation_dialog_action.*
import org.json.JSONObject
import javax.inject.Inject
class EditActionDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
private var action: Action? = null
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?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
actionPosition = bundle.getInt("actionPosition", -1)
bundle.getString("action")?.let { action = ActionDummy(mainApp).instantiate(JSONObject(it)) }
}
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?) {
super.onViewCreated(view, savedInstanceState)
action?.let {
automation_actionTitle.setText(it.friendlyName())
automation_editActionLayout.removeAllViews()
it.generateDialog(automation_editActionLayout)
binding.actionTitle.setText(it.friendlyName())
binding.editActionLayout.removeAllViews()
it.generateDialog(binding.editActionLayout)
}
}

View file

@ -11,6 +11,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.databinding.AutomationDialogEventBinding
import info.nightscout.androidaps.dialogs.DialogFragmentWithDate
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
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 io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_dialog_event.*
import javax.inject.Inject
class EditEventDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var fabricPrivacy: FabricPrivacy
@ -42,8 +43,14 @@ class EditEventDialog : DialogFragmentWithDate() {
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?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
event = AutomationEvent(mainApp)
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
@ -52,16 +59,17 @@ class EditEventDialog : DialogFragmentWithDate() {
}
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?) {
super.onViewCreated(view, savedInstanceState)
automation_inputEventTitle.setText(event.title)
automation_triggerDescription.text = event.trigger.friendlyDescription()
binding.inputEventTitle.setText(event.title)
binding.triggerDescription.text = event.trigger.friendlyDescription()
automation_editTrigger.setOnClickListener {
binding.editTrigger.setOnClickListener {
val args = Bundle()
args.putString("trigger", event.trigger.toJSON())
val dialog = EditTriggerDialog()
@ -71,10 +79,10 @@ class EditEventDialog : DialogFragmentWithDate() {
// setup action list view
actionListAdapter = ActionListAdapter()
automation_actionListView.layoutManager = LinearLayoutManager(context)
automation_actionListView.adapter = actionListAdapter
binding.actionListView.layoutManager = LinearLayoutManager(context)
binding.actionListView.adapter = actionListAdapter
automation_addAction.setOnClickListener { ChooseActionDialog().show(childFragmentManager, "ChooseActionDialog") }
binding.addAction.setOnClickListener { ChooseActionDialog().show(childFragmentManager, "ChooseActionDialog") }
showPreconditions()
@ -99,7 +107,7 @@ class EditEventDialog : DialogFragmentWithDate() {
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
event.trigger = it.trigger
automation_triggerDescription.text = event.trigger.friendlyDescription()
binding.triggerDescription.text = event.trigger.friendlyDescription()
}, { fabricPrivacy.logException(it) }
)
disposable += rxBus
@ -113,7 +121,7 @@ class EditEventDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
// check for title
val title = automation_inputEventTitle?.text?.toString() ?: return false
val title = binding.inputEventTitle.text?.toString() ?: return false
if (title.isEmpty()) {
ToastUtils.showToastInUiThread(context, R.string.automation_missing_task_name)
return false
@ -143,6 +151,7 @@ class EditEventDialog : DialogFragmentWithDate() {
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()
_binding = null
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
@ -154,12 +163,12 @@ class EditEventDialog : DialogFragmentWithDate() {
private fun showPreconditions() {
val forcedTriggers = event.getPreconditions()
if (forcedTriggers.size() > 0) {
automation_forcedTriggerDescription.visibility = View.VISIBLE
automation_forcedTriggerDescriptionLabel.visibility = View.VISIBLE
automation_forcedTriggerDescription.text = forcedTriggers.friendlyDescription()
binding.forcedTriggerDescription.visibility = View.VISIBLE
binding.forcedTriggerDescriptionLabel.visibility = View.VISIBLE
binding.forcedTriggerDescription.text = forcedTriggers.friendlyDescription()
} else {
automation_forcedTriggerDescription.visibility = View.GONE
automation_forcedTriggerDescriptionLabel.visibility = View.GONE
binding.forcedTriggerDescription.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.ViewGroup
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.plugins.bus.RxBusWrapper
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 io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.automation_dialog_edit_trigger.*
import org.json.JSONObject
import javax.inject.Inject
class EditTriggerDialog : DialogFragmentWithDate() {
@Inject lateinit var rxBus: RxBusWrapper
@Inject lateinit var mainApp: MainApp
@Inject lateinit var fabricPrivacy: FabricPrivacy
@ -32,15 +32,22 @@ class EditTriggerDialog : DialogFragmentWithDate() {
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?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
bundle.getString("trigger")?.let { triggers = TriggerDummy(mainApp).instantiate(JSONObject(it)) }
}
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?) {
@ -50,16 +57,16 @@ class EditTriggerDialog : DialogFragmentWithDate() {
.toObservable(EventTriggerChanged::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
automation_layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger)
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
disposable += rxBus
.toObservable(EventTriggerRemove::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
findParent(triggers, it.trigger)?.list?.remove(it.trigger)
automation_layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger)
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
disposable += rxBus
@ -67,17 +74,18 @@ class EditTriggerDialog : DialogFragmentWithDate() {
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
findParent(triggers, it.trigger)?.list?.add(it.trigger.duplicate())
automation_layoutTrigger.removeAllViews()
triggers?.generateDialog(automation_layoutTrigger)
binding.layoutTrigger.removeAllViews()
triggers?.generateDialog(binding.layoutTrigger)
}, { fabricPrivacy.logException(it) })
// display root trigger
triggers?.generateDialog(automation_layoutTrigger)
triggers?.generateDialog(binding.layoutTrigger)
}
override fun onDestroyView() {
super.onDestroyView()
disposable.clear()
_binding = null
}
override fun submit(): Boolean {

View file

@ -21,7 +21,7 @@ class SimpleItemTouchHelperCallback(private val mAdapter: ItemTouchHelperAdapter
}
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

View file

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

View file

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

View file

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

View file

@ -49,7 +49,7 @@ class FoodFragment : DaggerFragment() {
super.onViewCreated(view, savedInstanceState)
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_clearfilter.setOnClickListener {
@ -69,7 +69,7 @@ class FoodFragment : DaggerFragment() {
filterData()
}
}
food_subcategory.setOnItemSelectedListener(object : AdapterView.OnItemSelectedListener {
food_subcategory.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
filterData()
}
@ -77,7 +77,7 @@ class FoodFragment : DaggerFragment() {
override fun onNothingSelected(parent: AdapterView<*>?) {
filterData()
}
})
}
food_filter.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: 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 FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable();
private final CompositeDisposable disposable = new CompositeDisposable();
private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor();
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)
val importOkCheckedAgain = checkIfImportIsOk(prefsReloaded)
then(prefsReloaded, importOkCheckedAgain);
then(prefsReloaded, importOkCheckedAgain)
}
} 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 ->
@ -335,7 +335,7 @@ class ImportExportPrefs @Inject constructor(
for ((_, value) in prefs.metadata) {
if (value.status == PrefsStatus.ERROR)
importOk = false;
importOk = false
}
return importOk
}

View file

@ -167,10 +167,10 @@ class PrefFileListProvider @Inject constructor(
meta[PrefsMetadataKey.CREATED_AT]?.let { createdAt ->
try {
val date1 = DateTime.parse(createdAt.value);
val date1 = DateTime.parse(createdAt.value)
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) {
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)
}
return metadata;
return metadata
}
}

View file

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

View file

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

View file

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

View file

@ -10,9 +10,9 @@ import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.logging.StacktraceLoggerWrapper;
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)
public NSTreatment(JSONObject obj) {

View file

@ -91,10 +91,10 @@ public class NSClientService extends DaggerService {
@Inject DateUtil dateUtil;
@Inject UploadQueue uploadQueue;
private CompositeDisposable disposable = new CompositeDisposable();
private final CompositeDisposable disposable = new CompositeDisposable();
static public PowerManager.WakeLock mWakeLock;
private IBinder mBinder = new NSClientService.LocalBinder();
private final IBinder mBinder = new NSClientService.LocalBinder();
static ProfileStore profileStore;
@ -123,9 +123,9 @@ public class NSClientService extends DaggerService {
private String nsAPIhashCode = "";
private final ArrayList<Long> reconnections = new ArrayList<>();
private int WATCHDOG_INTERVAL_MINUTES = 2;
private int WATCHDOG_RECONNECT_IN = 15;
private int WATCHDOG_MAXCONNECTIONS = 5;
private final int WATCHDOG_INTERVAL_MINUTES = 2;
private final int WATCHDOG_RECONNECT_IN = 15;
private final int WATCHDOG_MAXCONNECTIONS = 5;
public NSClientService() {
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
public void call(Object... args) {
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
public void call(Object... args) {
aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args);
@ -412,7 +412,7 @@ public class NSClientService extends DaggerService {
nsDevice = sp.getString("careportal_enteredby", "");
}
private Emitter.Listener onError = new Emitter.Listener() {
private final Emitter.Listener onError = new Emitter.Listener() {
@Override
public void call(final Object... args) {
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
public void call(final Object... args) {
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,
@ -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,
@ -482,7 +482,7 @@ public class NSClientService extends DaggerService {
}
};
private Emitter.Listener onUrgentAlarm = args -> {
private final Emitter.Listener onUrgentAlarm = args -> {
JSONObject data;
try {
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,
@ -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
public void call(final Object... args) {
NSClientService.handler.post(() -> {

View file

@ -579,11 +579,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
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_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 {
overview_delta?.text = "Δ " + resourceHelper.gs(R.string.notavailable)
overview_avgdelta?.text = ""
overview_long_avgdelta?.text = ""
}
// strike through if BG is old
@ -608,16 +612,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_superbolus)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
}
loopPlugin.isDisconnected -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_disconnected)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
}
loopPlugin.isEnabled() && loopPlugin.isSuspended -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_paused)
overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper)
overview_apsmode_text?.visibility = View.VISIBLE
}
pump.isSuspended -> {
@ -628,27 +635,27 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
} else {
R.drawable.ic_loop_paused
})
overview_apsmode_text?.text = ""
overview_apsmode_text?.visibility = View.GONE
}
loopPlugin.isEnabled() && closedLoopEnabled.value() && loopPlugin.isLGS -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_lgs)
overview_apsmode_text?.text = ""
overview_apsmode_text?.visibility = View.GONE
}
loopPlugin.isEnabled() && closedLoopEnabled.value() -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_closed)
overview_apsmode_text?.text = ""
overview_apsmode_text?.visibility = View.GONE
}
loopPlugin.isEnabled() && !closedLoopEnabled.value() -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_open)
overview_apsmode_text?.text = ""
overview_apsmode_text?.visibility = View.GONE
}
else -> {
overview_apsmode?.setImageResource(R.drawable.ic_loop_disabled)
overview_apsmode_text?.text = ""
overview_apsmode_text?.visibility = View.GONE
}
}
} else {

View file

@ -33,7 +33,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() {
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 {
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()
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 carbs: TextView = itemView.findViewById(R.id.overview_quickwizard_item_carbs)
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(mSecondPath, paint);
if (mStyles.drawBackground) {
canvas.drawRect((float)startX, (float)startY2, endX, endY1, mPaintBackground);
canvas.drawRect(startX, startY2, endX, endY1, mPaintBackground);
}
} else if (mStyles.drawDataPoints) {
//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 {
private static final long serialVersionUID=1428267322645L;
private double x;
private double y1;
private double y2;
private final double x;
private final double y1;
private final double y2;
public DoubleDataPoint(double x, double y1, double y2) {
this.x=x;

View file

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

View file

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

View file

@ -289,7 +289,7 @@ class SmsCommunicatorPlugin @Inject constructor(
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) + ", "
}
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 + ", "
activePlugin.activeTreatments.updateTotalIOBTreatments()
val bolusIob = activePlugin.activeTreatments.lastCalculationTreatments.round()
@ -350,7 +350,7 @@ class SmsCommunicatorPlugin @Inject constructor(
"STATUS" -> {
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_loopisdisabled)

View file

@ -35,7 +35,7 @@ class SmsCommunicatorOtpActivity : NoSplashAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
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)
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.
*/
class SendToDataLayerThread extends AsyncTask<DataMap,Void,Void> {
private GoogleApiClient googleApiClient;
private final GoogleApiClient googleApiClient;
private static final String TAG = "SendToDataLayerThread";
private String path;
private String logPrefix = ""; // "WR: ";
private final String path;
private final String logPrefix = ""; // "WR: ";
private static int concurrency = 0;
private static int state = 0;
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.resources.ResourceHelper;
import info.nightscout.androidaps.utils.sharedPreferences.SP;
import kotlin.Suppress;
public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
@Inject public HasAndroidInjector injector;
@ -768,8 +769,9 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
// Log.d(TAG, "WR: " + source + " " + data);
}
@SuppressWarnings("UNCHECKED")
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) {
// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// } else {

View file

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

View file

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

View file

@ -72,7 +72,7 @@ public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculat
private final FabricPrivacy fabricPrivacy;
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> 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 IobCobCalculatorPlugin iobCobCalculatorPlugin; // cannot be injected : HistoryBrowser uses different instance
private final TreatmentsPlugin treatmentsPlugin; // cannot be injected : HistoryBrowser uses different instance
private boolean bgDataReload;
private boolean limitDataToOldestAvailable;
private String from;
private long end;
private final boolean bgDataReload;
private final boolean limitDataToOldestAvailable;
private final String from;
private final long end;
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 (autosensData.cob > 0 || autosensData.absorbing || autosensData.mealCarbs > 0) {
if (deviation > 0)
autosensData.absorbing = true;
else
autosensData.absorbing = false;
autosensData.absorbing = deviation > 0;
// stop excluding positive deviations as soon as mealCOB=0 if meal has been absorbing for >5h
if (autosensData.mealStartCounter > 60 && autosensData.cob < 0.5) {
autosensData.absorbing = false;
@ -329,10 +326,7 @@ public class IobCobOref1Thread extends Thread {
//if (iob.iob > currentBasal || uam ) {
if (iob.iob > 2 * currentBasal || autosensData.uam || autosensData.mealStartCounter < 9) {
autosensData.mealStartCounter++;
if (deviation > 0)
autosensData.uam = true;
else
autosensData.uam = false;
autosensData.uam = deviation > 0;
if (!autosensData.type.equals("uam")) {
// process.stderr.write("u(");
}

View file

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

View file

@ -2,5 +2,4 @@ package info.nightscout.androidaps.plugins.profile.local.events
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 FabricPrivacy fabricPrivacy;
private CompositeDisposable disposable = new CompositeDisposable();
private final CompositeDisposable disposable = new CompositeDisposable();
private TextView stateView;
private TextView activityView;

View file

@ -147,6 +147,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
super(new PluginDescription()
.mainType(PluginType.PUMP)
.fragmentClass(ComboFragment.class.getName())
.pluginIcon(R.drawable.ic_combo)
.pluginName(R.string.combopump)
.shortName(R.string.combopump_shortname)
.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;
switch (state) {
case PROGRAMMING:
@ -966,9 +967,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr
checkPumpTime(preCheckResult.state);
checkBasalRate(preCheckResult.state);
CommandResult historyCheckError = checkHistory();
if (historyCheckError != null) {
return historyCheckError;
}
} else {
long now = System.currentTimeMillis();
TemporaryBasal aapsTbr = treatmentsPlugin.getTempBasalFromHistory(now);

View file

@ -61,7 +61,7 @@ public class RuffyScripter implements RuffyCommands {
private final Object screenlock = new Object();
private IRTHandler mHandler = new IRTHandler.Stub() {
private final IRTHandler mHandler = new IRTHandler.Stub() {
@Override
public void log(String message) {
if (log.isTraceEnabled()) {
@ -667,7 +667,7 @@ public class RuffyScripter implements RuffyCommands {
synchronized (screenlock) {
try {
// updates usually come in every ~500, occasionally up to 1100ms
screenlock.wait((long) 2000);
screenlock.wait(2000);
} catch (InterruptedException e) {
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;
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 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 LocalBinder localBinder = new LocalBinder();
private final LocalBinder localBinder = new LocalBinder();
private boolean connectionRequested;
private final Object $alertLock = new Object[0];
private Alert alert = null;
private MutableLiveData<Alert> alertLiveData = new MutableLiveData<>();
private final MutableLiveData<Alert> alertLiveData = new MutableLiveData<>();
private Thread thread;
private Vibrator vibrator;
private boolean vibrating;
@ -56,7 +56,7 @@ public class InsightAlertService extends DaggerService implements InsightConnect
private long ignoreTimestamp;
private AlertType ignoreType;
private ServiceConnection serviceConnection = new ServiceConnection() {
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
connectionService = ((InsightConnectionService.LocalBinder) binder).getService();

View file

@ -46,7 +46,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick
@Inject FabricPrivacy fabricPrivacy;
@Inject DateUtil dateUtil;
private CompositeDisposable disposable = new CompositeDisposable();
private final CompositeDisposable disposable = new CompositeDisposable();
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";
private PumpDescription pumpDescription;
private final PumpDescription pumpDescription;
private InsightAlertService alertService;
private InsightConnectionService connectionService;
private long timeOffset;
private ServiceConnection serviceConnection = new ServiceConnection() {
private final ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
if (binder instanceof InsightConnectionService.LocalBinder) {
@ -219,6 +219,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface,
DateUtil dateUtil
) {
super(new PluginDescription()
.pluginIcon(R.drawable.ic_insight)
.pluginName(R.string.insight_local)
.shortName(R.string.insightpump_shortname)
.mainType(PluginType.PUMP)

View file

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

View file

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

View file

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

View file

@ -9,7 +9,7 @@ public enum Service {
PARAMETER((short) 0x0200, null),
REMOTE_CONTROL((short) 0x0100, "MAbcV2X6PVjxuz+R");
private short version;
private final short version;
private 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> {
private MessageRequest<OpenConfigurationWriteSessionMessage> openRequest;
private MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest;
private final MessageRequest<OpenConfigurationWriteSessionMessage> openRequest;
private final MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest;
public ConfigurationMessageRequest(T request, MessageRequest<OpenConfigurationWriteSessionMessage> openRequest, MessageRequest<CloseConfigurationWriteSessionMessage> closeRequest) {
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 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 List<ExceptionCallback> exceptionCallbacks = new ArrayList<>();
private LocalBinder localBinder = new LocalBinder();
private final List<ExceptionCallback> exceptionCallbacks = new ArrayList<>();
private final LocalBinder localBinder = new LocalBinder();
private PairingDataStorage pairingDataStorage;
private InsightState state;
private PowerManager.WakeLock wakeLock;
private DelayedActionThread disconnectTimer;
private DelayedActionThread recoveryTimer;
private DelayedActionThread timeoutTimer;
private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private ConnectionEstablisher connectionEstablisher;
private InputStreamReader inputStreamReader;
private OutputStreamWriter outputStreamWriter;
private KeyRequest keyRequest;
private ByteBuf buffer = new ByteBuf(BUFFER_SIZE);
private final ByteBuf buffer = new ByteBuf(BUFFER_SIZE);
private String verificationString;
private KeyPair keyPair;
private byte[] randomBytes;
private MessageQueue messageQueue = new MessageQueue();
private List<info.nightscout.androidaps.plugins.pump.insight.app_layer.Service> activatedServices = new ArrayList<>();
private final MessageQueue messageQueue = new MessageQueue();
private final List<info.nightscout.androidaps.plugins.pump.insight.app_layer.Service> activatedServices = new ArrayList<>();
private long lastDataTime;
private long lastConnected;
private long recoveryDuration = 0;

View file

@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.insight.exceptions;
public class ConnectionFailedException extends InsightException {
private long durationOfConnectionAttempt;
private final long durationOfConnectionAttempt;
public ConnectionFailedException(long 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 {
private int errorCode;
private final int errorCode;
public AppLayerErrorException(int errorCode) {
this.errorCode = errorCode;

View file

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

View file

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

View file

@ -10,10 +10,10 @@ import java.util.UUID;
public class ConnectionEstablisher extends Thread {
private Callback callback;
private boolean forPairing;
private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private final Callback callback;
private final boolean forPairing;
private final BluetoothAdapter bluetoothAdapter;
private final BluetoothDevice bluetoothDevice;
private 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 {
private long duration;
private Runnable runnable;
private final long duration;
private final Runnable runnable;
private DelayedActionThread(String name, long duration, Runnable runnable) {
setName(name);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -46,7 +46,7 @@ class XdripPlugin @Inject constructor(
bgReading.direction = bundle.getString(Intents.EXTRA_BG_SLOPE_NAME)
bgReading.date = bundle.getLong(Intents.EXTRA_TIMESTAMP)
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")
setSource(source)
MainApp.getDbHelper().createIfNotExists(bgReading, "XDRIP")

View file

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

View file

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

View file

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

View file

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

View file

@ -69,7 +69,7 @@ public class DataService extends DaggerIntentService {
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();
if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) {

View file

@ -2,19 +2,15 @@ package info.nightscout.androidaps.setupwizard
import android.Manifest
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.PreferencesActivity
import info.nightscout.androidaps.dialogs.ProfileSwitchDialog
import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.CommandQueueProvider
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.ProfileFunction
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.CryptoUtil
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.sharedPreferences.SP
import java.util.*
@ -61,7 +55,6 @@ class SWDefinition @Inject constructor(
private val loopPlugin: LoopPlugin,
private val nsClientPlugin: NSClientPlugin,
private val nsProfilePlugin: NSProfilePlugin,
private val protectionCheck: ProtectionCheck,
private val importExportPrefs: ImportExportPrefs,
private val androidPermission: AndroidPermission,
private val cryptoUtil: CryptoUtil,
@ -83,16 +76,6 @@ class SWDefinition @Inject constructor(
private val screenSetupWizard = SWScreen(injector, R.string.nav_setupwizard)
.add(SWInfotext(injector)
.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)
.skippable(false)
.add(SWInfotext(injector)
@ -100,20 +83,20 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.end_user_license_agreement_i_understand)
.visibility(SWValidator { !sp.getBoolean(R.string.key_i_understand, false) })
.action(Runnable {
.visibility { !sp.getBoolean(R.string.key_i_understand, false) }
.action {
sp.putBoolean(R.string.key_i_understand, true)
rxBus.send(EventSWUpdate(false))
}))
.visibility(SWValidator { !sp.getBoolean(R.string.key_i_understand, false) })
.validator(SWValidator { sp.getBoolean(R.string.key_i_understand, false) })
})
.visibility { !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)
.skippable(false)
.add(SWRadioButton(injector)
.option(R.array.unitsArray, R.array.unitsValues)
.preferenceId(R.string.key_units).label(R.string.units)
.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)
.skippable(false)
.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(SWButton(injector)
.text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) })
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, AndroidPermission.CASE_BATTERY) }))
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) })
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) })
.visibility { androidPermission.permissionNotGranted(context, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS) }
.action { androidPermission.askForPermission(activity, Manifest.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS, AndroidPermission.CASE_BATTERY) })
.visibility { 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)
.skippable(false)
.add(SWInfotext(injector)
@ -145,10 +128,10 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) })
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION, AndroidPermission.CASE_LOCATION) }))
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) })
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) })
.visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.ACCESS_FINE_LOCATION) }
.action { androidPermission.askForPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION, AndroidPermission.CASE_LOCATION) })
.visibility { 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)
.skippable(false)
.add(SWInfotext(injector)
@ -156,18 +139,18 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.askforpermission)
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) })
.action(Runnable { androidPermission.askForPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, AndroidPermission.CASE_STORAGE) }))
.visibility(SWValidator { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) })
.validator(SWValidator { !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) })
.visibility { androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
.action { androidPermission.askForPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE, AndroidPermission.CASE_STORAGE) })
.visibility { 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)
.add(SWInfotext(injector)
.label(R.string.storedsettingsfound))
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.nav_import)
.action(Runnable { importExportPrefs.importSharedPreferences(activity) }))
.visibility(SWValidator { importExportPrefs.prefsFileExists() && !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) })
.action { importExportPrefs.importSharedPreferences(activity) })
.visibility { importExportPrefs.prefsFileExists() && !androidPermission.permissionNotGranted(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) }
private val screenNsClient = SWScreen(injector, R.string.nsclientinternal_title)
.skippable(true)
.add(SWInfotext(injector)
@ -175,22 +158,18 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.enable_nsclient)
.action(Runnable {
nsClientPlugin.setPluginEnabled(PluginType.GENERAL, true)
nsClientPlugin.setFragmentVisible(PluginType.GENERAL, true)
configBuilderPlugin.processOnEnabledCategoryChanged(nsClientPlugin, PluginType.GENERAL)
configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange())
.action {
configBuilderPlugin.performPluginSwitch(nsClientPlugin, true, PluginType.GENERAL)
rxBus.send(EventSWUpdate(true))
})
.visibility(SWValidator { !nsClientPlugin.isEnabled(PluginType.GENERAL) }))
}
.visibility { !nsClientPlugin.isEnabled(PluginType.GENERAL) })
.add(SWEditUrl(injector)
.preferenceId(R.string.key_nsclientinternal_url)
.updateDelay(5)
.label(R.string.nsclientinternal_url_title)
.comment(R.string.nsclientinternal_url_dialogmessage))
.add(SWEditString(injector)
.validator(SWTextValidator { text: String -> text.length >= 12 })
.validator { text: String -> text.length >= 12 }
.preferenceId(R.string.key_nsclientinternal_api_secret)
.updateDelay(5)
.label(R.string.nsclientinternal_secret_dialogtitle)
@ -200,9 +179,8 @@ class SWDefinition @Inject constructor(
.label(R.string.status)
.initialStatus(nsClientPlugin.status)
)
.add(SWBreak(injector))
.validator(SWValidator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth })
.visibility(SWValidator { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) })
.validator { nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth }
.visibility { !(nsClientPlugin.nsClientService != null && NSClientService.isConnected && NSClientService.hasWriteAuth) }
private val screenPatientName = SWScreen(injector, R.string.patient_name)
.skippable(true)
.add(SWInfotext(injector)
@ -219,7 +197,7 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWInfotext(injector)
.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)
.skippable(false)
.add(SWBreak(injector))
@ -228,51 +206,28 @@ class SWDefinition @Inject constructor(
.preferenceId(R.string.key_age)
.label(R.string.patientage)
.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)
.skippable(false)
.add(SWPlugin(injector)
.add(SWPlugin(injector, this)
.option(PluginType.INSULIN, R.string.configbuilder_insulin_description)
.makeVisible(false)
.label(R.string.configbuilder_insulin))
.add(SWBreak(injector))
.add(SWInfotext(injector)
.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)
.skippable(false)
.add(SWPlugin(injector)
.add(SWPlugin(injector, this)
.option(PluginType.BGSOURCE, R.string.configbuilder_bgsource_description)
.label(R.string.configbuilder_bgsource))
.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)
.skippable(false)
.add(SWInfotext(injector)
.label(R.string.setupwizard_profile_description))
.add(SWBreak(injector))
.add(SWPlugin(injector)
.add(SWPlugin(injector, this)
.option(PluginType.PROFILE, R.string.configbuilder_profile_description)
.label(R.string.configbuilder_profile))
private val screenNsProfile = SWScreen(injector, R.string.nsprofile)
@ -281,69 +236,54 @@ class SWDefinition @Inject constructor(
.label(R.string.adjustprofileinns))
.add(SWFragment(injector, this)
.add(NSProfileFragment()))
.validator(SWValidator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") })
.visibility(SWValidator { nsProfilePlugin.isEnabled(PluginType.PROFILE) })
.validator { nsProfilePlugin.profile != null && nsProfilePlugin.profile!!.getDefaultProfile() != null && nsProfilePlugin.profile!!.getDefaultProfile()!!.isValid("StartupWizard") }
.visibility { nsProfilePlugin.isEnabled(PluginType.PROFILE) }
private val screenLocalProfile = SWScreen(injector, R.string.localprofile)
.skippable(false)
.add(SWFragment(injector, this)
.add(LocalProfileFragment()))
.validator(SWValidator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true })
.visibility(SWValidator { localProfilePlugin.isEnabled(PluginType.PROFILE) })
.validator { localProfilePlugin.profile?.getDefaultProfile()?.isValid("StartupWizard") == true }
.visibility { localProfilePlugin.isEnabled(PluginType.PROFILE) }
private val screenProfileSwitch = SWScreen(injector, R.string.careportal_profileswitch)
.skippable(false)
.add(SWInfotext(injector)
.label(R.string.profileswitch_ismissing))
.add(SWButton(injector)
.text(R.string.doprofileswitch)
.action(Runnable { ProfileSwitchDialog().show(activity.supportFragmentManager, "SetupWizard") }))
.validator(SWValidator { profileFunction.getProfile() != null })
.visibility(SWValidator { profileFunction.getProfile() == null })
.action { ProfileSwitchDialog().show(activity.supportFragmentManager, "SetupWizard") })
.validator { profileFunction.getProfile() != null }
.visibility { profileFunction.getProfile() == null }
private val screenPump = SWScreen(injector, R.string.configbuilder_pump)
.skippable(false)
.add(SWPlugin(injector)
.add(SWPlugin(injector, this)
.option(PluginType.PUMP, R.string.configbuilder_pump_description)
.label(R.string.configbuilder_pump))
.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)
.label(R.string.setupwizard_pump_pump_not_initialized)
.visibility(SWValidator { !isPumpInitialized() }))
.visibility { !isPumpInitialized() })
.add( // Omnipod only
SWInfotext(injector)
.label(R.string.setupwizard_pump_waiting_for_riley_link_connection)
.visibility(SWValidator {
.visibility {
val activePump = activePlugin.activePump
activePump is OmnipodPumpPlugin && !activePump.isRileyLinkReady
}))
})
.add( // Omnipod only
SWEventListener(injector, EventRileyLinkDeviceStatusChange::class.java)
.label(R.string.setupwizard_pump_riley_link_status)
.visibility(SWValidator {
activePlugin.activePump is OmnipodPumpPlugin
}))
.visibility { activePlugin.activePump is OmnipodPumpPlugin })
.add(SWButton(injector)
.text(R.string.readstatus)
.action(Runnable { commandQueue.readStatus("Clicked connect to pump", null) })
.visibility(SWValidator {
.action { commandQueue.readStatus("Clicked connect to pump", null) }
.visibility {
// 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
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 {
val activePump = activePlugin.activePump
@ -358,31 +298,20 @@ class SWDefinition @Inject constructor(
.add(SWInfotext(injector)
.label(R.string.setupwizard_aps_description))
.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)
.label("https://openaps.readthedocs.io/en/latest/"))
.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)
.skippable(false)
.add(SWRadioButton(injector)
.option(R.array.aps_modeArray, R.array.aps_modeValues)
.preferenceId(R.string.key_aps_mode).label(R.string.apsmode_title)
.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)
.skippable(false)
.add(SWInfotext(injector)
@ -390,17 +319,13 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWButton(injector)
.text(R.string.enableloop)
.action(Runnable {
loopPlugin.setPluginEnabled(PluginType.LOOP, true)
loopPlugin.setFragmentVisible(PluginType.LOOP, true)
configBuilderPlugin.processOnEnabledCategoryChanged(loopPlugin, PluginType.LOOP)
configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange())
.action {
configBuilderPlugin.performPluginSwitch(loopPlugin, true, PluginType.LOOP)
rxBus.send(EventSWUpdate(true))
})
.visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) }))
.validator(SWValidator { loopPlugin.isEnabled(PluginType.LOOP) })
.visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS })
}
.visibility { !loopPlugin.isEnabled(PluginType.LOOP) })
.validator { loopPlugin.isEnabled(PluginType.LOOP) }
.visibility { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS }
private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity)
.skippable(false)
.add(SWInfotext(injector)
@ -408,21 +333,9 @@ class SWDefinition @Inject constructor(
.add(SWHtmlLink(injector)
.label(R.string.setupwizard_sensitivity_url))
.add(SWBreak(injector))
.add(SWPlugin(injector)
.add(SWPlugin(injector, this)
.option(PluginType.SENSITIVITY, R.string.configbuilder_sensitivity_description)
.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)
.skippable(false)
.add(SWInfotext(injector)
@ -430,8 +343,8 @@ class SWDefinition @Inject constructor(
.add(SWBreak(injector))
.add(SWFragment(injector, this)
.add(ObjectivesFragment()))
.validator(SWValidator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted })
.visibility(SWValidator { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS })
.validator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted }
.visibility { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS }
private fun swDefinitionFull() { // List all the screens here
add(screenSetupWizard)

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.setupwizard.elements
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
@ -7,15 +8,17 @@ import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.TextView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.MyPreferenceFragment
import info.nightscout.androidaps.events.EventConfigBuilderChange
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.plugins.configBuilder.PluginStore
import info.nightscout.androidaps.setupwizard.SWDefinition
import info.nightscout.androidaps.setupwizard.events.EventSWUpdate
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 configBuilderPlugin: ConfigBuilderPlugin
@ -25,6 +28,8 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
private var pluginDescription = 0
private var makeVisible = true
private var fragment: MyPreferenceFragment? = null
fun option(pType: PluginType, pluginDescription: Int): SWPlugin {
this.pType = pType
this.pluginDescription = pluginDescription
@ -37,26 +42,30 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
}
override fun generateDialog(layout: LinearLayout) {
var selectedPlugin: PluginBase? = null
val context = layout.context
radioGroup = RadioGroup(context)
radioGroup?.clearCheck()
val pluginsInCategory = pluginStore.getSpecificPluginsList(pType!!)
radioGroup?.orientation = LinearLayout.VERTICAL
radioGroup?.visibility = View.VISIBLE
val pdesc = TextView(context)
pdesc.setText(pluginDescription)
val pDesc = TextView(context)
pDesc.setText(pluginDescription)
var params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.setMargins(0, 0, 0, 40)
pdesc.layoutParams = params
layout.addView(pdesc)
pDesc.layoutParams = params
layout.addView(pDesc)
for (i in pluginsInCategory.indices) {
val rdbtn = RadioButton(context)
val rdBtn = RadioButton(context)
val p = pluginsInCategory[i]
rdbtn.id = View.generateViewId()
rdbtn.text = p.name
if (p.isEnabled(pType!!)) rdbtn.isChecked = true
rdbtn.tag = p
radioGroup?.addView(rdbtn)
rdBtn.id = View.generateViewId()
rdBtn.text = p.name
if (p.isEnabled(pType!!)) {
rdBtn.isChecked = true
selectedPlugin = p
}
rdBtn.tag = p
radioGroup?.addView(rdBtn)
params = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
params.setMargins(80, 0, 0, 0)
val desc = TextView(context)
@ -73,8 +82,27 @@ class SWPlugin(injector: HasAndroidInjector) : SWItem(injector, Type.PLUGIN) {
configBuilderPlugin.storeSettings("SetupWizard")
rxBus.send(EventConfigBuilderChange())
rxBus.send(EventSWUpdate(false))
addConfiguration(layout, plugin)
}
layout.addView(radioGroup)
selectedPlugin?.let { addConfiguration(layout, it) }
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
if (isTablet) {
for (v in listOf<TextView>(
for (v in listOf<TextView?>(
view.overview_bg,
view.overview_time,
view.overview_timeagoshort,
@ -60,8 +60,8 @@ interface SkinInterface {
view.overview_basebasal,
view.overview_extendedbolus,
view.overview_sensitivity
)) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f)
for (v in listOf<TextView>(
)) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.5f)
for (v in listOf<TextView?>(
view.overview_pump,
view.overview_openaps,
view.overview_uploader,
@ -72,9 +72,13 @@ interface SkinInterface {
view.careportal_sensorage,
view.careportal_pbage,
view.careportal_batterylevel
)) v.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
view.overview_time_llayout.orientation = LinearLayout.HORIZONTAL
view.overview_timeagoshort.setTextSize(COMPLEX_UNIT_PX, view.overview_time.textSize)
)) v?.setTextSize(COMPLEX_UNIT_PX, v.textSize * 1.3f)
view.overview_time_llayout?.orientation = LinearLayout.HORIZONTAL
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.
*/
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) {
final JsonVisitor visitor = new JsonVisitor(1, '\t');

View file

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

View file

@ -53,7 +53,7 @@ object PrefImportSummaryDialog {
for ((metaKey, metaEntry) in prefs.metadata) {
val rowLayout = LayoutInflater.from(themedCtx).inflate(R.layout.import_summary_item, null)
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.status_icon) as ImageView).setImageResource(metaEntry.status.icon)
@ -84,9 +84,9 @@ object PrefImportSummaryDialog {
detailsBtn.setOnClickListener {
val detailsLayout = LayoutInflater.from(context).inflate(R.layout.import_summary_details, null)
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.setBackgroundColor(Color.TRANSPARENT);
wview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
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.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null)
AlertDialogHelper.Builder(context, R.style.AppTheme)
.setCustomTitle(AlertDialogHelper.buildCustomTitle(

View file

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

View file

@ -172,7 +172,7 @@ class BolusWizard @Inject constructor(
}
// Insulin from 15 min trend
glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
glucoseStatus = GlucoseStatus(injector).glucoseStatusData
glucoseStatus?.let {
if (useTrend) {
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
// Trend
val glucoseStatus = GlucoseStatus(injector).getGlucoseStatusData()
val glucoseStatus = GlucoseStatus(injector).glucoseStatusData
var trend = false
if (useTrend() == YES) {
trend = true

View file

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