Merge pull request #4 from nightscout/dev

Dev
This commit is contained in:
Andreas 2020-12-17 10:28:03 +01:00 committed by GitHub
commit efe351f430
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
520 changed files with 5492 additions and 4998 deletions

View file

@ -22,14 +22,6 @@ jacoco {
toolVersion = "0.8.3"
}
ext {
powermockVersion = "1.7.3"
dexmakerVersion = "1.2"
retrofit2Version = '2.9.0'
okhttp3Version = '4.9.0'
}
repositories {
jcenter { url "https://jcenter.bintray.com/" }
mavenCentral()
@ -128,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() + '"'
@ -143,6 +135,9 @@ android {
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
}
lintOptions {
checkReleaseBuilds false
disable 'MissingTranslation'
@ -230,11 +225,9 @@ android {
allprojects {
repositories {
jcenter()
flatDir {
dirs 'libs'
}
maven { url 'https://jitpack.io' }
}
}
@ -250,63 +243,6 @@ dependencies {
implementation project(':omnipod')
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.google.android.gms:play-services-wearable:17.0.0'
implementation 'com.google.android.gms:play-services-location:17.1.0'
implementation platform('com.google.firebase:firebase-bom:25.12.0')
implementation "com.google.firebase:firebase-analytics-ktx"
implementation 'com.google.firebase:firebase-auth-ktx'
implementation 'com.google.firebase:firebase-database-ktx'
implementation "androidx.appcompat:appcompat:$appcompat_verison"
implementation 'androidx.legacy:legacy-support-v13:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.biometric:biometric:1.0.1'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.gridlayout:gridlayout:1.0.0'
implementation 'androidx.percentlayout:percentlayout:1.0.0'
implementation "androidx.preference:preference-ktx:$preferencektx_version"
implementation "androidx.activity:activity-ktx:${activityVersion}"
implementation "androidx.fragment:fragment-ktx:${fragmentktx_version}"
implementation "androidx.constraintlayout:constraintlayout:$constraintlayout_version"
implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
implementation "com.google.android.material:material:$material_version"
implementation "io.reactivex.rxjava2:rxandroid:${rxandroid_version}"
implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}"
implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}"
implementation("com.github.tony19:logback-android-classic:1.1.1-6") {
exclude group: "com.google.android", module: "android"
}
implementation "org.apache.commons:commons-lang3:$commonslang3_version"
implementation 'org.slf4j:slf4j-api:1.7.30'
// Graphview cannot be upgraded
implementation "com.jjoe64:graphview:4.0.1"
implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2"
implementation 'com.madgag.spongycastle:core:1.58.0.0'
implementation("com.google.android:flexbox:0.3.0") {
exclude group: "com.android.support"
}
implementation("io.socket:socket.io-client:1.0.0") {
// excluding org.json which is provided by Android
exclude group: "org.json", module: "json"
}
implementation "com.google.code.gson:gson:2.8.6"
implementation('com.google.guava:guava:30.0-jre') {
exclude group: "com.google.code.findbugs", module: "jsr305"
}
implementation 'com.google.code.findbugs:jsr305:3.0.2'
implementation 'net.danlew:android.joda:2.10.6'
implementation 'org.mozilla:rhino:1.7.13'
implementation 'com.github.DavidProdinger:weekdays-selector:1.1.0'
implementation 'com.github.kenglxn.QRGen:android:2.6.0'
implementation 'com.eatthepath:java-otp:0.2.0'
testImplementation "junit:junit:$junit_version"
testImplementation 'org.json:json:20200518'
@ -323,31 +259,16 @@ dependencies {
testImplementation "org.skyscreamer:jsonassert:1.5.0"
testImplementation "org.hamcrest:hamcrest-all:1.3"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutinesVersion"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutinesVersion"
// new for tidepool
implementation "com.squareup.okhttp3:okhttp:$okhttp3Version"
implementation "com.squareup.okhttp3:logging-interceptor:$okhttp3Version"
implementation "com.squareup.retrofit2:retrofit:$retrofit2Version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit2Version"
implementation "com.squareup.retrofit2:converter-gson:$retrofit2Version"
// Phone checker
implementation 'com.scottyab:rootbeer-lib:0.0.8'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha03'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:rules:1.3.0-beta01'
androidTestImplementation "androidx.test.ext:junit:$androidx_junit"
androidTestImplementation "androidx.test:rules:$androidx_rules"
androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2'
/* Dagger2 - We are going to use dagger.android which includes
* support for Activity and fragment injection so we need to include
* the following dependencies */
implementation "com.google.dagger:dagger-android:$dagger_version"
implementation "com.google.dagger:dagger-android-support:$dagger_version"
annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version"
annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version"
kapt "com.google.dagger:dagger-android-processor:$dagger_version"
@ -356,15 +277,6 @@ dependencies {
kapt "com.google.dagger:dagger-compiler:$dagger_version"
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
//WorkManager
implementation "androidx.work:work-runtime:$work_version"
implementation "androidx.work:work-runtime-ktx:$work_version"
implementation "androidx.work:work-rxjava2:$work_version"
implementation 'com.google.androidbrowserhelper:androidbrowserhelper:2.0.0'
implementation 'com.google.guava:listenablefuture:9999.0-empty-to-avoid-conflict-with-guava'
}
/*

View file

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="info.nightscout.androidaps">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
@ -71,6 +72,10 @@
<activity android:name=".activities.ProfileHelperActivity"
android:theme="@style/ProfileHelperAppTheme" />
<activity android:name=".activities.StatsActivity" />
<activity
android:name="com.google.firebase.auth.internal.FederatedSignInActivity"
tools:replace="android:launchMode"
android:launchMode="standard" />
<!-- Receive new BG readings from other local apps -->
<receiver

View file

@ -2,3 +2,5 @@
51:6D:12:67:4C:27:F4:9B:9F:E5:42:9B:01:B3:98:E4:66:2B:85:B7:A8:DD:70:32:B7:6A:D7:97:9A:0D:97:10
#Leaked
55:5D:70:C9:BE:10:41:7E:4B:01:A9:C4:C6:44:4A:F8:69:71:35:25:ED:95:23:16:C7:15:E8:EB:C6:08:FC:B1
E0:71:A3:6E:96:60:5A:FC:B3:77:DB:2F:C4:E0:92:F3:39:A6:27:24:91:F5:7E:BB:55:9B:60:C6:CC:A3:03:41
32:99:61:C4:A0:92:E8:D2:C7:65:04:74:04:17:7E:2D:2A:16:2A:5A:63:48:69:6A:0A:C4:53:3C:7C:78:22:95

View file

@ -27,9 +27,10 @@ import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.joanzapata.iconify.Iconify
import com.joanzapata.iconify.fonts.FontAwesomeModule
import info.nightscout.androidaps.activities.ProfileHelperActivity
import dev.doubledot.doki.ui.DokiActivity
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
@ -70,6 +71,7 @@ import javax.inject.Inject
import kotlin.system.exitProcess
class MainActivity : NoSplashAppCompatActivity() {
private val disposable = CompositeDisposable()
@Inject lateinit var aapsLogger: AAPSLogger
@ -135,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)
@ -172,8 +175,8 @@ class MainActivity : NoSplashAppCompatActivity() {
override fun onResume() {
super.onResume()
protectionCheck.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null,
UIRunnable(Runnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) }),
UIRunnable(Runnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) })
UIRunnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed)) { finish() } },
UIRunnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed)) { finish() } }
)
}
@ -192,14 +195,14 @@ class MainActivity : NoSplashAppCompatActivity() {
val pageAdapter = TabPageAdapter(this)
main_navigation_view.setNavigationItemSelectedListener { true }
val menu = main_navigation_view.menu.also { it.clear() }
for (p in activePlugin.pluginsList) {
for (p in activePlugin.getPluginsList()) {
pageAdapter.registerNewFragment(p)
if (p.isEnabled() && p.hasFragment() && !p.isFragmentVisible() && !p.pluginDescription.neverVisible) {
val menuItem = menu.add(p.name)
menuItem.isCheckable = true
menuItem.setOnMenuItemClickListener {
val intent = Intent(this, SingleFragmentActivity::class.java)
intent.putExtra("plugin", activePlugin.pluginsList.indexOf(p))
intent.putExtra("plugin", activePlugin.getPluginsList().indexOf(p))
startActivity(intent)
main_drawer_layout.closeDrawers()
true
@ -237,7 +240,7 @@ class MainActivity : NoSplashAppCompatActivity() {
if (permissions.isNotEmpty()) {
if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
when (requestCode) {
AndroidPermission.CASE_STORAGE -> //show dialog after permission is granted
AndroidPermission.CASE_STORAGE -> //show dialog after permission is granted
OKDialog.show(this, "", resourceHelper.gs(R.string.alert_dialog_storage_permission_text))
AndroidPermission.CASE_LOCATION, AndroidPermission.CASE_SMS, AndroidPermission.CASE_BATTERY, AndroidPermission.CASE_PHONE_STATE, AndroidPermission.CASE_SYSTEM_WINDOW -> {
@ -272,8 +275,8 @@ class MainActivity : NoSplashAppCompatActivity() {
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.nav_preferences -> {
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, Runnable {
R.id.nav_preferences -> {
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, {
val i = Intent(this, PreferencesActivity::class.java)
i.putExtra("id", -1)
startActivity(i)
@ -281,17 +284,19 @@ class MainActivity : NoSplashAppCompatActivity() {
return true
}
R.id.nav_historybrowser -> {
R.id.nav_historybrowser -> {
startActivity(Intent(this, HistoryBrowseActivity::class.java))
return true
}
R.id.nav_setupwizard -> {
startActivity(Intent(this, SetupWizardActivity::class.java))
R.id.nav_setupwizard -> {
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, {
startActivity(Intent(this, SetupWizardActivity::class.java))
})
return true
}
R.id.nav_about -> {
R.id.nav_about -> {
var message = "Build: ${BuildConfig.BUILDVERSION}\n"
message += "Flavor: ${BuildConfig.FLAVOR}${BuildConfig.BUILD_TYPE}\n"
message += "${resourceHelper.gs(R.string.configbuilder_nightscoutversion_label)} ${nsSettingsStatus.nightscoutVersionName}"
@ -304,14 +309,15 @@ class MainActivity : NoSplashAppCompatActivity() {
.setIcon(iconsProvider.getIcon())
.setMessage(messageSpanned)
.setPositiveButton(resourceHelper.gs(R.string.ok), null)
.create().also {
it.show()
(it.findViewById<View>(android.R.id.message) as TextView).movementMethod = LinkMovementMethod.getInstance()
.setNeutralButton(resourceHelper.gs(R.string.cta_dont_kill_my_app_info)) { _, _ -> DokiActivity.start(context = this@MainActivity) }
.create().apply {
show()
findViewById<TextView>(android.R.id.message)?.movementMethod = LinkMovementMethod.getInstance()
}
return true
}
R.id.nav_exit -> {
R.id.nav_exit -> {
aapsLogger.debug(LTag.CORE, "Exiting")
rxBus.send(EventAppExit())
finish()
@ -321,7 +327,7 @@ class MainActivity : NoSplashAppCompatActivity() {
R.id.nav_plugin_preferences -> {
val plugin = (main_pager.adapter as TabPageAdapter).getPluginAt(main_pager.currentItem)
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, Runnable {
protectionCheck.queryProtection(this, ProtectionCheck.Protection.PREFERENCES, {
val i = Intent(this, PreferencesActivity::class.java)
i.putExtra("id", plugin.preferencesId)
startActivity(i)
@ -334,12 +340,12 @@ class MainActivity : NoSplashAppCompatActivity() {
return true
}
*/
R.id.nav_defaultprofile -> {
R.id.nav_defaultprofile -> {
startActivity(Intent(this, ProfileHelperActivity::class.java))
return true
}
R.id.nav_stats -> {
R.id.nav_stats -> {
startActivity(Intent(this, StatsActivity::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)
@ -151,7 +143,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
(savedInstanceState ?: arguments)?.let { bundle ->
if (bundle.containsKey("id")) {
pluginId = bundle.getInt("id") ?: -1
pluginId = bundle.getInt("id")
}
if (bundle.containsKey("filter")) {
filter = bundle.getString("filter") ?: ""
@ -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

@ -417,6 +417,8 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
try {
getDaoBgReadings().update(bgReading);
openHumansUploader.enqueueBGReading(bgReading);
aapsLogger.debug(LTag.DATABASE, "BG: Updating record from: "+ bgReading.toString());
scheduleBgHistoryChange(bgReading.date); // trigger cache invalidation
} catch (SQLException e) {
aapsLogger.error("Unhandled exception", e);
}

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

@ -58,7 +58,7 @@ class CalibrationDialog : DialogFragmentWithDate() {
val units = profileFunction.getUnits()
val unitLabel = if (units == Constants.MMOL) resourceHelper.gs(R.string.mmol) else resourceHelper.gs(R.string.mgdl)
val actions: LinkedList<String?> = LinkedList()
val bg = overview_calibration_bg.value
val bg = overview_calibration_bg?.value ?: return false
actions.add(resourceHelper.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel)
if (bg > 0) {
activity?.let { activity ->

View file

@ -150,7 +150,7 @@ class CarbsDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val carbs = overview_carbs_carbs.value.toInt()
val carbs = overview_carbs_carbs?.value?.toInt() ?: return false
val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value()
val units = profileFunction.getUnits()
val activityTTDuration = defaultValueHelper.determineActivityTTDuration()

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

@ -62,7 +62,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text)
val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin?.text ?: return false)
val durationInMinutes = actions_extendedbolus_duration.value.toInt()
val actions: LinkedList<String> = LinkedList()
val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value()

View file

@ -85,7 +85,7 @@ class FillDialog : DialogFragmentWithDate() {
}
override fun submit(): Boolean {
val insulin = SafeParse.stringToDouble(fill_insulinamount.text)
val insulin = SafeParse.stringToDouble(fill_insulinamount?.text ?: return false)
val actions: LinkedList<String?> = LinkedList()
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()

View file

@ -129,7 +129,7 @@ class InsulinDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
val pumpDescription = activePlugin.activePump.pumpDescription
val insulin = SafeParse.stringToDouble(overview_insulin_amount.text)
val insulin = SafeParse.stringToDouble(overview_insulin_amount?.text ?: return false)
val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value()
val actions: LinkedList<String?> = LinkedList()
val units = profileFunction.getUnits()

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)
@ -91,7 +91,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() {
?: return false
val actions: LinkedList<String> = LinkedList()
val duration = overview_profileswitch_duration.value.toInt()
val duration = overview_profileswitch_duration?.value?.toInt() ?: return false
if (duration > 0)
actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration))
val profile = overview_profileswitch_profile.selectedItem.toString()

View file

@ -84,7 +84,7 @@ class TempBasalDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
var percent = 0
var absolute = 0.0
val durationInMinutes = actions_tempbasal_duration.value.toInt()
val durationInMinutes = actions_tempbasal_duration?.value?.toInt() ?: return false
val profile = profileFunction.getProfile() ?: return false
val actions: LinkedList<String> = LinkedList()
if (isPercentPump) {

View file

@ -116,7 +116,7 @@ class TempTargetDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
val actions: LinkedList<String> = LinkedList()
val reason = overview_temptarget_reason.selectedItem.toString()
val reason = overview_temptarget_reason?.selectedItem?.toString() ?: return false
val unitResId = if (profileFunction.getUnits() == Constants.MGDL) R.string.mgdl else R.string.mmol
val target = overview_temptarget_temptarget.value
val duration = overview_temptarget_duration.value.toInt()

View file

@ -94,7 +94,7 @@ class TreatmentDialog : DialogFragmentWithDate() {
override fun submit(): Boolean {
val pumpDescription = activePlugin.activePump.pumpDescription
val insulin = SafeParse.stringToDouble(overview_treatment_insulin.text)
val insulin = SafeParse.stringToDouble(overview_treatment_insulin?.text ?: return false)
val carbs = SafeParse.stringToInt(overview_treatment_carbs.text)
val recordOnlyChecked = overview_treatment_record_only.isChecked
val actions: LinkedList<String?> = LinkedList()

View file

@ -8,6 +8,7 @@ import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.lifecycleScope
import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
@ -37,7 +38,6 @@ import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_historybrowse.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
@ -168,7 +168,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
if (it.cause is EventCustomCalculationFinished) {
updateGUI("EventAutosensCalculationFinished", bgOnly = false)
}
}) { fabricPrivacy::logException }
}, fabricPrivacy::logException )
)
disposable.add(rxBus
.toObservable(EventAutosensBgLoaded::class.java)
@ -178,12 +178,12 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
if (it.cause is EventCustomCalculationFinished) {
updateGUI("EventAutosensCalculationFinished", bgOnly = true)
}
}) { fabricPrivacy::logException }
}, fabricPrivacy::logException )
)
disposable.add(rxBus
.toObservable(EventIobCalculationProgress::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ overview_iobcalculationprogess?.text = it.progress }) { fabricPrivacy::logException }
.subscribe({ overview_iobcalculationprogess?.text = it.progress }, fabricPrivacy::logException )
)
disposable.add(rxBus
.toObservable(EventRefreshOverview::class.java)
@ -193,7 +193,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
prepareGraphs()
updateGUI("EventRefreshOverview", bgOnly = false)
}
}) { fabricPrivacy::logException }
}, fabricPrivacy::logException )
)
if (start == 0L) {
// set start of current day
@ -256,7 +256,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
}
private fun runCalculation(from: String) {
GlobalScope.launch(Dispatchers.Default) {
lifecycleScope.launch(Dispatchers.Default) {
treatmentsPluginHistory.initializeData(start - T.hours(8).msecs())
val end = start + T.hours(rangeToDisplay.toLong()).msecs()
iobCobCalculatorPluginHistory.stopCalculation(from)
@ -273,7 +273,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() {
val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine()
GlobalScope.launch(Dispatchers.Main) {
lifecycleScope.launch(Dispatchers.Main) {
historybrowse_noprofile?.visibility = (profile == null).toVisibility()
profile ?: return@launch

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

@ -46,17 +46,17 @@ class ConfigBuilderPlugin @Inject constructor(
}
private fun setAlwaysEnabledPluginsEnabled() {
for (plugin in activePlugin.pluginsList) {
for (plugin in activePlugin.getPluginsList()) {
if (plugin.pluginDescription.alwaysEnabled) plugin.setPluginEnabled(plugin.getType(), true)
}
storeSettings("setAlwaysEnabledPluginsEnabled")
}
override fun storeSettings(from: String) {
activePlugin.pluginsList
activePlugin.getPluginsList()
aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from")
activePlugin.verifySelectionInCategories()
for (p in activePlugin.pluginsList) {
for (p in activePlugin.getPluginsList()) {
val type = p.getType()
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.alwaysVisible) continue
if (p.pluginDescription.alwaysEnabled && p.pluginDescription.neverVisible) continue
@ -82,7 +82,7 @@ class ConfigBuilderPlugin @Inject constructor(
private fun loadSettings() {
aapsLogger.debug(LTag.CONFIGBUILDER, "Loading stored settings")
for (p in activePlugin.pluginsList) {
for (p in activePlugin.getPluginsList()) {
val type = p.getType()
loadPref(p, type, true)
if (p.getType() == PluginType.PUMP) {
@ -110,7 +110,7 @@ class ConfigBuilderPlugin @Inject constructor(
}
fun logPluginStatus() {
for (p in activePlugin.pluginsList) {
for (p in activePlugin.getPluginsList()) {
aapsLogger.debug(LTag.CONFIGBUILDER, p.name + ":" +
(if (p.isEnabled(PluginType.GENERAL)) " GENERAL" else "") +
(if (p.isEnabled(PluginType.TREATMENT)) " TREATMENT" else "") +
@ -147,7 +147,7 @@ class ConfigBuilderPlugin @Inject constructor(
}
}
fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
override fun performPluginSwitch(changedPlugin: PluginBase, enabled: Boolean, type: PluginType) {
changedPlugin.setPluginEnabled(type, enabled)
changedPlugin.setFragmentVisible(type, enabled)
processOnEnabledCategoryChanged(changedPlugin, type)

View file

@ -15,13 +15,13 @@ class PluginStore @Inject constructor(
lateinit var plugins: List<@JvmSuppressWildcards PluginBase>
private var activeBgSource: BgSourceInterface? = null
private var activePump: PumpInterface? = null
private var activeBgSourceStore: BgSourceInterface? = null
private var activePumpStore: PumpInterface? = null
private var activeProfile: ProfileInterface? = null
private var activeAPS: APSInterface? = null
private var activeInsulin: InsulinInterface? = null
private var activeSensitivity: SensitivityInterface? = null
private var activeTreatments: TreatmentsInterface? = null
private var activeAPSStore: APSInterface? = null
private var activeInsulinStore: InsulinInterface? = null
private var activeSensitivityStore: SensitivityInterface? = null
private var activeTreatmentsStore: TreatmentsInterface? = null
fun loadDefaults() {
verifySelectionInCategories()
@ -71,34 +71,34 @@ class PluginStore @Inject constructor(
// PluginType.APS
if (!config.NSCLIENT && !config.PUMPCONTROL) {
pluginsInCategory = getSpecificPluginsList(PluginType.APS)
activeAPS = getTheOneEnabledInArray(pluginsInCategory, PluginType.APS) as APSInterface?
if (activeAPS == null) {
activeAPS = getDefaultPlugin(PluginType.APS) as APSInterface
(activeAPS as PluginBase).setPluginEnabled(PluginType.APS, true)
activeAPSStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.APS) as APSInterface?
if (activeAPSStore == null) {
activeAPSStore = getDefaultPlugin(PluginType.APS) as APSInterface
(activeAPSStore as PluginBase).setPluginEnabled(PluginType.APS, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting APSInterface")
}
setFragmentVisiblities((activeAPS as PluginBase).name, pluginsInCategory, PluginType.APS)
setFragmentVisiblities((activeAPSStore as PluginBase).name, pluginsInCategory, PluginType.APS)
}
// PluginType.INSULIN
pluginsInCategory = getSpecificPluginsList(PluginType.INSULIN)
activeInsulin = getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN) as InsulinInterface?
if (activeInsulin == null) {
activeInsulin = getDefaultPlugin(PluginType.INSULIN) as InsulinInterface
(activeInsulin as PluginBase).setPluginEnabled(PluginType.INSULIN, true)
activeInsulinStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.INSULIN) as InsulinInterface?
if (activeInsulinStore == null) {
activeInsulinStore = getDefaultPlugin(PluginType.INSULIN) as InsulinInterface
(activeInsulinStore as PluginBase).setPluginEnabled(PluginType.INSULIN, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting InsulinInterface")
}
setFragmentVisiblities((activeInsulin as PluginBase).name, pluginsInCategory, PluginType.INSULIN)
setFragmentVisiblities((activeInsulinStore as PluginBase).name, pluginsInCategory, PluginType.INSULIN)
// PluginType.SENSITIVITY
pluginsInCategory = getSpecificPluginsList(PluginType.SENSITIVITY)
activeSensitivity = getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY) as SensitivityInterface?
if (activeSensitivity == null) {
activeSensitivity = getDefaultPlugin(PluginType.SENSITIVITY) as SensitivityInterface
(activeSensitivity as PluginBase).setPluginEnabled(PluginType.SENSITIVITY, true)
activeSensitivityStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.SENSITIVITY) as SensitivityInterface?
if (activeSensitivityStore == null) {
activeSensitivityStore = getDefaultPlugin(PluginType.SENSITIVITY) as SensitivityInterface
(activeSensitivityStore as PluginBase).setPluginEnabled(PluginType.SENSITIVITY, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting SensitivityInterface")
}
setFragmentVisiblities((activeSensitivity as PluginBase).name, pluginsInCategory, PluginType.SENSITIVITY)
setFragmentVisiblities((activeSensitivityStore as PluginBase).name, pluginsInCategory, PluginType.SENSITIVITY)
// PluginType.PROFILE
pluginsInCategory = getSpecificPluginsList(PluginType.PROFILE)
@ -112,33 +112,33 @@ class PluginStore @Inject constructor(
// PluginType.BGSOURCE
pluginsInCategory = getSpecificPluginsList(PluginType.BGSOURCE)
activeBgSource = getTheOneEnabledInArray(pluginsInCategory, PluginType.BGSOURCE) as BgSourceInterface?
if (activeBgSource == null) {
activeBgSource = getDefaultPlugin(PluginType.BGSOURCE) as BgSourceInterface
(activeBgSource as PluginBase).setPluginEnabled(PluginType.BGSOURCE, true)
activeBgSourceStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.BGSOURCE) as BgSourceInterface?
if (activeBgSourceStore == null) {
activeBgSourceStore = getDefaultPlugin(PluginType.BGSOURCE) as BgSourceInterface
(activeBgSourceStore as PluginBase).setPluginEnabled(PluginType.BGSOURCE, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting BgInterface")
}
setFragmentVisiblities((activeBgSource as PluginBase).name, pluginsInCategory, PluginType.PUMP)
setFragmentVisiblities((activeBgSourceStore as PluginBase).name, pluginsInCategory, PluginType.PUMP)
// PluginType.PUMP
pluginsInCategory = getSpecificPluginsList(PluginType.PUMP)
activePump = getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP) as PumpInterface?
if (activePump == null) {
activePump = getDefaultPlugin(PluginType.PUMP) as PumpInterface
(activePump as PluginBase).setPluginEnabled(PluginType.PUMP, true)
activePumpStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.PUMP) as PumpInterface?
if (activePumpStore == null) {
activePumpStore = getDefaultPlugin(PluginType.PUMP) as PumpInterface
(activePumpStore as PluginBase).setPluginEnabled(PluginType.PUMP, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface")
}
setFragmentVisiblities((activePump as PluginBase).name, pluginsInCategory, PluginType.PUMP)
setFragmentVisiblities((activePumpStore as PluginBase).name, pluginsInCategory, PluginType.PUMP)
// PluginType.TREATMENT
pluginsInCategory = getSpecificPluginsList(PluginType.TREATMENT)
activeTreatments = getTheOneEnabledInArray(pluginsInCategory, PluginType.TREATMENT) as TreatmentsInterface?
if (activeTreatments == null) {
activeTreatments = getDefaultPlugin(PluginType.TREATMENT) as TreatmentsInterface
(activeTreatments as PluginBase).setPluginEnabled(PluginType.TREATMENT, true)
activeTreatmentsStore = getTheOneEnabledInArray(pluginsInCategory, PluginType.TREATMENT) as TreatmentsInterface?
if (activeTreatmentsStore == null) {
activeTreatmentsStore = getDefaultPlugin(PluginType.TREATMENT) as TreatmentsInterface
(activeTreatmentsStore as PluginBase).setPluginEnabled(PluginType.TREATMENT, true)
aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting PumpInterface")
}
setFragmentVisiblities((activeTreatments as PluginBase).name, pluginsInCategory, PluginType.TREATMENT)
setFragmentVisiblities((activeTreatmentsStore as PluginBase).name, pluginsInCategory, PluginType.TREATMENT)
}
/**
@ -203,27 +203,31 @@ class PluginStore @Inject constructor(
// ***** Interface *****
override fun getActiveBgSource(): BgSourceInterface {
return activeBgSource ?: checkNotNull(activeBgSource) { "No bg source selected" }
}
override val activeBgSource: BgSourceInterface
get() = activeBgSourceStore ?: checkNotNull(activeBgSourceStore) { "No bg source selected" }
override fun getActiveProfileInterface(): ProfileInterface =
activeProfile ?: checkNotNull(activeProfile) { "No profile selected" }
override val activeProfileInterface: ProfileInterface
get() = activeProfile ?: checkNotNull(activeProfile) { "No profile selected" }
override fun getActiveInsulin(): InsulinInterface =
activeInsulin ?: checkNotNull(activeInsulin) { "No insulin selected" }
override val activeInsulin: InsulinInterface
get() = activeInsulinStore ?: checkNotNull(activeInsulinStore) { "No insulin selected" }
override fun getActiveAPS(): APSInterface =
activeAPS ?: checkNotNull(activeAPS) { "No APS selected" }
override val activeAPS: APSInterface
get() = activeAPSStore ?: checkNotNull(activeAPSStore) { "No APS selected" }
override fun getActivePump(): PumpInterface =
activePump ?: checkNotNull(activePump) { "No pump selected" }
override val activePump: PumpInterface
get() = activePumpStore ?: checkNotNull(activePumpStore) { "No pump selected" }
override fun getActiveSensitivity(): SensitivityInterface =
activeSensitivity ?: checkNotNull(activeSensitivity) { "No sensitivity selected" }
override val activeSensitivity: SensitivityInterface
get() = activeSensitivityStore
?: checkNotNull(activeSensitivityStore) { "No sensitivity selected" }
override fun getActiveTreatments(): TreatmentsInterface =
activeTreatments ?: checkNotNull(activeTreatments) { "No treatments selected" }
override val activeTreatments: TreatmentsInterface
get() = activeTreatmentsStore
?: checkNotNull(activeTreatmentsStore) { "No treatments selected" }
override val activeOverview: OverviewInterface
get() = getSpecificPluginsListByInterface(OverviewInterface::class.java).first() as OverviewInterface
override fun getPluginsList(): ArrayList<PluginBase> = ArrayList(plugins)

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,51 +160,66 @@ 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 {
val dialog = EditEventDialog()
val args = Bundle()
args.putString("event", event.toJSON())
args.putInt("position", position)
dialog.arguments = args
dialog.show(childFragmentManager, "EditEventDialog")
}
if (!event.readOnly)
holder.binding.rootLayout.setOnClickListener {
val dialog = EditEventDialog()
val args = Bundle()
args.putString("event", event.toJSON())
args.putInt("position", position)
dialog.arguments = args
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()
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

@ -1,13 +1,13 @@
package info.nightscout.androidaps.plugins.general.maintenance
import android.Manifest
import androidx.appcompat.app.AppCompatActivity
import android.bluetooth.BluetoothAdapter
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.provider.Settings
import androidx.annotation.StringRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
@ -21,6 +21,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.maintenance.formats.*
import info.nightscout.androidaps.utils.AndroidPermission
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
@ -43,12 +44,6 @@ import javax.inject.Singleton
* Created by mike on 03.07.2016.
*/
private const val REQUEST_EXTERNAL_STORAGE = 1
private val PERMISSIONS_STORAGE = arrayOf(
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
)
@Singleton
class ImportExportPrefs @Inject constructor(
private var log: AAPSLogger,
@ -57,6 +52,7 @@ class ImportExportPrefs @Inject constructor(
private val buildHelper: BuildHelper,
private val rxBus: RxBusWrapper,
private val passwordCheck: PasswordCheck,
private val androidPermission: AndroidPermission,
private val classicPrefsFormat: ClassicPrefsFormat,
private val encryptedPrefsFormat: EncryptedPrefsFormat,
private val prefFileList: PrefFileListProvider
@ -73,12 +69,15 @@ class ImportExportPrefs @Inject constructor(
}
fun verifyStoragePermissions(fragment: Fragment, onGranted: Runnable) {
fragment.context?.let {
val permission = ContextCompat.checkSelfPermission(it,
fragment.context?.let { ctx ->
val permission = ContextCompat.checkSelfPermission(ctx,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
fragment.requestPermissions(PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE)
fragment.activity?.let {
androidPermission.askForPermission(it, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE), AndroidPermission.CASE_STORAGE)
}
} else {
onGranted.run()
}
@ -209,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)
}
}
@ -279,7 +278,7 @@ class ImportExportPrefs @Inject constructor(
}
}
public fun importSharedPreferences(activity: FragmentActivity, importFile: PrefsFile) {
fun importSharedPreferences(activity: FragmentActivity, importFile: PrefsFile) {
askToConfirmImport(activity, importFile) { password ->
@ -336,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

@ -15,10 +15,13 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import dagger.android.HasAndroidInjector;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.interfaces.ConfigInterface;
import info.nightscout.androidaps.logging.AAPSLogger;
import info.nightscout.androidaps.logging.LTag;
import info.nightscout.androidaps.plugins.aps.loop.APSResult;
import info.nightscout.androidaps.plugins.configBuilder.RunningConfiguration;
import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.HtmlHelper;
import info.nightscout.androidaps.utils.Round;
@ -85,6 +88,8 @@ public class NSDeviceStatus {
private final SP sp;
private final ResourceHelper resourceHelper;
private final NSSettingsStatus nsSettingsStatus;
private final ConfigInterface config;
private final RunningConfiguration runningConfiguration;
private JSONObject data = null;
@ -93,12 +98,16 @@ public class NSDeviceStatus {
AAPSLogger aapsLogger,
SP sp,
ResourceHelper resourceHelper,
NSSettingsStatus nsSettingsStatus
NSSettingsStatus nsSettingsStatus,
ConfigInterface config,
RunningConfiguration runningConfiguration
) {
this.aapsLogger = aapsLogger;
this.sp = sp;
this.resourceHelper = resourceHelper;
this.nsSettingsStatus = nsSettingsStatus;
this.config = config;
this.runningConfiguration = runningConfiguration;
}
public void handleNewData(JSONArray devicestatuses) {
@ -114,8 +123,13 @@ public class NSDeviceStatus {
// Objectives 0
sp.putBoolean(R.string.key_ObjectivespumpStatusIsAvailableInNS, true);
}
if (devicestatusJson.has("configuration") && config.getNSCLIENT()) {
// copy configuration of Insulin and Sensitivity from main AAPS
runningConfiguration.apply(devicestatusJson.getJSONObject("configuration"));
}
}
} catch (JSONException ignored) {
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}
@ -375,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

@ -43,8 +43,8 @@ class OpenHumansAPI(
.toSingle()
.map { response ->
response.use { _ ->
val body = response.body
val jsonObject = body?.let { JSONObject(it.string()) }
val responseBody = response.body
val jsonObject = responseBody?.let { JSONObject(it.string()) }
if (!response.isSuccessful) throw OHHttpException(response.code, response.message, jsonObject?.getString("error"))
if (jsonObject == null) throw OHHttpException(response.code, response.message, "No body")
if (!jsonObject.has("expires_in")) throw OHMissingFieldException("expires_in")

View file

@ -564,7 +564,7 @@ class OpenHumansUploader @Inject constructor(
creationDate = uploadDate.time
),
content = bytes,
highestQueueId = items.map { it.id }.max()
highestQueueId = items.map { it.id }.maxOrNull()
))
}

View file

@ -22,6 +22,7 @@ import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.text.toSpanned
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector
@ -36,11 +37,7 @@ import info.nightscout.androidaps.dialogs.InsulinDialog
import info.nightscout.androidaps.dialogs.TreatmentDialog
import info.nightscout.androidaps.dialogs.WizardDialog
import info.nightscout.androidaps.events.*
import info.nightscout.androidaps.interfaces.ActivePluginProvider
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.interfaces.DatabaseHelperInterface
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin
import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification
@ -75,37 +72,16 @@ import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.overview_buttons_layout.*
import kotlinx.android.synthetic.main.overview_buttons_layout.overview_carbsbutton
import kotlinx.android.synthetic.main.overview_buttons_layout.overview_insulinbutton
import kotlinx.android.synthetic.main.overview_buttons_layout.overview_quickwizardbutton
import kotlinx.android.synthetic.main.overview_buttons_layout.overview_treatmentbutton
import kotlinx.android.synthetic.main.overview_buttons_layout.overview_wizardbutton
import kotlinx.android.synthetic.main.overview_fragment.overview_notifications
import kotlinx.android.synthetic.main.overview_fragment_nsclient.*
import kotlinx.android.synthetic.main.overview_graphs_layout.overview_bggraph
import kotlinx.android.synthetic.main.overview_graphs_layout.overview_chartMenuButton
import kotlinx.android.synthetic.main.overview_graphs_layout.overview_iobcalculationprogess
import kotlinx.android.synthetic.main.overview_graphs_layout.overview_iobgraph
import kotlinx.android.synthetic.main.overview_graphs_layout.*
import kotlinx.android.synthetic.main.overview_info_layout.*
import kotlinx.android.synthetic.main.overview_info_layout.overview_arrow
import kotlinx.android.synthetic.main.overview_info_layout.overview_basebasal
import kotlinx.android.synthetic.main.overview_info_layout.overview_bg
import kotlinx.android.synthetic.main.overview_info_layout.overview_cob
import kotlinx.android.synthetic.main.overview_info_layout.overview_extendedbolus
import kotlinx.android.synthetic.main.overview_info_layout.overview_iob
import kotlinx.android.synthetic.main.overview_info_layout.overview_sensitivity
import kotlinx.android.synthetic.main.overview_info_layout.overview_time
import kotlinx.android.synthetic.main.overview_info_layout.overview_timeagoshort
import kotlinx.android.synthetic.main.overview_loop_pumpstatus_layout.*
import kotlinx.android.synthetic.main.overview_statuslights_layout.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.collections.ArrayList
import kotlin.math.abs
@ -155,9 +131,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
private var loopHandler = Handler()
private var refreshLoop: Runnable? = null
private val worker = Executors.newSingleThreadScheduledExecutor()
private var scheduledUpdate: ScheduledFuture<*>? = null
private val secondaryGraphs = ArrayList<GraphView>()
private val secondaryGraphsLabel = ArrayList<TextView>()
@ -522,21 +495,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
}
}
var task: Runnable? = null
private fun scheduleUpdateGUI(from: String) {
class UpdateRunnable : Runnable {
override fun run() {
activity?.runOnUiThread {
updateGUI(from)
scheduledUpdate = null
}
updateGUI(from)
task = null
}
}
// prepare task for execution in 500 milliseconds
// cancel waiting task to prevent multiple updates
scheduledUpdate?.cancel(false)
val task: Runnable = UpdateRunnable()
scheduledUpdate = worker.schedule(task, 500, TimeUnit.MILLISECONDS)
view?.removeCallbacks(task)
task = UpdateRunnable()
view?.postDelayed(task, 500)
}
@SuppressLint("SetTextI18n")
@ -562,6 +533,14 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
val units = profileFunction.getUnits()
val lowLine = defaultValueHelper.determineLowLine()
val highLine = defaultValueHelper.determineHighLine()
val lastRun = loopPlugin.lastRun
val predictionsAvailable = if (config.APS) lastRun?.request?.hasPredictions == true else config.NSCLIENT
try {
updateGraph(lastRun, predictionsAvailable, lowLine, highLine, pump, profile)
} catch (e: IllegalStateException) {
return // view no longer exists
}
//Start with updating the BG as it is unaffected by loop.
// **** BG value ****
@ -579,11 +558,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 +591,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 +614,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 {
@ -657,8 +643,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
overview_apsmode_text?.visibility = View.GONE
overview_time_llayout?.visibility = View.VISIBLE
}
val lastRun = loopPlugin.lastRun
val predictionsAvailable = if (config.APS) lastRun?.request?.hasPredictions == true else config.NSCLIENT
// temp target
val tempTarget = treatmentsPlugin.tempTargetFromHistory
@ -796,9 +780,10 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList
iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData ->
String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100)
} ?: ""
}
// ****** GRAPH *******
GlobalScope.launch(Dispatchers.Main) {
private fun updateGraph(lastRun: LoopInterface.LastRun?, predictionsAvailable: Boolean, lowLine: Double, highLine: Double, pump: PumpInterface, profile: Profile) {
viewLifecycleOwner.lifecycleScope.launch(Dispatchers.Main) {
overview_bggraph ?: return@launch
val graphData = GraphData(injector, overview_bggraph, iobCobCalculatorPlugin, treatmentsPlugin)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList()

View file

@ -6,6 +6,7 @@ import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Config
import info.nightscout.androidaps.R
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.interfaces.OverviewInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
@ -16,9 +17,12 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi
import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.extensions.plusAssign
import info.nightscout.androidaps.utils.extensions.*
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -28,6 +32,7 @@ class OverviewPlugin @Inject constructor(
private val notificationStore: NotificationStore,
private val fabricPrivacy: FabricPrivacy,
private val rxBus: RxBusWrapper,
private val sp: SP,
aapsLogger: AAPSLogger,
resourceHelper: ResourceHelper,
private val config: Config
@ -41,7 +46,7 @@ class OverviewPlugin @Inject constructor(
.preferencesId(R.xml.pref_overview)
.description(R.string.description_overview),
aapsLogger, resourceHelper, injector
) {
), OverviewInterface {
private var disposable: CompositeDisposable = CompositeDisposable()
@ -82,4 +87,57 @@ class OverviewPlugin @Inject constructor(
}
}
}
override fun configuration(): JSONObject =
JSONObject()
.putString(R.string.key_quickwizard, sp, resourceHelper)
.putInt(R.string.key_eatingsoon_duration, sp, resourceHelper)
.putDouble(R.string.key_eatingsoon_target, sp, resourceHelper)
.putInt(R.string.key_activity_duration, sp, resourceHelper)
.putDouble(R.string.key_activity_target, sp, resourceHelper)
.putInt(R.string.key_hypo_duration, sp, resourceHelper)
.putDouble(R.string.key_hypo_target, sp, resourceHelper)
.putDouble(R.string.key_low_mark, sp, resourceHelper)
.putDouble(R.string.key_high_mark, sp, resourceHelper)
.putDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_res_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_res_critical, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper)
.putDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper)
override fun applyConfiguration(configuration: JSONObject) {
configuration
.storeString(R.string.key_quickwizard, sp, resourceHelper)
.storeInt(R.string.key_eatingsoon_duration, sp, resourceHelper)
.storeDouble(R.string.key_eatingsoon_target, sp, resourceHelper)
.storeInt(R.string.key_activity_duration, sp, resourceHelper)
.storeDouble(R.string.key_activity_target, sp, resourceHelper)
.storeInt(R.string.key_hypo_duration, sp, resourceHelper)
.storeDouble(R.string.key_hypo_target, sp, resourceHelper)
.storeDouble(R.string.key_low_mark, sp, resourceHelper)
.storeDouble(R.string.key_high_mark, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_cage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_cage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_iage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_iage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sbat_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_sbat_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bage_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bage_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_res_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_res_critical, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bat_warning, sp, resourceHelper)
.storeDouble(R.string.key_statuslights_bat_critical, sp, resourceHelper)
}
}

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

@ -22,7 +22,7 @@ import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.services.AlarmSoundService
import info.nightscout.androidaps.services.AlarmSoundServiceHelper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.resources.IconsProvider
import info.nightscout.androidaps.utils.resources.ResourceHelper
@ -39,6 +39,7 @@ class NotificationStore @Inject constructor(
private val resourceHelper: ResourceHelper,
private val context: Context,
private val iconsProvider: IconsProvider,
private val alarmSoundServiceHelper: AlarmSoundServiceHelper,
private val dateUtil: DateUtil
) {
@ -46,10 +47,12 @@ class NotificationStore @Inject constructor(
private var usesChannels = false
companion object {
private const val CHANNEL_ID = "AndroidAPS-Overview"
}
inner class NotificationComparator : Comparator<Notification> {
override fun compare(o1: Notification, o2: Notification): Int {
return o1.level - o2.level
}
@ -68,17 +71,9 @@ class NotificationStore @Inject constructor(
store.add(n)
if (sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false) && n !is NotificationWithAction) {
raiseSystemNotification(n)
if (usesChannels && n.soundId != null && n.soundId != 0) {
val alarm = Intent(context, AlarmSoundService::class.java)
alarm.putExtra("soundid", n.soundId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm)
}
if (usesChannels && n.soundId != null && n.soundId != 0) alarmSoundServiceHelper.startAlarm(context, n.soundId)
} else {
if (n.soundId != null && n.soundId != 0) {
val alarm = Intent(context, AlarmSoundService::class.java)
alarm.putExtra("soundid", n.soundId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm)
}
if (n.soundId != null && n.soundId != 0) alarmSoundServiceHelper.startAlarm(context, n.soundId)
}
Collections.sort(store, NotificationComparator())
return true
@ -87,10 +82,7 @@ class NotificationStore @Inject constructor(
@Synchronized fun remove(id: Int): Boolean {
for (i in store.indices) {
if (store[i].id == id) {
if (store[i].soundId != null) {
val alarm = Intent(context, AlarmSoundService::class.java)
context.stopService(alarm)
}
if (store[i].soundId != null) alarmSoundServiceHelper.stopService(context)
store.removeAt(i)
return true
}
@ -195,10 +187,10 @@ class NotificationStore @Inject constructor(
@Suppress("SetTextI18n")
holder.text.text = dateUtil.timeString(notification.date) + " " + notification.text
when (notification.level) {
Notification.URGENT -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent))
Notification.NORMAL -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal))
Notification.LOW -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow))
Notification.INFO -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo))
Notification.URGENT -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationUrgent))
Notification.NORMAL -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationNormal))
Notification.LOW -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationLow))
Notification.INFO -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationInfo))
Notification.ANNOUNCEMENT -> holder.cv.setBackgroundColor(resourceHelper.gc(R.color.notificationAnnouncement))
}
}
@ -208,6 +200,7 @@ class NotificationStore @Inject constructor(
}
inner class NotificationsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var cv: CardView = itemView.findViewById(R.id.notification_cardview)
var text: TextView = itemView.findViewById(R.id.notification_text)
var dismiss: Button = itemView.findViewById(R.id.notification_dismiss)

View file

@ -44,7 +44,7 @@ class DummyService : DaggerService() {
.subscribe({
aapsLogger.debug(LTag.CORE, "EventAppExit received")
stopSelf()
}) { fabricPrivacy::logException }
}, fabricPrivacy::logException )
)
}

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;
@ -290,7 +291,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
return;
}
executeTask(new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient), dataMap);
(new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dataMap);
}
}
}
@ -401,7 +402,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
}
}
entries.putDataMapArrayList("entries", dataMaps);
executeTask(new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient), entries);
(new SendToDataLayerThread(WEARABLE_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, entries);
}
sendPreferences();
sendBasals();
@ -552,8 +553,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
dm.putDataMapArrayList("temps", temps);
dm.putDataMapArrayList("boluses", boluses);
dm.putDataMapArrayList("predictions", predictions);
executeTask(new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient), dm);
(new SendToDataLayerThread(BASAL_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dm);
}
private DataMap tempDatamap(long startTime, double startBasal, long to, double toBasal, double amount) {
@ -600,7 +600,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putString("openSettings", "openSettings");
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendNotification", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("OpenSettings", "No connection to wearable available!");
@ -616,7 +615,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
dataMapRequest.getDataMap().putString("progressstatus", status);
dataMapRequest.getDataMap().putInt("progresspercent", progresspercent);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendBolusProgress", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("BolusProgress", "No connection to wearable available!");
@ -636,7 +634,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: " + actionstring);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendActionConfirmationRequest", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("confirmationRequest", "No connection to wearable available!");
@ -656,7 +653,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: " + actionstring);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendChangeConfirmationRequest", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("changeConfirmRequest", "No connection to wearable available!");
@ -674,7 +670,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
aapsLogger.debug(LTag.WEAR, "Canceling notification on wear: " + actionstring);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendCancelNotificationRequest", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("cancelNotificationReq", "No connection to wearable available!");
@ -700,8 +695,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
currentBasal = generateBasalString();
//bgi
double bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits());
bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.to1Decimal(bgi);
@ -739,7 +732,6 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
dataMapRequest.getDataMap().putBoolean("showBgi", sp.getBoolean(R.string.key_wear_showbgi, false));
dataMapRequest.getDataMap().putInt("batteryLevel", (phoneBattery >= 30) ? 1 : 0);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendStatus", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
@ -756,28 +748,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog
dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis());
dataMapRequest.getDataMap().putBoolean("wearcontrol", wearcontrol);
PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest();
debugData("sendPreferences", putDataRequest);
Wearable.DataApi.putDataItem(googleApiClient, putDataRequest);
} else {
Log.e("SendStatus", "No connection to wearable available!");
}
}
private void debugData(String source, Object data) {
// Log.d(TAG, "WR: " + source + " " + data);
}
private void executeTask(AsyncTask task, DataMap... parameters) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Object[]) parameters);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
// } else {
// task.execute();
// }
}
@NonNull
private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) {

View file

@ -22,9 +22,9 @@ class InsulinFragment : DaggerFragment() {
override fun onResume() {
super.onResume()
insulin_name?.setText(activePlugin.getActiveInsulin().getFriendlyName())
insulin_comment?.setText(activePlugin.getActiveInsulin().getComment())
insulin_dia?.text = resourceHelper.gs(R.string.dia) + ": " + activePlugin.getActiveInsulin().getDia() + "h"
insulin_graph?.show(activePlugin.getActiveInsulin())
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

@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -18,10 +19,11 @@ class InsulinLyumjevPlugin @Inject constructor(
rxBus: RxBusWrapper, aapsLogger: AAPSLogger
) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) {
override val id get(): InsulinInterface.InsulinType = InsulinInterface.InsulinType.OREF_LYUMJEV
override val friendlyName get(): String = resourceHelper.gs(R.string.lyumjev)
override fun getId(): Int = InsulinInterface.OREF_LYUMJEV
override fun getFriendlyName(): String = resourceHelper.gs(R.string.lyumjev)
override fun configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: JSONObject) {}
override fun commentStandardText(): String = resourceHelper.gs(R.string.lyumjev)

View file

@ -3,16 +3,16 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Iob
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.PluginBase
import info.nightscout.androidaps.interfaces.PluginDescription
import info.nightscout.androidaps.interfaces.PluginType
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.db.Treatment
import info.nightscout.androidaps.utils.resources.ResourceHelper
/**
@ -35,15 +35,16 @@ abstract class InsulinOrefBasePlugin(
), InsulinInterface {
private var lastWarned: Long = 0
override fun getDia(): Double {
val dia = userDefinedDia
return if (dia >= MIN_DIA) {
dia
} else {
sendShortDiaNotification(dia)
MIN_DIA
override val dia
get(): Double {
val dia = userDefinedDia
return if (dia >= MIN_DIA) {
dia
} else {
sendShortDiaNotification(dia)
MIN_DIA
}
}
}
open fun sendShortDiaNotification(dia: Double) {
if (System.currentTimeMillis() - lastWarned > 60 * 1000) {
@ -62,17 +63,13 @@ abstract class InsulinOrefBasePlugin(
return profile?.dia ?: MIN_DIA
}
fun iobCalcForTreatment(treatment: Treatment, time: Long): Iob {
return this.iobCalcForTreatment(treatment, time, 0.0)
}
override fun iobCalcForTreatment(treatment: Treatment, time: Long, dia: Double): Iob {
val result = Iob()
val peak = peak
if (treatment.insulin != 0.0) {
val bolusTime = treatment.date
val t = (time - bolusTime) / 1000.0 / 60.0
val td = getDia() * 60 //getDIA() always >= MIN_DIA
val td = dia * 60 //getDIA() always >= MIN_DIA
val tp = peak.toDouble()
// force the IOB to 0 if over DIA hours have passed
if (t < td) {
@ -86,19 +83,21 @@ abstract class InsulinOrefBasePlugin(
return result
}
override fun getComment(): String {
var comment = commentStandardText()
val userDia = userDefinedDia
if (userDia < MIN_DIA) {
comment += "\n" + resourceHelper.gs(R.string.dia_too_short, userDia, MIN_DIA)
override val comment
get(): String {
var comment = commentStandardText()
val userDia = userDefinedDia
if (userDia < MIN_DIA) {
comment += "\n" + resourceHelper.gs(R.string.dia_too_short, userDia, MIN_DIA)
}
return comment
}
return comment
}
abstract val peak: Int
abstract fun commentStandardText(): String
companion object {
const val MIN_DIA = 5.0
}
}

View file

@ -3,11 +3,14 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.extensions.storeInt
import info.nightscout.androidaps.utils.extensions.putInt
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -23,12 +26,13 @@ class InsulinOrefFreePeakPlugin @Inject constructor(
rxBus: RxBusWrapper, aapsLogger: AAPSLogger
) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) {
override fun getId(): Int {
return InsulinInterface.OREF_FREE_PEAK
}
override val id get(): InsulinInterface.InsulinType = InsulinInterface.InsulinType.OREF_FREE_PEAK
override fun getFriendlyName(): String {
return resourceHelper.gs(R.string.free_peak_oref)
override val friendlyName get(): String = resourceHelper.gs(R.string.free_peak_oref)
override fun configuration(): JSONObject = JSONObject().putInt(R.string.key_insulin_oref_peak, sp, resourceHelper)
override fun applyConfiguration(configuration: JSONObject) {
configuration.storeInt(R.string.key_insulin_oref_peak, sp, resourceHelper)
}
override fun commentStandardText(): String {
@ -39,6 +43,7 @@ class InsulinOrefFreePeakPlugin @Inject constructor(
get() = sp.getInt(R.string.key_insulin_oref_peak, DEFAULT_PEAK)
companion object {
private const val DEFAULT_PEAK = 75
}

View file

@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -21,18 +22,13 @@ class InsulinOrefRapidActingPlugin @Inject constructor(
rxBus: RxBusWrapper, aapsLogger: AAPSLogger
) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) {
override val id get(): InsulinInterface.InsulinType = InsulinInterface.InsulinType.OREF_RAPID_ACTING
override val friendlyName get(): String = resourceHelper.gs(R.string.rapid_acting_oref)
override fun getId(): Int {
return InsulinInterface.OREF_RAPID_ACTING
}
override fun configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: JSONObject) {}
override fun getFriendlyName(): String {
return resourceHelper.gs(R.string.rapid_acting_oref)
}
override fun commentStandardText(): String {
return resourceHelper.gs(R.string.fastactinginsulincomment)
}
override fun commentStandardText(): String = resourceHelper.gs(R.string.fastactinginsulincomment)
override val peak = 75

View file

@ -3,10 +3,11 @@ package info.nightscout.androidaps.plugins.insulin
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.InsulinInterface
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
import javax.inject.Singleton
@ -21,10 +22,11 @@ class InsulinOrefUltraRapidActingPlugin @Inject constructor(
rxBus: RxBusWrapper, aapsLogger: AAPSLogger
) : InsulinOrefBasePlugin(injector, resourceHelper, profileFunction, rxBus, aapsLogger) {
override val id get(): InsulinInterface.InsulinType = InsulinInterface.InsulinType.OREF_ULTRA_RAPID_ACTING
override val friendlyName get(): String = resourceHelper.gs(R.string.ultrarapid_oref)
override fun getId(): Int = InsulinInterface.OREF_ULTRA_RAPID_ACTING
override fun getFriendlyName(): String = resourceHelper.gs(R.string.ultrarapid_oref)
override fun configuration(): JSONObject = JSONObject()
override fun applyConfiguration(configuration: JSONObject) {}
override fun commentStandardText(): String = resourceHelper.gs(R.string.ultrafastactinginsulincomment)

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;
}
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);

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