diff --git a/.gitignore b/.gitignore index c7ed9df2f5..961dd40194 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ build/ .idea/* !.idea/codeStyles/ -app/src/main/jniLibs full/ debug/ release/ diff --git a/.travis.yml b/.travis.yml index 165a1eff9a..d08c3bf279 100644 --- a/.travis.yml +++ b/.travis.yml @@ -8,7 +8,7 @@ android: components: - platform-tools - tools - - build-tools-28.0.3 + - build-tools-29.0.2 - android-28 - extra-google-m2repository - extra-android-m2repository diff --git a/README.md b/README.md index 32aef48cd9..f762852a96 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # AndroidAPS -* Check the wiki: http://wiki.androidaps.org +* Check the wiki: https://androidaps.readthedocs.io * Everyone who’s been looping with AndroidAPS needs to fill out the form after 3 days of looping https://docs.google.com/forms/d/14KcMjlINPMJHVt28MDRupa4sz4DDIooI4SrW0P3HSN8/viewform?c=0&w=1 [![Gitter](https://badges.gitter.im/MilosKozak/AndroidAPS.svg)](https://gitter.im/MilosKozak/AndroidAPS?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) @@ -11,4 +11,4 @@ dev: [![codecov](https://codecov.io/gh/MilosKozak/AndroidAPS/branch/dev/graph/badge.svg)](https://codecov.io/gh/MilosKozak/AndroidAPS) -[![Donate via PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Y4LHGJJESAVB8) \ No newline at end of file +![BTC](https://bitit.io/assets/coins/icon-btc-1e5a37bc0eb730ac83130d7aa859052bd4b53ac3f86f99966627801f7b0410be.svg) 3KawK8aQe48478s6fxJ8Ms6VTWkwjgr9f2 diff --git a/app/build.gradle b/app/build.gradle index 11e681d084..3780e2fd16 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,13 +1,12 @@ buildscript { repositories { - maven { url 'https://maven.fabric.io/public' } jcenter() + maven { url "https://plugins.gradle.org/m2/" } // jacoco 0.2 } dependencies { - classpath 'io.fabric.tools:gradle:1.+' - classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4' - classpath 'de.undercouch:gradle-download-task:3.4.3' + //classpath 'com.dicedmelon.gradle:jacoco-android:0.1.4' + classpath 'com.hiya:jacoco-android:0.2' } } apply plugin: 'com.android.application' @@ -15,26 +14,23 @@ apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' apply plugin: 'com.google.gms.google-services' -apply plugin: 'io.fabric' -apply plugin: 'jacoco-android' -apply plugin: 'de.undercouch.download' - +//apply plugin: 'jacoco-android' +apply plugin: 'com.hiya.jacoco-android' +apply plugin: 'com.google.firebase.crashlytics' jacoco { toolVersion = "0.8.3" } ext { - ormLiteVersion = "4.46" powermockVersion = "1.7.3" dexmakerVersion = "1.2" - retrofit2Version = '2.8.1' - okhttp3Version = '4.6.0' + retrofit2Version = '2.9.0' + okhttp3Version = '4.7.2' } repositories { - maven { url 'https://maven.fabric.io/public' } jcenter { url "https://jcenter.bintray.com/" } mavenCentral() google() @@ -126,7 +122,7 @@ android { ndkVersion "21.1.6352462" defaultConfig { - minSdkVersion 23 + minSdkVersion 24 targetSdkVersion 28 multiDexEnabled true versionCode 1500 @@ -139,9 +135,9 @@ android { // if you change minSdkVersion to less than 11, you need to change executeTask for wear // OMNIPOD: Keep track of what commit from the main repository we're on, these fields aren't actually used anywhere - buildConfigField "String", "DEV_VERSION", '"2.6.5-dev"' - buildConfigField "String", "DEV_VERSION_COMMIT", '"cf291b3adc2a8df06fd99220b59b500298c8e56f"' - buildConfigField "String", "DEV_VERSION_COMMIT_DATE", '"6.5.2020"' // 6th May + buildConfigField "String", "DEV_VERSION", '"2.6.7-dev"' + buildConfigField "String", "DEV_VERSION_COMMIT", '"65c8cc98804cfc366239ad2bedb2dd98e3e4f3c2"' + buildConfigField "String", "DEV_VERSION_COMMIT_DATE", '"16.8.2020"' // 16th of August ndk { moduleName "BleCommandUtil" @@ -249,16 +245,18 @@ dependencies { wearApp project(':wear') implementation project(':core') + implementation project(':dana') + implementation project(':danars') + implementation project(':danar') + implementation project(':rileylink') + implementation project(':medtronic') 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.0.0" - implementation 'com.google.firebase:firebase-core:17.4.0' + implementation 'com.google.firebase:firebase-core:17.4.3' implementation 'com.google.firebase:firebase-auth:19.3.1' - implementation 'com.google.firebase:firebase-database:19.3.0' - implementation('com.crashlytics.sdk.android:crashlytics:2.10.1@aar') { - transitive = true; - } + implementation 'com.google.firebase:firebase-database:19.3.1' implementation 'androidx.appcompat:appcompat:1.1.0' implementation 'androidx.legacy:legacy-support-v13:1.0.0' @@ -269,12 +267,12 @@ dependencies { implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'androidx.percentlayout:percentlayout:1.0.0' implementation "androidx.preference:preference-ktx:1.1.1" - implementation "androidx.activity:activity:${activityVersion}" implementation "androidx.activity:activity-ktx:${activityVersion}" + implementation "androidx.fragment:fragment:${fragmentVersion}" + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.android.material:material:1.1.0' - implementation 'com.wdullaer:materialdatetimepicker:4.2.3' - implementation "io.reactivex.rxjava2:rxandroid:2.1.1" + implementation "io.reactivex.rxjava2:rxandroid:${rxandroid_version}" implementation "com.j256.ormlite:ormlite-core:${ormLiteVersion}" implementation "com.j256.ormlite:ormlite-android:${ormLiteVersion}" @@ -286,10 +284,9 @@ dependencies { // Graphview cannot be upgraded implementation "com.jjoe64:graphview:4.0.1" implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2" - implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.madgag.spongycastle:core:1.58.0.0' + // Omnipod wizard implementation(name: "com.atech-software.android.library.wizardpager-1.1.4", ext: "aar") - implementation("com.google.android:flexbox:0.3.0") { exclude group: "com.android.support" } @@ -313,7 +310,7 @@ dependencies { implementation 'com.eatthepath:java-otp:0.2.0' testImplementation "junit:junit:4.13" - testImplementation "org.json:json:20190722" + testImplementation 'org.json:json:20200518' testImplementation "org.mockito:mockito-core:2.8.47" testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}" testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}" @@ -341,7 +338,7 @@ dependencies { // 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' @@ -362,30 +359,6 @@ dependencies { androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' } - -task downloadZipFile(type: Download) { - src 'https://github.com/MilosKozak/danars-support-lib/archive/master.zip' - dest new File(buildDir, 'danars.zip') -} - -task downloadAndUnzipFile(dependsOn: downloadZipFile, type: Copy) { - from zipTree(downloadZipFile.dest) - def outputDir = file("${buildDir}/unpacked/dist") - into outputDir -} - - -task copyLibs(dependsOn: downloadAndUnzipFile, type: Copy) { - def src = file("${buildDir}/unpacked/dist/danars-support-lib-master") - def target = file("src/main/jniLibs/") - - from src - into target -} - -task full_clean(type: Delete) { - delete file("src/main/jniLibs") -} /* // Run 'adb' shell command to clear application data of main app for 'debug' variant task clearMainAppData(type: Exec) { @@ -417,8 +390,6 @@ tasks.whenTaskAdded { task -> } } */ -clean.dependsOn full_clean -preBuild.dependsOn copyLibs printf('--------------\n') printf('isMaster: %s\n', isMaster().toString()) diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index a327989975..0a99af2948 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -8,16 +8,15 @@ import androidx.test.rule.GrantPermissionRule import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefUltraRapidActingPlugin import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.source.RandomBgPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin @@ -30,7 +29,6 @@ import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith -import org.slf4j.LoggerFactory import javax.inject.Inject @LargeTest @@ -44,7 +42,7 @@ class RealPumpTest { private val validProfile = "{\"dia\":\"6\",\"carbratio\":[{\"time\":\"00:00\",\"value\":\"30\"}],\"carbs_hr\":\"20\",\"delay\":\"20\",\"sens\":[{\"time\":\"00:00\",\"value\":\"10\"},{\"time\":\"2:00\",\"value\":\"11\"}],\"timezone\":\"UTC\",\"basal\":[{\"time\":\"00:00\",\"value\":\"0.1\"}],\"target_low\":[{\"time\":\"00:00\",\"value\":\"4\"}],\"target_high\":[{\"time\":\"00:00\",\"value\":\"5\"}],\"startDate\":\"1970-01-01T00:00:00.000Z\",\"units\":\"mmol\"}" - @Inject lateinit var pump : DanaRv2Plugin + @Inject lateinit var pump : info.nightscout.androidaps.danaRv2.DanaRv2Plugin @Inject lateinit var randomBgPlugin :RandomBgPlugin @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var profileFunction: ProfileFunction diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index cd4b814b6c..8f3db8e179 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -58,15 +58,6 @@ - - - - - @@ -74,17 +65,11 @@ - - - - - - - - + @@ -122,6 +107,9 @@ + + + - - - - @@ -286,16 +258,7 @@ android:name=".plugins.pump.medtronic.service.RileyLinkMedtronicService" android:enabled="true" android:exported="true" /> - - - - - - - + diff --git a/app/src/main/assets/OpenAPSSMB/determine-basal.js b/app/src/main/assets/OpenAPSSMB/determine-basal.js index 00a9c1d0a2..137ceca541 100644 --- a/app/src/main/assets/OpenAPSSMB/determine-basal.js +++ b/app/src/main/assets/OpenAPSSMB/determine-basal.js @@ -407,6 +407,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ , 'bg': bg , 'tick': tick , 'eventualBG': eventualBG + , 'targetBG': target_bg , 'insulinReq': 0 , 'reservoir' : reservoir_data // The expected reservoir volume at which to deliver the microbolus (the reservoir volume from right before the last pumphistory run) , 'deliverAt' : deliverAt // The time at which the microbolus should be delivered @@ -800,7 +801,7 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ rT.COB=meal_data.mealCOB; rT.IOB=iob_data.iob; - rT.reason="COB: " + meal_data.mealCOB + ", Dev: " + convert_bg(deviation, profile) + ", BGI: " + convert_bg(bgi, profile) + ", ISF: " + convert_bg(sens, profile) + ", CR: " + round(profile.carb_ratio, 2) + ", Target: " + convert_bg(target_bg, profile) + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile); + rT.reason="COB: " + round(meal_data.mealCOB, 1) + ", Dev: " + convert_bg(deviation, profile) + ", BGI: " + convert_bg(bgi, profile) + ", ISF: " + convert_bg(sens, profile) + ", CR: " + round(profile.carb_ratio, 2) + ", Target: " + convert_bg(target_bg, profile) + ", minPredBG " + convert_bg(minPredBG, profile) + ", minGuardBG " + convert_bg(minGuardBG, profile) + ", IOBpredBG " + convert_bg(lastIOBpredBG, profile); if (lastCOBpredBG > 0) { rT.reason += ", COBpredBG " + convert_bg(lastCOBpredBG, profile); } @@ -877,8 +878,10 @@ var determine_basal = function determine_basal(glucose_status, currenttemp, iob_ console.error("naive_eventualBG:",naive_eventualBG,"bgUndershoot:",bgUndershoot,"zeroTempDuration:",zeroTempDuration,"zeroTempEffect:",zeroTempEffect,"carbsReq:",carbsReq); if ( carbsReq >= profile.carbsReqThreshold && minutesAboveThreshold <= 45 ) { rT.carbsReq = carbsReq; + rT.carbsReqWithin = minutesAboveThreshold; rT.reason += carbsReq + " add'l carbs req w/in " + minutesAboveThreshold + "m; "; } + // don't low glucose suspend if IOB is already super negative and BG is rising faster than predicted if (bg < threshold && iob_data.iob < -profile.current_basal*20/60 && minDelta > 0 && minDelta > expectedDelta) { rT.reason += "IOB "+iob_data.iob+" < " + round(-profile.current_basal*20/60,2); diff --git a/app/src/main/java/info/nightscout/androidaps/Config.java b/app/src/main/java/info/nightscout/androidaps/Config.java deleted file mode 100644 index bb967cdeb6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/Config.java +++ /dev/null @@ -1,15 +0,0 @@ -package info.nightscout.androidaps; - -/** - * Created by mike on 07.06.2016. - */ -public class Config { - public static int SUPPORTEDNSVERSION = 1002; // 0.10.00 - - public static final boolean APS = BuildConfig.FLAVOR.equals("full"); - - public static final boolean NSCLIENT = BuildConfig.FLAVOR.equals("nsclient") || BuildConfig.FLAVOR.equals("nsclient2"); - public static final boolean PUMPCONTROL = BuildConfig.FLAVOR.equals("pumpcontrol"); - - public static final boolean PUMPDRIVERS = BuildConfig.FLAVOR.equals("full") || BuildConfig.FLAVOR.equals("pumpcontrol"); -} diff --git a/app/src/main/java/info/nightscout/androidaps/Config.kt b/app/src/main/java/info/nightscout/androidaps/Config.kt new file mode 100644 index 0000000000..c5edf0c438 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/Config.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps + +import info.nightscout.androidaps.interfaces.ConfigInterface +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class Config @Inject constructor(): ConfigInterface{ + + override val SUPPORTEDNSVERSION = 1002 // 0.10.00 + override val APS = BuildConfig.FLAVOR == "full" + override val NSCLIENT = BuildConfig.FLAVOR == "nsclient" || BuildConfig.FLAVOR == "nsclient2" + override val PUMPCONTROL = BuildConfig.FLAVOR == "pumpcontrol" + override val PUMPDRIVERS = BuildConfig.FLAVOR == "full" || BuildConfig.FLAVOR == "pumpcontrol" +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt index 4e58a1f21f..ff35d585ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -27,6 +27,7 @@ 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 info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.activities.SingleFragmentActivity @@ -49,10 +50,10 @@ import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicato import info.nightscout.androidaps.setupwizard.SetupWizardActivity import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.LocaleHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.isRunningRealPumpTest +import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -85,6 +86,7 @@ class MainActivity : NoSplashAppCompatActivity() { @Inject lateinit var iconsProvider: IconsProvider @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var signatureVerifierPlugin: SignatureVerifierPlugin + @Inject lateinit var config: Config private lateinit var actionBarDrawerToggle: ActionBarDrawerToggle private var pluginPreferencesMenuItem: MenuItem? = null @@ -137,15 +139,15 @@ class MainActivity : NoSplashAppCompatActivity() { } androidPermission.notifyForStoragePermission(this) androidPermission.notifyForBatteryOptimizationPermission(this) - if (Config.PUMPDRIVERS) { - androidPermission.notifyForLocationPermissions(this) + androidPermission.notifyForLocationPermissions(this) + if (config.PUMPDRIVERS) { androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin) androidPermission.notifyForSystemWindowPermissions(this) } } private fun checkPluginPreferences(viewPager: ViewPager2) { - pluginPreferencesMenuItem?.isEnabled = (viewPager.adapter as TabPageAdapter).getPluginAt(viewPager.currentItem).preferencesId != -1 + if (viewPager.currentItem >= 0) pluginPreferencesMenuItem?.isEnabled = (viewPager.adapter as TabPageAdapter).getPluginAt(viewPager.currentItem).preferencesId != -1 } override fun onPostCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { @@ -173,6 +175,7 @@ class MainActivity : NoSplashAppCompatActivity() { private fun processPreferenceChange(ev: EventPreferenceChange) { if (ev.isChanged(resourceHelper, R.string.key_keep_screen_on)) setWakeLock() + if (ev.isChanged(resourceHelper, R.string.key_skin)) recreate() } private fun setupViews() { @@ -322,6 +325,11 @@ class MainActivity : NoSplashAppCompatActivity() { return true } */ + R.id.nav_defaultprofile -> { + startActivity(Intent(this, ProfileHelperActivity::class.java)) + return true + } + R.id.nav_stats -> { startActivity(Intent(this, StatsActivity::class.java)) return true @@ -352,7 +360,7 @@ class MainActivity : NoSplashAppCompatActivity() { val hashes: List = signatureVerifierPlugin.shortHashes() if (hashes.isNotEmpty()) fabricPrivacy.firebaseAnalytics.setUserProperty("Hash", hashes[0]) activePlugin.activePump.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Pump", it::class.java.simpleName) } - if (!Config.NSCLIENT && !Config.PUMPCONTROL) + if (!config.NSCLIENT && !config.PUMPCONTROL) activePlugin.activeAPS.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Aps", it::class.java.simpleName) } activePlugin.activeBgSource.let { fabricPrivacy.firebaseAnalytics.setUserProperty("BgSource", it::class.java.simpleName) } fabricPrivacy.firebaseAnalytics.setUserProperty("Profile", activePlugin.activeProfileInterface.javaClass.simpleName) diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 66acee4016..ca60ca93d4 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -7,7 +7,6 @@ import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; -import androidx.annotation.StringRes; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import com.j256.ormlite.android.apptools.OpenHelperManager; @@ -21,6 +20,7 @@ import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.StaticInjector; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.logging.AAPSLogger; @@ -37,7 +37,7 @@ import info.nightscout.androidaps.receivers.NetworkChangeReceiver; import info.nightscout.androidaps.receivers.TimeDateOrTZChangeReceiver; import info.nightscout.androidaps.services.Intents; import info.nightscout.androidaps.utils.ActivityMonitor; -import info.nightscout.androidaps.utils.LocaleHelper; +import info.nightscout.androidaps.utils.locale.LocaleHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; public class MainApp extends DaggerApplication { @@ -52,11 +52,15 @@ public class MainApp extends DaggerApplication { @Inject ActivityMonitor activityMonitor; @Inject VersionCheckerUtils versionCheckersUtils; @Inject SP sp; + @Inject NSUpload nsUpload; + @Inject Config config; @Inject ConfigBuilderPlugin configBuilderPlugin; @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @Inject List plugins; + @Inject StaticInjector staticInjector; // TODO avoid , here fake only to initialize + @Override public void onCreate() { super.onCreate(); @@ -66,7 +70,7 @@ public class MainApp extends DaggerApplication { sResources = getResources(); LocaleHelper.INSTANCE.update(this); sDatabaseHelper = OpenHelperManager.getHelper(sInstance, DatabaseHelper.class); - +/* Thread.setDefaultUncaughtExceptionHandler((thread, ex) -> { if (ex instanceof InternalError) { // usually the app trying to spawn a thread while being killed @@ -74,7 +78,7 @@ public class MainApp extends DaggerApplication { } aapsLogger.error("Uncaught exception crashing app", ex); }); - +*/ registerActivityLifecycleCallbacks(activityMonitor); JodaTimeAndroid.init(this); @@ -92,7 +96,7 @@ public class MainApp extends DaggerApplication { pluginStore.setPlugins(plugins); configBuilderPlugin.initialize(); - NSUpload.uploadAppStart(); + nsUpload.uploadAppStart(); new Thread(() -> keepAliveManager.setAlarm(this)).start(); doMigrations(); @@ -100,7 +104,13 @@ public class MainApp extends DaggerApplication { private void doMigrations() { - + // set values for different builds + if (!sp.contains(R.string.key_ns_alarms)) + sp.putBoolean(R.string.key_ns_alarms, config.getNSCLIENT()); + if (!sp.contains(R.string.key_ns_announcements)) + sp.putBoolean(R.string.key_ns_announcements, config.getNSCLIENT()); + if (!sp.contains(R.string.key_language)) + sp.putString(R.string.key_language, "default"); } @Override @@ -111,6 +121,7 @@ public class MainApp extends DaggerApplication { .build(); } + @SuppressWarnings("deprecation") private void registerLocalBroadcastReceiver() { IntentFilter filter = new IntentFilter(); filter.addAction(Intents.ACTION_NEW_TREATMENT); @@ -145,16 +156,6 @@ public class MainApp extends DaggerApplication { registerReceiver(new BTReceiver(), filter); } - @Deprecated - public static String gs(@StringRes int id) { - return sResources.getString(id); - } - - @Deprecated - public static MainApp instance() { - return sInstance; - } - public static DatabaseHelper getDbHelper() { return sDatabaseHelper; } diff --git a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt index 08560e062e..e01ea6da78 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -13,19 +13,22 @@ import dagger.android.HasAndroidInjector import dagger.android.support.AndroidSupportInjection import info.nightscout.androidaps.Config import info.nightscout.androidaps.R +import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.danar.DanaRPlugin +import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.events.EventRebuildTabs import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.PluginStore -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.constraints.safety.SafetyPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin -import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus @@ -35,13 +38,8 @@ import info.nightscout.androidaps.plugins.general.wear.WearPlugin import info.nightscout.androidaps.plugins.general.xdripStatusline.StatusLinePlugin import info.nightscout.androidaps.plugins.insulin.InsulinOrefFreePeakPlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin -import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin @@ -67,19 +65,18 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var sp: SP @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var pluginStore: PluginStore + @Inject lateinit var config: Config @Inject lateinit var automationPlugin: AutomationPlugin @Inject lateinit var danaRPlugin: DanaRPlugin @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRv2Plugin: DanaRv2Plugin @Inject lateinit var danaRSPlugin: DanaRSPlugin - @Inject lateinit var careportalPlugin: CareportalPlugin @Inject lateinit var comboPlugin: ComboPlugin @Inject lateinit var insulinOrefFreePeakPlugin: InsulinOrefFreePeakPlugin @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var localInsightPlugin: LocalInsightPlugin @Inject lateinit var medtronicPumpPlugin: MedtronicPumpPlugin - @Inject lateinit var omnipodPumpPlugin: OmnipodPumpPlugin @Inject lateinit var nsClientPlugin: NSClientPlugin @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin @@ -102,6 +99,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang @Inject lateinit var passwordCheck: PasswordCheck @Inject lateinit var nsSettingStatus: NSSettingsStatus + // TODO why? @Inject lateinit var androidInjector: DispatchingAndroidInjector override fun androidInjector(): AndroidInjector = androidInjector @@ -161,22 +159,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(tomatoPlugin, rootKey) addPreferencesFromResourceIfEnabled(poctechPlugin, rootKey) addPreferencesFromResourceIfEnabled(glimpPlugin, rootKey) - addPreferencesFromResourceIfEnabled(careportalPlugin, rootKey) - addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, Config.APS) - addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, Config.APS) - addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, Config.APS) + addPreferencesFromResourceIfEnabled(loopPlugin, rootKey, config.APS) + addPreferencesFromResourceIfEnabled(openAPSAMAPlugin, rootKey, config.APS) + addPreferencesFromResourceIfEnabled(openAPSSMBPlugin, rootKey, config.APS) addPreferencesFromResourceIfEnabled(sensitivityAAPSPlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityWeightedAveragePlugin, rootKey) addPreferencesFromResourceIfEnabled(sensitivityOref1Plugin, rootKey) - addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(omnipodPumpPlugin, rootKey, Config.PUMPDRIVERS) - addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey, !Config.NSCLIENT) + addPreferencesFromResourceIfEnabled(danaRPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(danaRKoreanPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(danaRv2Plugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(danaRSPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(localInsightPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(comboPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(medtronicPumpPlugin, rootKey, config.PUMPDRIVERS) + addPreferencesFromResourceIfEnabled(virtualPumpPlugin, rootKey, !config.NSCLIENT) addPreferencesFromResourceIfEnabled(insulinOrefFreePeakPlugin, rootKey) addPreferencesFromResourceIfEnabled(nsClientPlugin, rootKey) addPreferencesFromResourceIfEnabled(tidepoolPlugin, rootKey) @@ -189,9 +185,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang addPreferencesFromResourceIfEnabled(maintenancePlugin, rootKey) } initSummary(preferenceScreen, pluginId != -1) - for (plugin in pluginStore.plugins) { - plugin.preprocessPreferences(this) - } + preprocessPreferences() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { @@ -208,12 +202,49 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang activity?.recreate() return } - if (key == resourceHelper.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) + if (key == resourceHelper.gs(R.string.key_openapsama_useautosens) && sp.getBoolean(R.string.key_openapsama_useautosens, false)) { activity?.let { show(it, resourceHelper.gs(R.string.configbuilder_sensitivity), resourceHelper.gs(R.string.sensitivity_warning)) } + } + checkForBiometricFallback(key) updatePrefSummary(findPreference(key)) + preprocessPreferences() + } + + private fun preprocessPreferences() { + for (plugin in pluginStore.plugins) { + plugin.preprocessPreferences(this) + } + } + + private fun checkForBiometricFallback(key: String) { + // Biometric protection activated without set master password + if ((resourceHelper.gs(R.string.key_settings_protection) == key || + resourceHelper.gs(R.string.key_application_protection) == key || + resourceHelper.gs(R.string.key_bolus_protection) == key) && + sp.getString(R.string.key_master_password, "") == "" && + sp.getInt(key, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal + ) { + activity?.let { + val title = resourceHelper.gs(R.string.unsecure_fallback_biometric) + val message = resourceHelper.gs(R.string.master_password_missing, resourceHelper.gs(R.string.configbuilder_general), resourceHelper.gs(R.string.protection)) + show(it, title = title, message = message) + } + } + + // Master password erased with activated Biometric protection + val isBiometricActivated = sp.getInt(R.string.key_settings_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal || + sp.getInt(R.string.key_application_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal || + sp.getInt(R.string.key_bolus_protection, ProtectionCheck.ProtectionType.NONE.ordinal) == ProtectionCheck.ProtectionType.BIOMETRIC.ordinal + if (resourceHelper.gs(R.string.key_master_password) == key && sp.getString(key, "") == "" && isBiometricActivated) { + activity?.let { + val title = resourceHelper.gs(R.string.unsecure_fallback_biometric) + val message = resourceHelper.gs(R.string.unsecure_fallback_descriotion_biometric) + show(it, title = title, message = message) + } + } } @SuppressLint("RestrictedApi") @@ -242,11 +273,9 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang resourceHelper.gs(R.string.key_high_mark), resourceHelper.gs(R.string.key_low_mark) ) - if (listOf(*unitDependent).contains(pref.key)) { - val editTextPref = pref as EditTextPreference - val converted = Profile.toCurrentUnitsString(profileFunction, SafeParse.stringToDouble(editTextPref.text)) - editTextPref.summary = converted - editTextPref.text = converted + if (unitDependent.toList().contains(pref.key) && pref is EditTextPreference) { + val converted = Profile.toCurrentUnits(profileFunction, SafeParse.stringToDouble(pref.text)) + pref.summary = converted.toString() } } @@ -282,7 +311,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } for (plugin in pluginStore.plugins) { - pref?.let { it.key?.let { plugin.updatePreferenceSummary(pref) }} + pref?.let { it.key?.let { plugin.updatePreferenceSummary(pref) } } } val hmacPasswords = arrayOf( diff --git a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt index ad3961c883..ea90f4b250 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/PreferencesActivity.kt @@ -5,7 +5,7 @@ import android.os.Bundle import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceScreen import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.LocaleHelper +import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt new file mode 100644 index 0000000000..efb7e57b19 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/activities/ProfileHelperActivity.kt @@ -0,0 +1,288 @@ +package info.nightscout.androidaps.activities + +import android.content.res.ColorStateList +import android.os.Bundle +import android.text.Editable +import android.text.TextWatcher +import android.view.Menu +import android.widget.PopupMenu +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.data.defaultProfile.DefaultProfile +import info.nightscout.androidaps.data.defaultProfile.DefaultProfileDPV +import info.nightscout.androidaps.db.ProfileSwitch +import info.nightscout.androidaps.dialogs.ProfileViewerDialog +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin +import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.ToastUtils +import info.nightscout.androidaps.utils.alertDialogs.OKDialog +import info.nightscout.androidaps.utils.extensions.toVisibility +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.stats.TddCalculator +import kotlinx.android.synthetic.main.activity_profilehelper.* +import java.text.DecimalFormat +import javax.inject.Inject + +class ProfileHelperActivity : NoSplashAppCompatActivity() { + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var tddCalculator: TddCalculator + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var defaultProfile: DefaultProfile + @Inject lateinit var defaultProfileDPV: DefaultProfileDPV + @Inject lateinit var localProfilePlugin: LocalProfilePlugin + @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var activePlugin: ActivePluginProvider + @Inject lateinit var databaseHelper: DatabaseHelperInterface + + enum class ProfileType { + MOTOL_DEFAULT, + DPV_DEFAULT, + CURRENT, + AVAILABLE_PROFILE, + PROFILE_SWITCH + } + + private var tabSelected = 0 + private val typeSelected = arrayOf(ProfileType.MOTOL_DEFAULT, ProfileType.CURRENT) + + private val ageUsed = arrayOf(15.0, 15.0) + private val weightUsed = arrayOf(0.0, 0.0) + private val tddUsed = arrayOf(0.0, 0.0) + private val pctUsed = arrayOf(32.0, 32.0) + + private lateinit var profileList: ArrayList + private val profileUsed = arrayOf(0, 0) + + private lateinit var profileSwitch: List + private val profileSwitchUsed = arrayOf(0, 0) + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_profilehelper) + + profilehelper_menu1.setOnClickListener { + switchTab(0, typeSelected[0]) + } + profilehelper_menu2.setOnClickListener { + switchTab(1, typeSelected[1]) + } + + profilehelper_profiletype.setOnClickListener { + PopupMenu(this, profilehelper_profiletype).apply { + menuInflater.inflate(R.menu.menu_profilehelper, menu) + setOnMenuItemClickListener { item -> + profilehelper_profiletype.setText(item.title) + when (item.itemId) { + R.id.menu_default -> switchTab(tabSelected, ProfileType.MOTOL_DEFAULT) + R.id.menu_default_dpv -> switchTab(tabSelected, ProfileType.DPV_DEFAULT) + R.id.menu_current -> switchTab(tabSelected, ProfileType.CURRENT) + R.id.menu_available -> switchTab(tabSelected, ProfileType.AVAILABLE_PROFILE) + R.id.menu_profileswitch -> switchTab(tabSelected, ProfileType.PROFILE_SWITCH) + } + true + } + show() + } + } + + // Active profile + profileList = activePlugin.activeProfileInterface.profile?.getProfileList() ?: ArrayList() + + profilehelper_available_profile_list.setOnClickListener { + PopupMenu(this, profilehelper_available_profile_list).apply { + var order = 0 + for (name in profileList) menu.add(Menu.NONE, order, order++, name) + setOnMenuItemClickListener { item -> + profilehelper_available_profile_list.setText(item.title) + profileUsed[tabSelected] = item.itemId + true + } + show() + } + } + + // Profile switch + profileSwitch = databaseHelper.getProfileSwitchData(dateUtil._now() - T.months(2).msecs(), true) + + profilehelper_profileswitch_list.setOnClickListener { + PopupMenu(this, profilehelper_profileswitch_list).apply { + var order = 0 + for (name in profileSwitch) menu.add(Menu.NONE, order, order++, name.customizedName) + setOnMenuItemClickListener { item -> + profilehelper_profileswitch_list.setText(item.title) + profileSwitchUsed[tabSelected] = item.itemId + true + } + show() + } + } + + // Default profile + profilehelper_copytolocalprofile.setOnClickListener { + val age = ageUsed[tabSelected] + val weight = weightUsed[tabSelected] + val tdd = tddUsed[tabSelected] + val pct = pctUsed[tabSelected] + val profile = if (typeSelected[tabSelected] == ProfileType.MOTOL_DEFAULT) defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) + else defaultProfileDPV.profile(age, tdd, pct / 100.0, profileFunction.getUnits()) + profile?.let { + OKDialog.showConfirmation(this, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile), Runnable { + localProfilePlugin.addProfile(localProfilePlugin.copyFrom(it, "DefaultProfile" + dateUtil.dateAndTimeAndSecondsString(dateUtil._now()))) + rxBus.send(EventLocalProfileChanged()) + }) + } + } + + profilehelper_age.setParams(0.0, 1.0, 18.0, 1.0, DecimalFormat("0"), false, null) + profilehelper_weight.setParams(0.0, 0.0, 150.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher { + override fun afterTextChanged(s: Editable) {} + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + profilehelper_tdd_row.visibility = (profilehelper_weight.value == 0.0).toVisibility() + } + }) + profilehelper_tdd.setParams(0.0, 0.0, 200.0, 1.0, DecimalFormat("0"), false, null, object : TextWatcher { + override fun afterTextChanged(s: Editable) {} + override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { + profilehelper_weight_row.visibility = (profilehelper_tdd.value == 0.0).toVisibility() + } + }) + + profilehelper_basalpctfromtdd.setParams(32.0, 32.0, 37.0, 1.0, DecimalFormat("0"), false, null) + + profilehelper_tdds.text = tddCalculator.stats() + + // Current profile + profilehelper_current_profile_text.text = profileFunction.getProfileName() + + // General + profilehelper_compareprofile.setOnClickListener { + storeValues() + for (i in 0..1) { + if (typeSelected[i] == ProfileType.MOTOL_DEFAULT) { + if (ageUsed[i] < 1 || ageUsed[i] > 18) { + ToastUtils.showToastInUiThread(this, R.string.invalidage) + return@setOnClickListener + } + if ((weightUsed[i] < 5 || weightUsed[i] > 150) && tddUsed[i] == 0.0) { + ToastUtils.showToastInUiThread(this, R.string.invalidweight) + return@setOnClickListener + } + if ((tddUsed[i] < 5 || tddUsed[i] > 150) && weightUsed[i] == 0.0) { + ToastUtils.showToastInUiThread(this, R.string.invalidweight) + return@setOnClickListener + } + } + if (typeSelected[i] == ProfileType.DPV_DEFAULT) { + if (ageUsed[i] < 1 || ageUsed[i] > 18) { + ToastUtils.showToastInUiThread(this, R.string.invalidage) + return@setOnClickListener + } + if (tddUsed[i] < 5 || tddUsed[i] > 150) { + ToastUtils.showToastInUiThread(this, R.string.invalidweight) + return@setOnClickListener + } + if ((pctUsed[i] < 32 || pctUsed[i] > 37)) { + ToastUtils.showToastInUiThread(this, R.string.invalidpct) + return@setOnClickListener + } + } + } + + getProfile(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0)?.let { profile0 -> + getProfile(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)?.let { profile1 -> + ProfileViewerDialog().also { pvd -> + pvd.arguments = Bundle().also { + it.putLong("time", DateUtil.now()) + it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) + it.putString("customProfile", profile0.data.toString()) + it.putString("customProfile2", profile1.data.toString()) + it.putString("customProfileUnits", profileFunction.getUnits()) + it.putString("customProfileName", getProfileName(ageUsed[0], tddUsed[0], weightUsed[0], pctUsed[0] / 100.0, 0) + "\n" + getProfileName(ageUsed[1], tddUsed[1], weightUsed[1], pctUsed[1] / 100.0, 1)) + } + }.show(supportFragmentManager, "ProfileViewDialog") + return@setOnClickListener + } + } + ToastUtils.showToastInUiThread(this, R.string.invalidinput) + } + + switchTab(0, typeSelected[0], false) + } + + private fun getProfile(age: Double, tdd: Double, weight: Double, basalPct: Double, tab: Int): Profile? = + when (typeSelected[tab]) { + ProfileType.MOTOL_DEFAULT -> defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) + ProfileType.DPV_DEFAULT -> defaultProfileDPV.profile(age, tdd, basalPct, profileFunction.getUnits()) + ProfileType.CURRENT -> profileFunction.getProfile()?.convertToNonCustomizedProfile() + ProfileType.AVAILABLE_PROFILE -> activePlugin.activeProfileInterface.profile?.getSpecificProfile(profileList[profileUsed[tab]].toString()) + ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].profileObject?.convertToNonCustomizedProfile() + } + + private fun getProfileName(age: Double, tdd: Double, weight: Double, basalSumPct: Double, tab: Int): String = + when (typeSelected[tab]) { + ProfileType.MOTOL_DEFAULT -> if (tdd > 0) resourceHelper.gs(R.string.formatwithtdd, age, tdd) else resourceHelper.gs(R.string.formatwithweight, age, weight) + ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.formatwittddandpct, age, tdd, (basalSumPct * 100).toInt()) + ProfileType.CURRENT -> profileFunction.getProfileName() + ProfileType.AVAILABLE_PROFILE -> profileList[profileUsed[tab]].toString() + ProfileType.PROFILE_SWITCH -> profileSwitch[profileSwitchUsed[tab]].customizedName + } + + private fun storeValues() { + ageUsed[tabSelected] = profilehelper_age.value + weightUsed[tabSelected] = profilehelper_weight.value + tddUsed[tabSelected] = profilehelper_tdd.value + pctUsed[tabSelected] = profilehelper_basalpctfromtdd.value + } + + private fun switchTab(tab: Int, newContent: ProfileType, storeOld: Boolean = true) { + setBackgroundColorOnSelected(tab) + // Store values for selected tab. listBox values are stored on selection change + if (storeOld) storeValues() + + tabSelected = tab + typeSelected[tabSelected] = newContent + profilehelper_profiletype_title.defaultHintTextColor = ColorStateList.valueOf(resourceHelper.gc(if (tab == 0) R.color.tabBgColorSelected else R.color.examinedProfile)) + + // show new content + profilehelper_profiletype.setText( + when (typeSelected[tabSelected]) { + ProfileType.MOTOL_DEFAULT -> resourceHelper.gs(R.string.motoldefaultprofile) + ProfileType.DPV_DEFAULT -> resourceHelper.gs(R.string.dpvdefaultprofile) + ProfileType.CURRENT -> resourceHelper.gs(R.string.currentprofile) + ProfileType.AVAILABLE_PROFILE -> resourceHelper.gs(R.string.availableprofile) + ProfileType.PROFILE_SWITCH -> resourceHelper.gs(R.string.careportal_profileswitch) + }) + profilehelper_default_profile.visibility = (newContent == ProfileType.MOTOL_DEFAULT || newContent == ProfileType.DPV_DEFAULT).toVisibility() + profilehelper_current_profile.visibility = (newContent == ProfileType.CURRENT).toVisibility() + profilehelper_available_profile.visibility = (newContent == ProfileType.AVAILABLE_PROFILE).toVisibility() + profilehelper_profile_switch.visibility = (newContent == ProfileType.PROFILE_SWITCH).toVisibility() + + // restore selected values + profilehelper_age.value = ageUsed[tabSelected] + profilehelper_weight.value = weightUsed[tabSelected] + profilehelper_tdd.value = tddUsed[tabSelected] + profilehelper_basalpctfromtdd.value = pctUsed[tabSelected] + + profilehelper_basalpctfromtdd_row.visibility = (newContent == ProfileType.DPV_DEFAULT).toVisibility() + if (profileList.isNotEmpty()) + profilehelper_available_profile_list.setText(profileList[profileUsed[tabSelected]].toString()) + if (profileSwitch.isNotEmpty()) + profilehelper_profileswitch_list.setText(profileSwitch[profileSwitchUsed[tabSelected]].customizedName) + } + + private fun setBackgroundColorOnSelected(tab: Int) { + profilehelper_menu1.setBackgroundColor(resourceHelper.gc(if (tab == 1) R.color.defaultbackground else R.color.tabBgColorSelected)) + profilehelper_menu2.setBackgroundColor(resourceHelper.gc(if (tab == 0) R.color.defaultbackground else R.color.examinedProfile)) + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.kt index 9e62f16c97..0193b690a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SingleFragmentActivity.kt @@ -9,7 +9,7 @@ import dagger.android.support.DaggerAppCompatActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.configBuilder.PluginStore -import info.nightscout.androidaps.utils.LocaleHelper +import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt index 6ea91d443a..ca26266f8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/StatsActivity.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.activities import android.os.Bundle import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.ActivityMonitor +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TirCalculator diff --git a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt index 2a5e8bcecd..1d03ddb344 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -8,9 +8,9 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.defaultProfile.DefaultProfile import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.utils.ActivityMonitor import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.InstanceId @@ -19,7 +19,7 @@ import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.androidaps.utils.stats.TirCalculator -import kotlinx.android.synthetic.main.survey_activity.* +import kotlinx.android.synthetic.main.activity_survey.* import javax.inject.Inject class SurveyActivity : NoSplashAppCompatActivity() { @@ -34,7 +34,7 @@ class SurveyActivity : NoSplashAppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - setContentView(R.layout.survey_activity) + setContentView(R.layout.activity_survey) survey_id.text = InstanceId.instanceId() @@ -62,16 +62,20 @@ class SurveyActivity : NoSplashAppCompatActivity() { ToastUtils.showToastInUiThread(this, R.string.invalidweight) return@setOnClickListener } - val profile = defaultProfile.profile(age, tdd, weight, profileFunction.getUnits()) - val args = Bundle() - args.putLong("time", DateUtil.now()) - args.putInt("mode", ProfileViewerDialog.Mode.CUSTOM_PROFILE.ordinal) - args.putString("customProfile", profile.data.toString()) - args.putString("customProfileUnits", profile.units) - args.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight") - val pvd = ProfileViewerDialog() - pvd.arguments = args - pvd.show(supportFragmentManager, "ProfileViewDialog") + profileFunction.getProfile()?.let { runningProfile -> + defaultProfile.profile(age, tdd, weight, profileFunction.getUnits())?.let { profile -> + ProfileViewerDialog().also { pvd -> + pvd.arguments = Bundle().also { + it.putLong("time", DateUtil.now()) + it.putInt("mode", ProfileViewerDialog.Mode.PROFILE_COMPARE.ordinal) + it.putString("customProfile", runningProfile.data.toString()) + it.putString("customProfile2", profile.data.toString()) + it.putString("customProfileUnits", profile.units) + it.putString("customProfileName", "Age: $age TDD: $tdd Weight: $weight") + } + }.show(supportFragmentManager, "ProfileViewDialog") + } + } } survey_submit.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java index 5759429d69..7ba9957ed8 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -17,7 +17,6 @@ import com.j256.ormlite.table.TableUtils; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; import java.util.ArrayList; @@ -29,11 +28,13 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.inject.Inject; + import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.dana.comm.RecordTypes; import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; @@ -46,15 +47,13 @@ import info.nightscout.androidaps.events.EventTempBasalChange; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.ProfileInterface; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.interfaces.ProfileStore; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin; -import info.nightscout.androidaps.plugins.configBuilder.PluginStore; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryBgData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; import info.nightscout.androidaps.plugins.pump.insight.database.InsightBolusID; import info.nightscout.androidaps.plugins.pump.insight.database.InsightHistoryOffset; import info.nightscout.androidaps.plugins.pump.insight.database.InsightPumpID; @@ -62,7 +61,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.db.PodHistory; import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin; import info.nightscout.androidaps.utils.JsonHelper; import info.nightscout.androidaps.utils.PercentageSplitter; -import info.nightscout.androidaps.utils.ToastUtils; +import info.nightscout.androidaps.utils.T; /** * This Helper contains all resource to provide a central DB management functionality. Only methods handling @@ -73,7 +72,9 @@ import info.nightscout.androidaps.utils.ToastUtils; * direct calls to the corresponding methods (eg. resetDatabases) should be done by a central service. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATABASE); + @Inject AAPSLogger aapsLogger; + @Inject RxBusWrapper rxBus; + @Inject VirtualPumpPlugin virtualPumpPlugin; public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_BGREADINGS = "BgReadings"; @@ -83,7 +84,6 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public static final String DATABASE_DANARHISTORY = "DanaRHistory"; public static final String DATABASE_DBREQUESTS = "DBRequests"; public static final String DATABASE_CAREPORTALEVENTS = "CareportalEvents"; - public static final String DATABASE_PROFILESWITCHES = "ProfileSwitches"; public static final String DATABASE_TDDS = "TDDs"; public static final String DATABASE_INSIGHT_HISTORY_OFFSETS = "InsightHistoryOffsets"; public static final String DATABASE_INSIGHT_BOLUS_IDS = "InsightBolusIDs"; @@ -97,6 +97,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static final ScheduledExecutorService bgWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledBgPost = null; + private static final ScheduledExecutorService bgHistoryWorker = Executors.newSingleThreadScheduledExecutor(); + private static ScheduledFuture scheduledBgHistoryPost = null; + private static long oldestBgHistoryChange = 0; + private static final ScheduledExecutorService tempBasalsWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledTemBasalsPost = null; @@ -117,6 +121,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); + StaticInjector.Companion.getInstance().androidInjector().inject(this); onCreate(getWritableDatabase(), getConnectionSource()); //onUpgrade(getWritableDatabase(), getConnectionSource(), 1,1); } @@ -124,8 +129,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { - if (L.isEnabled(LTag.DATABASE)) - log.info("onCreate"); + aapsLogger.info(LTag.DATABASE, "onCreate"); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); TableUtils.createTableIfNotExists(connectionSource, DanaRHistoryRecord.class); @@ -144,7 +148,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { database.execSQL("INSERT INTO sqlite_sequence (name, seq) SELECT \"" + DATABASE_INSIGHT_PUMP_IDS + "\", " + System.currentTimeMillis() + " " + "WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\")"); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } @@ -156,7 +160,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { this.newVersion = newVersion; if (oldVersion < 7) { - log.info(DatabaseHelper.class.getName(), "onUpgrade"); + aapsLogger.info(LTag.DATABASE, "onUpgrade"); TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.dropTable(connectionSource, BgReading.class, true); TableUtils.dropTable(connectionSource, DanaRHistoryRecord.class, true); @@ -179,15 +183,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { database.execSQL("UPDATE sqlite_sequence SET seq = " + System.currentTimeMillis() + " WHERE name = \"" + DATABASE_INSIGHT_PUMP_IDS + "\""); } } catch (SQLException e) { - log.error("Can't drop databases", e); + aapsLogger.error("Can't drop databases", e); throw new RuntimeException(e); } } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { - log.info("Do nothing for downgrading..."); - log.debug("oldVersion: {}, newVersion: {}", oldVersion, newVersion); + aapsLogger.info(LTag.DATABASE, "Do nothing for downgrading..."); + aapsLogger.info(LTag.DATABASE, "oldVersion: {}, newVersion: {}", oldVersion, newVersion); } public int getOldVersion() { @@ -228,9 +232,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, PodHistory.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + virtualPumpPlugin.setFakingStatus(true); scheduleBgChange(null); // trigger refresh scheduleTemporaryBasalChange(); scheduleExtendedBolusChange(); @@ -241,7 +245,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { new java.util.TimerTask() { @Override public void run() { - RxBus.Companion.getINSTANCE().send(new EventRefreshOverview("resetDatabases", false)); + rxBus.send(new EventRefreshOverview("resetDatabases", false)); } }, 3000 @@ -253,7 +257,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, TempTarget.class, true); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTemporaryTargetChange(); } @@ -264,9 +268,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, TemporaryBasal.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(false); + virtualPumpPlugin.setFakingStatus(false); scheduleTemporaryBasalChange(); } @@ -276,7 +280,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.createTableIfNotExists(connectionSource, ExtendedBolus.class); updateEarliestDataChange(0); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleExtendedBolusChange(); } @@ -286,7 +290,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, CareportalEvent.class, true); TableUtils.createTableIfNotExists(connectionSource, CareportalEvent.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -296,7 +300,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, ProfileSwitch.class, true); TableUtils.createTableIfNotExists(connectionSource, ProfileSwitch.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleProfileSwitchChange(); } @@ -306,7 +310,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { TableUtils.dropTable(connectionSource, TDD.class, true); TableUtils.createTableIfNotExists(connectionSource, TDD.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -364,11 +368,10 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return getDao(PodHistory.class); } - public static long roundDateToSec(long date) { + public long roundDateToSec(long date) { long rounded = date - date % 1000; if (rounded != date) - if (L.isEnabled(LTag.DATABASE)) - log.debug("Rounding " + date + " to " + rounded); + aapsLogger.debug(LTag.DATABASE, "Rounding " + date + " to " + rounded); return rounded; } // ------------------- BgReading handling ----------------------- @@ -379,23 +382,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { BgReading old = getDaoBgReadings().queryForId(bgReading.date); if (old == null) { getDaoBgReadings().create(bgReading); - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: New record from: " + from + " " + bgReading.toString()); + aapsLogger.debug(LTag.DATABASE, "BG: New record from: " + from + " " + bgReading.toString()); scheduleBgChange(bgReading); return true; } if (!old.isEqual(bgReading)) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: Similiar found: " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "BG: Similiar found: " + old.toString()); old.copyFrom(bgReading); getDaoBgReadings().update(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); - scheduleBgChange(bgReading); + aapsLogger.debug(LTag.DATABASE, "BG: Updating record from: " + from + " New data: " + old.toString()); + scheduleBgHistoryChange(old.date); // trigger cache invalidation return false; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -405,16 +405,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoBgReadings().update(bgReading); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleBgChange(@Nullable final BgReading bgReading) { + private void scheduleBgChange(@Nullable final BgReading bgReading) { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventNewBg"); - RxBus.Companion.getINSTANCE().send(new EventNewBG(bgReading)); + aapsLogger.debug(LTag.DATABASE, "Firing EventNewBg"); + rxBus.send(new EventNewBG(bgReading)); scheduledBgPost = null; } } @@ -428,6 +427,26 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } + private void scheduleBgHistoryChange(@Nullable final long timestamp) { + class PostRunnable implements Runnable { + public void run() { + aapsLogger.debug(LTag.DATABASE, "Firing EventNewBg"); + rxBus.send(new EventNewHistoryBgData(oldestBgHistoryChange)); + scheduledBgHistoryPost = null; + oldestBgHistoryChange = 0; + } + } + // prepare task for execution in 1 sec + // cancel waiting task to prevent sending multiple posts + if (scheduledBgHistoryPost != null) + scheduledBgHistoryPost.cancel(false); + Runnable task = new PostRunnable(); + final int sec = 3; + if (oldestBgHistoryChange == 0 || oldestBgHistoryChange > timestamp) oldestBgHistoryChange = timestamp; + scheduledBgHistoryPost = bgHistoryWorker.schedule(task, sec, TimeUnit.SECONDS); + + } + public List getBgreadingsDataFromTime(long mills, boolean ascending) { try { Dao daoBgreadings = getDaoBgReadings(); @@ -440,7 +459,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -457,7 +476,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -474,7 +493,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { bgReadings = daoBgreadings.query(preparedQuery); return bgReadings; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -485,8 +504,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Dao dao = getDaoTDD(); dao.createOrUpdate(tdd); } catch (SQLException e) { - ToastUtils.showToastInUiThread(MainApp.instance(), "createOrUpdate-Exception"); - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -499,7 +517,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); tddList = getDaoTDD().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); tddList = new ArrayList<>(); } return tddList; @@ -518,7 +536,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); tddList = getDaoTDD().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); tddList = new ArrayList<>(); } return tddList; @@ -534,7 +552,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().delete(dbr); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -543,7 +561,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().deleteById(nsClientId); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -560,7 +578,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { delete(r); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -568,7 +586,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { TableUtils.clearTable(connectionSource, DbRequest.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -576,7 +594,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoDbRequest().closeableIterator(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); return null; } } @@ -607,7 +625,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempTargets = daoTempTargets.query(preparedQuery); return tempTargets; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -624,7 +642,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempTargets = daoTempTargets.query(preparedQuery); return tempTargets; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -641,8 +659,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } @@ -661,28 +678,25 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(old); // need to delete/create because date may change too old.copyFrom(tempTarget); getDaoTempTargets().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; } } } getDaoTempTargets().create(tempTarget); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } if (tempTarget.source == Source.USER) { getDaoTempTargets().create(tempTarget); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -692,16 +706,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTempTargets().delete(tempTarget); scheduleTemporaryTargetChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleTemporaryTargetChange() { + private void scheduleTemporaryTargetChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventTempTargetChange"); - RxBus.Companion.getINSTANCE().send(new EventTempTargetChange()); + aapsLogger.debug(LTag.DATABASE, "Firing EventTempTargetChange"); + rxBus.send(new EventTempTargetChange()); scheduledTemTargetPost = null; } } @@ -743,14 +756,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .source(Source.NIGHTSCOUT); createOrUpdate(tempTarget); } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteTempTargetById(String _id) { TempTarget stored = findTempTargetById(_id); if (stored != null) { - log.debug("TEMPTARGET: Removing TempTarget record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPTARGET: Removing TempTarget record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); } @@ -770,7 +783,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -787,7 +800,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -802,7 +815,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); historyList = getDaoDanaRHistory().query(preparedQuery); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); historyList = new ArrayList<>(); } return historyList; @@ -825,8 +838,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List trList = getDaoTemporaryBasal().query(preparedQuery); if (trList.size() > 0) { // do nothing, pump history record cannot be changed - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); return false; } @@ -843,8 +855,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { old.copyFromPump(tempBasal); old.source = Source.PUMP; - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); getDaoTemporaryBasal().update(old); @@ -855,8 +866,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; @@ -873,8 +883,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -896,8 +905,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(old); // need to delete/create because date may change too old.copyFrom(tempBasal); getDaoTemporaryBasal().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleTemporaryBasalChange(); @@ -906,22 +914,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; } if (tempBasal.source == Source.USER) { getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -931,7 +937,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoTemporaryBasal().delete(tempBasal); updateEarliestDataChange(tempBasal.date); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleTemporaryBasalChange(); } @@ -947,7 +953,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempbasals = getDaoTemporaryBasal().query(preparedQuery); return tempbasals; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -963,20 +969,19 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { tempbasals = getDaoTemporaryBasal().query(preparedQuery); return tempbasals; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } - private static void scheduleTemporaryBasalChange() { + private void scheduleTemporaryBasalChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventTempBasalChange"); - RxBus.Companion.getINSTANCE().send(new EventReloadTempBasalData()); - RxBus.Companion.getINSTANCE().send(new EventTempBasalChange()); + aapsLogger.debug(LTag.DATABASE, "Firing EventTempBasalChange"); + rxBus.send(new EventReloadTempBasalData()); + rxBus.send(new EventTempBasalChange()); if (earliestDataChange != null) - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange)); + rxBus.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledTemBasalsPost = null; } @@ -1010,7 +1015,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void createTempBasalFromJsonIfNotExists(JSONObject trJson) { try { if (trJson.has("originalExtendedAmount")) { // extended bolus uploaded as temp basal - ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()) + ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance()) .source(Source.NIGHTSCOUT) .date(trJson.getLong("mills")) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0) @@ -1018,14 +1023,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .insulin(trJson.getDouble("originalExtendedAmount")) ._id(trJson.getString("_id")); // if faking found in NS, adapt AAPS to use it too - if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) { - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + if (!virtualPumpPlugin.getFakingStatus()) { + virtualPumpPlugin.setFakingStatus(true); updateEarliestDataChange(0); scheduleTemporaryBasalChange(); } createOrUpdate(extendedBolus); } else if (trJson.has("isFakedTempBasal")) { // extended bolus end uploaded as temp basal end - ExtendedBolus extendedBolus = new ExtendedBolus(MainApp.instance()); + ExtendedBolus extendedBolus = new ExtendedBolus(StaticInjector.Companion.getInstance()); extendedBolus.source = Source.NIGHTSCOUT; extendedBolus.date = trJson.getLong("mills"); extendedBolus.pumpId = trJson.has("pumpId") ? trJson.getLong("pumpId") : 0; @@ -1033,14 +1038,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBolus.insulin = 0; extendedBolus._id = trJson.getString("_id"); // if faking found in NS, adapt AAPS to use it too - if (!VirtualPumpPlugin.Companion.getPlugin().getFakingStatus()) { - VirtualPumpPlugin.Companion.getPlugin().setFakingStatus(true); + if (!virtualPumpPlugin.getFakingStatus()) { + virtualPumpPlugin.setFakingStatus(true); updateEarliestDataChange(0); scheduleTemporaryBasalChange(); } createOrUpdate(extendedBolus); } else { - TemporaryBasal tempBasal = new TemporaryBasal( MainApp.instance()) + TemporaryBasal tempBasal = new TemporaryBasal(StaticInjector.Companion.getInstance()) .date(trJson.getLong("mills")) .source(Source.NIGHTSCOUT) .pumpId(trJson.has("pumpId") ? trJson.getLong("pumpId") : 0); @@ -1059,15 +1064,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { createOrUpdate(tempBasal); } } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteTempBasalById(String _id) { TemporaryBasal stored = findTempBasalById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleTemporaryBasalChange(); @@ -1089,7 +1093,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return list.get(0); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1111,7 +1115,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1121,8 +1125,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public boolean createOrUpdate(ExtendedBolus extendedBolus) { try { - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); ExtendedBolus old; extendedBolus.date = roundDateToSec(extendedBolus.date); @@ -1141,13 +1144,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { PreparedQuery preparedQuery = queryBuilder.prepare(); List trList = getDaoExtendedBolus().query(preparedQuery); if (trList.size() > 1) { - log.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId); + aapsLogger.error("EXTENDEDBOLUS: Multiple records found for pumpId: " + extendedBolus.pumpId); return false; } getDaoExtendedBolus().createOrUpdate(extendedBolus); } - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; @@ -1160,8 +1162,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1183,8 +1184,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(old); // need to delete/create because date may change too old.copyFrom(extendedBolus); getDaoExtendedBolus().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); scheduleExtendedBolusChange(); @@ -1193,22 +1193,20 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; } if (extendedBolus.source == Source.USER) { getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -1219,7 +1217,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .where().eq("pumpId", pumpId) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1229,7 +1227,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoExtendedBolus().delete(extendedBolus); updateEarliestDataChange(extendedBolus.date); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleExtendedBolusChange(); } @@ -1245,7 +1243,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBoluses = getDaoExtendedBolus().query(preparedQuery); return extendedBoluses; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -1261,7 +1259,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { extendedBoluses = getDaoExtendedBolus().query(preparedQuery); return extendedBoluses; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList(); } @@ -1269,8 +1267,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteExtendedBolusById(String _id) { ExtendedBolus stored = findExtendedBolusById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); scheduleExtendedBolusChange(); @@ -1292,7 +1289,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1315,19 +1312,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { */ public void createExtendedBolusFromJsonIfNotExists(JSONObject json) { - ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(MainApp.instance(), json); + ExtendedBolus extendedBolus = ExtendedBolus.createFromJson(StaticInjector.Companion.getInstance(), json); if (extendedBolus != null) createOrUpdate(extendedBolus); } - private static void scheduleExtendedBolusChange() { + private void scheduleExtendedBolusChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventExtendedBolusChange"); - RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventExtendedBolusChange())); + aapsLogger.debug(LTag.DATABASE, "Firing EventExtendedBolusChange"); + rxBus.send(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) - RxBus.Companion.getINSTANCE().send(new EventNewHistoryData(earliestDataChange)); + rxBus.send(new EventNewHistoryData(earliestDataChange)); earliestDataChange = null; scheduledExtendedBolusPost = null; } @@ -1350,7 +1346,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoCareportalEvents().createOrUpdate(careportalEvent); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -1359,7 +1355,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoCareportalEvents().delete(careportalEvent); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleCareportalEventChange(); } @@ -1368,7 +1364,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoCareportalEvents().queryForId(timestamp); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1389,7 +1385,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { else return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1406,7 +1402,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1423,7 +1419,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1452,7 +1448,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1469,7 +1465,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvents = preprocessOpenAPSOfflineEvents(careportalEvents); return careportalEvents; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1485,15 +1481,13 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 1) { CareportalEvent record = list.get(0); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Removing CareportalEvent record from database: " + record.toString()); + aapsLogger.debug(LTag.DATABASE, "Removing CareportalEvent record from database: " + record.toString()); delete(record); } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("CareportalEvent not found database: " + _id); + aapsLogger.debug(LTag.DATABASE, "CareportalEvent not found database: " + _id); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1507,17 +1501,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { List list = getDaoCareportalEvents().query(preparedQuery); CareportalEvent careportalEvent; if (list.size() == 0) { - careportalEvent = new CareportalEvent(MainApp.instance()); + careportalEvent = new CareportalEvent(StaticInjector.Companion.getInstance()); careportalEvent.source = Source.NIGHTSCOUT; - if (L.isEnabled(LTag.DATABASE)) - log.debug("Adding CareportalEvent record to database: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Adding CareportalEvent record to database: " + trJson.toString()); // Record does not exists. add } else if (list.size() == 1) { careportalEvent = list.get(0); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Updating CareportalEvent record in database: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Updating CareportalEvent record in database: " + trJson.toString()); } else { - log.error("Something went wrong"); + aapsLogger.error("Something went wrong"); return; } careportalEvent.date = trJson.getLong("mills"); @@ -1526,16 +1518,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { careportalEvent._id = trJson.getString("_id"); createOrUpdate(careportalEvent); } catch (SQLException | JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } - private static void scheduleCareportalEventChange() { + private void scheduleCareportalEventChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing scheduleCareportalEventChange"); - RxBus.Companion.getINSTANCE().send(new EventCareportalEventChange()); + aapsLogger.debug(LTag.DATABASE, "Firing scheduleCareportalEventChange"); + rxBus.send(new EventCareportalEventChange()); scheduledCareportalEventPost = null; } } @@ -1565,16 +1556,23 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { //add last one without duration ProfileSwitch last = getLastProfileSwitchWithoutDuration(); if (last != null) { - if (!profileSwitches.contains(last)) + if (!isInList(profileSwitches, last)) profileSwitches.add(last); } return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } + boolean isInList(List profileSwitches, ProfileSwitch last) { + for (ProfileSwitch ps : profileSwitches) { + if (ps.isEqual(last)) return true; + } + return false; + } + @Nullable private ProfileSwitch getLastProfileSwitchWithoutDuration() { try { @@ -1592,7 +1590,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { else return null; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1610,7 +1608,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitches = daoProfileSwitch.query(preparedQuery); return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1628,7 +1626,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitches = daoProfileSwitch.query(preparedQuery); return profileSwitches; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } @@ -1646,8 +1644,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profileName = old.profileName; // preserver profileName to prevent multiple CPP extension getDaoProfileSwitch().delete(old); // need to delete/create because date may change too getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1666,8 +1663,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoProfileSwitch().delete(old); // need to delete/create because date may change too old.copyFrom(profileSwitch); getDaoProfileSwitch().create(old); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; } @@ -1676,20 +1672,18 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // look for already added percentage from NS profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } if (profileSwitch.source == Source.USER) { getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return false; } @@ -1699,17 +1693,16 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { getDaoProfileSwitch().delete(profileSwitch); scheduleProfileSwitchChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - private static void scheduleProfileSwitchChange() { + private void scheduleProfileSwitchChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Firing EventProfileNeedsUpdate"); - RxBus.Companion.getINSTANCE().send(new EventReloadProfileSwitchData()); - RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); + aapsLogger.debug(LTag.DATABASE, "Firing EventProfileNeedsUpdate"); + rxBus.send(new EventReloadProfileSwitchData()); + rxBus.send(new EventProfileNeedsUpdate()); scheduledProfileSwitchEventPost = null; } } @@ -1735,9 +1728,9 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } */ - public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, JSONObject trJson) { + public void createProfileSwitchFromJsonIfNotExists(ActivePluginProvider activePluginProvider, NSUpload nsUpload, JSONObject trJson) { try { - ProfileSwitch profileSwitch = new ProfileSwitch(MainApp.instance()); + ProfileSwitch profileSwitch = new ProfileSwitch(StaticInjector.Companion.getInstance()); profileSwitch.date = trJson.getLong("mills"); if (trJson.has("duration")) profileSwitch.durationInMinutes = trJson.getInt("duration"); @@ -1758,18 +1751,15 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Profile profile = store.getSpecificProfile(profileSwitch.profileName); if (profile != null) { profileSwitch.profileJson = profile.getData().toString(); - if (L.isEnabled(LTag.DATABASE)) - log.debug("Profile switch prefilled with JSON from local store"); + aapsLogger.debug(LTag.DATABASE, "Profile switch prefilled with JSON from local store"); // Update data in NS - NSUpload.updateProfileSwitch(profileSwitch); + nsUpload.updateProfileSwitch(profileSwitch); } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } else { - if (L.isEnabled(LTag.DATABASE)) - log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); + aapsLogger.debug(LTag.DATABASE, "Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } @@ -1777,15 +1767,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { profileSwitch.profilePlugin = trJson.getString("profilePlugin"); createOrUpdate(profileSwitch); } catch (JSONException e) { - log.error("Unhandled exception: " + trJson.toString(), e); + aapsLogger.error("Unhandled exception: " + trJson.toString(), e); } } public void deleteProfileSwitchById(String _id) { ProfileSwitch stored = findProfileSwitchById(_id); if (stored != null) { - if (L.isEnabled(LTag.DATABASE)) - log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATABASE, "PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); } @@ -1805,7 +1794,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return null; } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1816,7 +1805,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightHistoryOffset().createOrUpdate(offset); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1824,7 +1813,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { return getDaoInsightHistoryOffset().queryForId(pumpSerial); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1833,7 +1822,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightBolusID().createOrUpdate(bolusID); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1845,7 +1834,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .and().between("timestamp", timestamp - 259200000, timestamp + 259200000) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1854,7 +1843,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoInsightPumpID().createOrUpdate(pumpID); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1867,7 +1856,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { .and().lt("timestamp", before) .queryForFirst(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } @@ -1880,7 +1869,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { try { getDaoPodHistory().createOrUpdate(podHistory); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -1898,9 +1887,57 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { podHistories = daoPodHistory.query(preparedQuery); return podHistories; } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); } + + // Copied from xDrip+ + String calculateDirection(BgReading bgReading) { + // Rework to get bgreaings from internal DB and calculate on that base + + List bgReadingsList = MainApp.getDbHelper().getAllBgreadingsDataFromTime(bgReading.date - T.mins(10).msecs(), false); + if (bgReadingsList == null || bgReadingsList.size() < 2) + return "NONE"; + BgReading current = bgReadingsList.get(1); + BgReading previous = bgReadingsList.get(0); + + if (bgReadingsList.get(1).date < bgReadingsList.get(0).date) { + current = bgReadingsList.get(0); + previous = bgReadingsList.get(1); + } + + double slope; + + // Avoid division by 0 + if (current.date == previous.date) + slope = 0; + else + slope = (previous.value - current.value) / (previous.date - current.date); + +// aapsLogger.error(LTag.GLUCOSE, "Slope is :" + slope + " delta " + (previous.value - current.value) + " date difference " + (current.date - previous.date)); + + double slope_by_minute = slope * 60000; + String arrow = "NONE"; + + if (slope_by_minute <= (-3.5)) { + arrow = "DoubleDown"; + } else if (slope_by_minute <= (-2)) { + arrow = "SingleDown"; + } else if (slope_by_minute <= (-1)) { + arrow = "FortyFiveDown"; + } else if (slope_by_minute <= (1)) { + arrow = "Flat"; + } else if (slope_by_minute <= (2)) { + arrow = "FortyFiveUp"; + } else if (slope_by_minute <= (3.5)) { + arrow = "SingleUp"; + } else if (slope_by_minute <= (40)) { + arrow = "DoubleUp"; + } +// aapsLogger.error(LTag.GLUCOSE, "Direction set to: " + arrow); + return arrow; + } + } diff --git a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java new file mode 100644 index 0000000000..0e9f9d82b2 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelperProvider.java @@ -0,0 +1,101 @@ +package info.nightscout.androidaps.db; + +import com.j256.ormlite.dao.CloseableIterator; + +import org.jetbrains.annotations.NotNull; + +import java.sql.SQLException; +import java.util.List; + +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; + +@Singleton +public class DatabaseHelperProvider implements DatabaseHelperInterface { + + @Inject DatabaseHelperProvider() {} + + @NotNull @Override public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { + return MainApp.getDbHelper().getAllBgreadingsDataFromTime(mills, ascending); + } + + @Override public void createOrUpdate(@NotNull CareportalEvent careportalEvent) { + MainApp.getDbHelper().createOrUpdate(careportalEvent); + } + + @Override public void createOrUpdate(@NotNull DanaRHistoryRecord record) { + MainApp.getDbHelper().createOrUpdate(record); + } + + @NotNull @Override public List getDanaRHistoryRecordsByType(byte type) { + return MainApp.getDbHelper().getDanaRHistoryRecordsByType(type); + } + + @NotNull @Override public List getTDDs() { + return MainApp.getDbHelper().getTDDs(); + } + + @Override public long size(@NotNull String table) { + return MainApp.getDbHelper().size(table); + } + + @Override public void create(@NotNull DbRequest record) { + try { + MainApp.getDbHelper().create(record); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override public void deleteAllDbRequests() { + MainApp.getDbHelper().deleteAllDbRequests(); + } + + @Override public int deleteDbRequest(@NotNull String id) { + return MainApp.getDbHelper().deleteDbRequest(id); + } + + @Override public void deleteDbRequestbyMongoId(@NotNull String action, @NotNull String _id) { + MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); + } + + @NotNull @Override public CloseableIterator getDbRequestInterator() { + return MainApp.getDbHelper().getDbRequestInterator(); + } + + @Override public long roundDateToSec(long date) { + return MainApp.getDbHelper().roundDateToSec(date); + } + + @Override public void createOrUpdateTDD(@NotNull TDD record) { + MainApp.getDbHelper().createOrUpdateTDD(record); + } + + @Override public void createOrUpdate(@NotNull TemporaryBasal tempBasal) { + MainApp.getDbHelper().createOrUpdate(tempBasal); + } + + @NotNull @Override public TemporaryBasal findTempBasalByPumpId(long id) { + return MainApp.getDbHelper().findTempBasalByPumpId(id); + } + + @NotNull @Override public List getTemporaryBasalsDataFromTime(long mills, boolean ascending) { + return MainApp.getDbHelper().getTemporaryBasalsDataFromTime(mills, ascending); + } + + @NotNull @Override public CareportalEvent getCareportalEventFromTimestamp(long timestamp) { + return MainApp.getDbHelper().getCareportalEventFromTimestamp(timestamp); + } + + @NotNull @Override public List getTDDsForLastXDays(int days) { + return MainApp.getDbHelper().getTDDsForLastXDays(days); + } + + @NotNull @Override public List getProfileSwitchData(long from, boolean ascending) { + return MainApp.getDbHelper().getProfileSwitchData(from, ascending); + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt index d3fef14166..0e55e30b85 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalAdapterAM import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread @@ -17,12 +17,10 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread abstract class APSModule { @ContributesAndroidInjector abstract fun loggerCallbackInjector(): LoggerCallback - @ContributesAndroidInjector abstract fun apsResultInjector(): APSResult @ContributesAndroidInjector abstract fun determineBasalResultSMBInjector(): DetermineBasalResultSMB @ContributesAndroidInjector abstract fun determineBasalResultAMAInjector(): DetermineBasalResultAMA @ContributesAndroidInjector abstract fun determineBasalAdapterAMAJSInjector(): DetermineBasalAdapterAMAJS @ContributesAndroidInjector abstract fun determineBasalAdapterSMBJSInjector(): DetermineBasalAdapterSMBJS - @ContributesAndroidInjector abstract fun autosensDataInjector(): AutosensData @ContributesAndroidInjector abstract fun iobCobThreadInjector(): IobCobThread @ContributesAndroidInjector abstract fun iobCobOref1ThreadInjector(): IobCobOref1Thread } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt index 134be115db..3c2e89b348 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -11,10 +11,6 @@ import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizar import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusActivity -import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRHistoryActivity -import info.nightscout.androidaps.plugins.pump.danaR.activities.DanaRUserOptionsActivity -import info.nightscout.androidaps.plugins.pump.danaRS.activities.BLEScanActivity -import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightAlertActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingActivity import info.nightscout.androidaps.plugins.pump.insight.activities.InsightPairingInformationActivity @@ -25,11 +21,6 @@ import info.nightscout.androidaps.setupwizard.SetupWizardActivity @Suppress("unused") abstract class ActivitiesModule { - @ContributesAndroidInjector abstract fun contributesBLEScanActivity(): BLEScanActivity - @ContributesAndroidInjector abstract fun contributeBolusProgressHelperActivity(): BolusProgressHelperActivity - @ContributesAndroidInjector abstract fun contributeDanaRHistoryActivity(): DanaRHistoryActivity - @ContributesAndroidInjector abstract fun contributeDanaRUserOptionsActivity(): DanaRUserOptionsActivity - @ContributesAndroidInjector abstract fun contributeErrorHelperActivity(): ErrorHelperActivity @ContributesAndroidInjector abstract fun contributesHistoryBrowseActivity(): HistoryBrowseActivity @ContributesAndroidInjector abstract fun contributesInsightAlertActivity(): InsightAlertActivity @ContributesAndroidInjector abstract fun contributesInsightPairingActivity(): InsightPairingActivity @@ -37,7 +28,6 @@ abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesLogSettingActivity(): LogSettingActivity @ContributesAndroidInjector abstract fun contributeMainActivity(): MainActivity @ContributesAndroidInjector abstract fun contributesMedtronicHistoryActivity(): MedtronicHistoryActivity - @ContributesAndroidInjector abstract fun contributesPairingHelperActivity(): PairingHelperActivity @ContributesAndroidInjector abstract fun contributesPreferencesActivity(): PreferencesActivity @ContributesAndroidInjector abstract fun contributesQuickWizardListActivity(): QuickWizardListActivity @ContributesAndroidInjector abstract fun contributesRequestDexcomPermissionActivity(): RequestDexcomPermissionActivity @@ -48,5 +38,6 @@ abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesSmsCommunicatorOtpActivity(): SmsCommunicatorOtpActivity @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity + @ContributesAndroidInjector abstract fun contributesDefaultProfileActivity(): ProfileHelperActivity @ContributesAndroidInjector abstract fun contributesPrefImportListActivity(): PrefImportListActivity } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt index 387de6419c..e45db6c006 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,56 +5,18 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.core.dependencyInjection.CoreModule -import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.data.ProfileStore -import info.nightscout.androidaps.data.PumpEnactResult -import info.nightscout.androidaps.db.BgReading -import info.nightscout.androidaps.db.CareportalEvent -import info.nightscout.androidaps.db.ProfileSwitch -import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback -import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB -import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* -import info.nightscout.androidaps.plugins.general.automation.AutomationEvent -import info.nightscout.androidaps.plugins.general.automation.actions.* -import info.nightscout.androidaps.plugins.general.automation.elements.* -import info.nightscout.androidaps.plugins.general.automation.triggers.* -import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData -import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction -import info.nightscout.androidaps.plugins.general.smsCommunicator.AuthRequest -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SendAndListen -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.command.SetPreamble -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioPacket -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RadioResponse -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* -import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager -import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask -import info.nightscout.androidaps.plugins.treatments.Treatment -import info.nightscout.androidaps.queue.CommandQueue -import info.nightscout.androidaps.queue.commands.* -import info.nightscout.androidaps.setupwizard.SWEventListener -import info.nightscout.androidaps.setupwizard.SWScreen -import info.nightscout.androidaps.setupwizard.elements.* -import info.nightscout.androidaps.utils.wizard.BolusWizard -import info.nightscout.androidaps.utils.wizard.QuickWizardEntry +import info.nightscout.androidaps.core.di.CoreModule +import info.nightscout.androidaps.dana.di.DanaModule +import info.nightscout.androidaps.danar.di.DanaRModule +import info.nightscout.androidaps.danars.di.DanaRSModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, - CoreModule::class, + PluginsModule::class, + SkinsModule::class, ActivitiesModule::class, FragmentsModule::class, AppModule::class, @@ -65,13 +27,17 @@ import javax.inject.Singleton ObjectivesModule::class, WizardModule::class, MedtronicModule::class, + OmnipodModule::class, APSModule::class, PreferencesModule::class, OverviewModule::class, DataClassesModule::class, SMSModule::class, UIModule::class, - OmnipodModule::class + CoreModule::class, + DanaModule::class, + DanaRModule::class, + DanaRSModule::class ] ) interface AppComponent : AndroidInjector { diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt index 944fe3615f..4fb00e9bb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -8,46 +8,34 @@ import dagger.Provides import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.db.DatabaseHelperProvider +import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.PluginStore -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunctionImplementation +import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.CommandQueue -import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.androidNotification.NotificationHolder import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.Storage import javax.inject.Singleton @Module(includes = [ - AppModule.AppBindings::class, - PluginsModule::class, - SkinsModule::class + AppModule.AppBindings::class ]) open class AppModule { @Provides - @Singleton - fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction { - return ProfileFunctionImplementation(injector, aapsLogger, sp, resourceHelper, activePlugin, fabricPrivacy) - } - - @Provides - fun providesPlugins(@PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>, + fun providesPlugins(configInterface: ConfigInterface, + @PluginsModule.AllConfigs allConfigs: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards PluginBase>, @PluginsModule.PumpDriver pumpDrivers: Lazy>, @PluginsModule.NotNSClient notNsClient: Lazy>, - @PluginsModule.NSClient nsClient: Lazy>, @PluginsModule.APS aps: Lazy>) : List<@JvmSuppressWildcards PluginBase> { val plugins = allConfigs.toMutableMap() - if (Config.PUMPDRIVERS) plugins += pumpDrivers.get() - if (Config.APS) plugins += aps.get() - if (!Config.NSCLIENT) plugins += notNsClient.get() - if (Config.NSCLIENT) plugins += nsClient.get() + if (configInterface.PUMPDRIVERS) plugins += pumpDrivers.get() + if (configInterface.APS) plugins += aps.get() + if (!configInterface.NSCLIENT) plugins += notNsClient.get() return plugins.toList().sortedBy { it.first }.map { it.second } } @@ -63,7 +51,12 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider - @Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider - + @Binds fun bindCommandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider + @Binds fun bindConfigInterface(config: Config): ConfigInterface + @Binds fun bindConfigBuilderInterface(configBuilderPlugin: ConfigBuilderPlugin): ConfigBuilderInterface + @Binds fun bindTreatmentInterface(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface + @Binds fun bindDatabaseHelperInterface(databaseHelperProvider: DatabaseHelperProvider): DatabaseHelperInterface + @Binds fun bindUploadQueueInterface(uploadQueue: UploadQueue): UploadQueueInterface + @Binds fun bindNotificationHolderInterface(notificationHolder: NotificationHolder): NotificationHolderInterface } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt index b0850bacc2..e9339e187b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/CommandQueueModule.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.queue.CommandQueue import info.nightscout.androidaps.queue.commands.* @@ -10,8 +9,6 @@ import info.nightscout.androidaps.queue.commands.* @Suppress("unused") abstract class CommandQueueModule { - @ContributesAndroidInjector abstract fun pumpEnactResultInjector(): PumpEnactResult - @ContributesAndroidInjector abstract fun commandQueueInjector(): CommandQueue @ContributesAndroidInjector abstract fun commandBolusInjector(): CommandBolus @ContributesAndroidInjector abstract fun commandCancelExtendedBolusInjector(): CommandCancelExtendedBolus diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt index 99ffb12f25..c63e70ace8 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/DataClassesModule.kt @@ -3,14 +3,10 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.data.ProfileStore -import info.nightscout.androidaps.db.BgReading -import info.nightscout.androidaps.db.CareportalEvent -import info.nightscout.androidaps.db.ExtendedBolus -import info.nightscout.androidaps.db.ProfileSwitch -import info.nightscout.androidaps.db.TemporaryBasal +import info.nightscout.androidaps.db.* +import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.plugins.general.food.FoodService import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @@ -19,18 +15,11 @@ import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @Suppress("unused") abstract class DataClassesModule { - @ContributesAndroidInjector abstract fun profileInjector(): Profile @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus - @ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore - - @ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading - @ContributesAndroidInjector abstract fun treatmentInjector(): Treatment - @ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch - @ContributesAndroidInjector abstract fun temporaryBasalInjector(): TemporaryBasal - @ContributesAndroidInjector abstract fun careportalEventInjector(): CareportalEvent - @ContributesAndroidInjector abstract fun extendedBolusInjector(): ExtendedBolus + @ContributesAndroidInjector abstract fun DatabaseHelperInjector(): DatabaseHelper @ContributesAndroidInjector abstract fun treatmentServiceInjector(): TreatmentService + @ContributesAndroidInjector abstract fun foodServiceInjector(): FoodService @ContributesAndroidInjector abstract fun bolusWizardInjector(): BolusWizard @ContributesAndroidInjector abstract fun quickWizardEntryInjector(): QuickWizardEntry diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt index f9753fda61..cde5137ac9 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.OpenAPSSMBFragment import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderFragment import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog -import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog import info.nightscout.androidaps.plugins.general.actions.ActionsFragment import info.nightscout.androidaps.plugins.general.automation.AutomationFragment import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseActionDialog @@ -18,8 +17,6 @@ import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTrigg import info.nightscout.androidaps.plugins.general.automation.dialogs.EditActionDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditEventDialog import info.nightscout.androidaps.plugins.general.automation.dialogs.EditTriggerDialog -import info.nightscout.androidaps.plugins.general.careportal.CareportalFragment -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog import info.nightscout.androidaps.plugins.general.food.FoodFragment import info.nightscout.androidaps.plugins.general.maintenance.MaintenanceFragment import info.nightscout.androidaps.plugins.general.nsclient.NSClientFragment @@ -34,7 +31,6 @@ import info.nightscout.androidaps.plugins.profile.ns.NSProfileFragment import info.nightscout.androidaps.plugins.pump.combo.ComboFragment import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusGeneralFragment import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.dialog.RileyLinkStatusHistoryFragment -import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment import info.nightscout.androidaps.plugins.pump.insight.LocalInsightFragment import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicFragment import info.nightscout.androidaps.plugins.pump.medtronic.dialog.RileyLinkStatusDeviceMedtronic @@ -54,13 +50,11 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesActionsFragment(): ActionsFragment @ContributesAndroidInjector abstract fun contributesAutomationFragment(): AutomationFragment @ContributesAndroidInjector abstract fun contributesBGSourceFragment(): BGSourceFragment - @ContributesAndroidInjector abstract fun contributesCareportalFragment(): CareportalFragment @ContributesAndroidInjector abstract fun contributesComboFragment(): ComboFragment @ContributesAndroidInjector abstract fun contributesConfigBuilderFragment(): ConfigBuilderFragment - @ContributesAndroidInjector abstract fun contributesDanaRFragment(): DanaRFragment @ContributesAndroidInjector abstract fun contributesFoodFragment(): FoodFragment @ContributesAndroidInjector abstract fun contributesInsulinFragment(): InsulinFragment @ContributesAndroidInjector abstract fun contributesLocalProfileFragment(): LocalProfileFragment @@ -89,7 +83,6 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesVirtualPumpFragment(): VirtualPumpFragment - @ContributesAndroidInjector abstract fun contributesBolusProgressDialog(): BolusProgressDialog @ContributesAndroidInjector abstract fun contributesCalibrationDialog(): CalibrationDialog @ContributesAndroidInjector abstract fun contributesCarbsDialog(): CarbsDialog @ContributesAndroidInjector abstract fun contributesCareDialog(): CareDialog @@ -100,17 +93,13 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesEditQuickWizardDialog(): EditQuickWizardDialog - @ContributesAndroidInjector abstract fun contributesErrorDialog(): ErrorDialog @ContributesAndroidInjector abstract fun contributesExtendedBolusDialog(): ExtendedBolusDialog @ContributesAndroidInjector abstract fun contributesFillDialog(): FillDialog @ContributesAndroidInjector abstract fun contributesChooseActionDialog(): ChooseActionDialog @ContributesAndroidInjector abstract fun contributesChooseTriggerDialog(): ChooseTriggerDialog @ContributesAndroidInjector abstract fun contributesInsulinDialog(): InsulinDialog - @ContributesAndroidInjector abstract fun contributesNewNSTreatmentDialog(): NewNSTreatmentDialog - @ContributesAndroidInjector abstract fun contributesNtpProgressDialog(): NtpProgressDialog @ContributesAndroidInjector abstract fun contributesObjectivesExamDialog(): ObjectivesExamDialog @ContributesAndroidInjector abstract fun contributesProfileSwitchDialog(): ProfileSwitchDialog - @ContributesAndroidInjector abstract fun contributesProfileViewerDialog(): ProfileViewerDialog @ContributesAndroidInjector abstract fun contributesTempBasalDialog(): TempBasalDialog @ContributesAndroidInjector abstract fun contributesTempTargetDialog(): TempTargetDialog @ContributesAndroidInjector abstract fun contributesTreatmentDialog(): TreatmentDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt index 7166906611..f813a6d49d 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/MedtronicModule.kt @@ -2,10 +2,6 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.plugins.general.automation.AutomationEvent -import info.nightscout.androidaps.plugins.general.automation.actions.* -import info.nightscout.androidaps.plugins.general.automation.elements.* -import info.nightscout.androidaps.plugins.general.automation.triggers.* import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE @@ -16,8 +12,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Radi import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.* import info.nightscout.androidaps.plugins.pump.medtronic.comm.MedtronicCommunicationManager import info.nightscout.androidaps.plugins.pump.medtronic.comm.ui.MedtronicUITask -import info.nightscout.androidaps.queue.CommandQueue -import info.nightscout.androidaps.queue.commands.* @Module @Suppress("unused") diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt index a47a316fd2..0e73cea942 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt @@ -19,6 +19,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsPodStateManager import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUITask +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Singleton @@ -53,7 +54,7 @@ abstract class OmnipodModule { @Provides @Singleton fun podStateManagerProvider(aapsLogger: AAPSLogger, sp: SP, omnipodPumpStatus: OmnipodPumpStatus, - rxBus: RxBusWrapper, resourceHelper: ResourceHelper): PodStateManager = - AapsPodStateManager(aapsLogger, sp, omnipodPumpStatus, rxBus, resourceHelper) + rxBus: RxBusWrapper, resourceHelper: ResourceHelper, dateUtil: DateUtil): PodStateManager = + AapsPodStateManager(aapsLogger, sp, omnipodPumpStatus, rxBus, resourceHelper, dateUtil) } } diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt index d022d3a726..196e5b1203 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OverviewModule.kt @@ -2,16 +2,8 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB -import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread @Module @Suppress("unused") diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt index c790f58c32..41c1615fe0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PluginsModule.kt @@ -1,13 +1,13 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Binds -import dagger.Lazy import dagger.Module -import dagger.Provides import dagger.multibindings.IntKey import dagger.multibindings.IntoMap -import dagger.multibindings.IntoSet -import info.nightscout.androidaps.Config +import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.danar.DanaRPlugin +import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin @@ -21,7 +21,6 @@ import info.nightscout.androidaps.plugins.constraints.storage.StorageConstraintP import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerPlugin import info.nightscout.androidaps.plugins.general.actions.ActionsPlugin import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin -import info.nightscout.androidaps.plugins.general.careportal.CareportalPlugin import info.nightscout.androidaps.plugins.general.dataBroadcaster.DataBroadcastPlugin import info.nightscout.androidaps.plugins.general.food.FoodPlugin import info.nightscout.androidaps.plugins.general.maintenance.MaintenancePlugin @@ -38,10 +37,6 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorP import info.nightscout.androidaps.plugins.profile.local.LocalProfilePlugin import info.nightscout.androidaps.plugins.profile.ns.NSProfilePlugin import info.nightscout.androidaps.plugins.pump.combo.ComboPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.pump.mdi.MDIPlugin import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin @@ -70,7 +65,7 @@ abstract class PluginsModule { abstract fun bindIobCobCalculatorPlugin(plugin: IobCobCalculatorPlugin): PluginBase @Binds - @NotNSClient + @AllConfigs @IntoMap @IntKey(20) abstract fun bindActionsPlugin(plugin: ActionsPlugin): PluginBase @@ -165,12 +160,6 @@ abstract class PluginsModule { @IntKey(170) abstract fun bindVirtualPumpPlugin(plugin: VirtualPumpPlugin): PluginBase - @Binds - @NSClient - @IntoMap - @IntKey(180) - abstract fun bindCareportalPlugin(plugin: CareportalPlugin): PluginBase - @Binds @APS @IntoMap @@ -202,7 +191,7 @@ abstract class PluginsModule { abstract fun bindLocalProfilePlugin(plugin: LocalProfilePlugin): PluginBase @Binds - @AllConfigs + @APS @IntoMap @IntKey(250) abstract fun bindAutomationPlugin(plugin: AutomationPlugin): PluginBase @@ -231,7 +220,6 @@ abstract class PluginsModule { @IntKey(280) abstract fun bindSmsCommunicatorPlugin(plugin: SmsCommunicatorPlugin): PluginBase - @Binds @APS @IntoMap @@ -367,9 +355,6 @@ abstract class PluginsModule { @Qualifier annotation class NotNSClient - @Qualifier - annotation class NSClient - @Qualifier annotation class APS diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt index 0921ed7cd0..4c6e67608c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ReceiversModule.kt @@ -4,8 +4,10 @@ import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBluetoothStateReceiver import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkBroadcastReceiver +import info.nightscout.androidaps.plugins.aps.loop.CarbSuggestionReceiver import info.nightscout.androidaps.receivers.* + @Module @Suppress("unused") abstract class ReceiversModule { @@ -14,10 +16,9 @@ abstract class ReceiversModule { @ContributesAndroidInjector abstract fun contributesChargingStateReceiver(): ChargingStateReceiver @ContributesAndroidInjector abstract fun contributesDataReceiver(): DataReceiver @ContributesAndroidInjector abstract fun contributesKeepAliveReceiver(): KeepAliveReceiver - @ContributesAndroidInjector abstract fun contributesNetworkChangeReceiver(): NetworkChangeReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBluetoothStateReceiver(): RileyLinkBluetoothStateReceiver @ContributesAndroidInjector abstract fun contributesSmsReceiver(): SmsReceiver @ContributesAndroidInjector abstract fun contributesTimeDateOrTZChangeReceiver(): TimeDateOrTZChangeReceiver - + @ContributesAndroidInjector abstract fun contributesCarbSuggestionReceiver(): CarbSuggestionReceiver @ContributesAndroidInjector abstract fun contributesRileyLinkBroadcastReceiver(): RileyLinkBroadcastReceiver -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt index 25d102e3ef..f961c3a863 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt @@ -7,11 +7,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Dismiss import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService -import info.nightscout.androidaps.plugins.pump.danaR.services.AbstractDanaRExecutionService -import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService -import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService -import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService -import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2ExecutionService import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService import info.nightscout.androidaps.plugins.pump.insight.connection_service.InsightConnectionService import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService @@ -24,17 +19,12 @@ import info.nightscout.androidaps.services.LocationService @Suppress("unused") abstract class ServicesModule { - @ContributesAndroidInjector abstract fun contributesAbstractDanaRExecutionService(): AbstractDanaRExecutionService @ContributesAndroidInjector abstract fun contributesAlarmSoundService(): AlarmSoundService @ContributesAndroidInjector abstract fun contributesDataService(): DataService @ContributesAndroidInjector abstract fun contributesDismissNotificationService(): DismissNotificationService @ContributesAndroidInjector abstract fun contributesDummyService(): DummyService @ContributesAndroidInjector abstract fun contributesLocationService(): LocationService @ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService - @ContributesAndroidInjector abstract fun contributesDanaRSService(): DanaRSService - @ContributesAndroidInjector abstract fun contributesDanaRv2ExecutionService(): DanaRv2ExecutionService - @ContributesAndroidInjector abstract fun contributesDanaRExecutionService(): DanaRExecutionService - @ContributesAndroidInjector abstract fun contributesDanaRKoreanExecutionService(): DanaRKoreanExecutionService @ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService @ContributesAndroidInjector abstract fun contributesInsightAlertService(): InsightAlertService @ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt index ebd4691f38..cd71cc8fd2 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt @@ -8,6 +8,7 @@ import dagger.multibindings.IntoMap import info.nightscout.androidaps.skins.SkinButtonsOn import info.nightscout.androidaps.skins.SkinClassic import info.nightscout.androidaps.skins.SkinInterface +import info.nightscout.androidaps.skins.SkinLargeDisplay import javax.inject.Qualifier @Module @@ -25,6 +26,12 @@ open class SkinsModule { @IntKey(10) fun bindsSkinButtonsOn(skinButtonsOn: SkinButtonsOn): SkinInterface = skinButtonsOn + @Provides + @Skin + @IntoMap + @IntKey(20) + fun bindsSkinLargeDisplay(skinLargeDisplay: SkinLargeDisplay): SkinInterface = skinLargeDisplay + @Qualifier annotation class Skin } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/UIModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/UIModule.kt index 50abc0b69a..193b46957a 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/UIModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/UIModule.kt @@ -2,16 +2,6 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector -import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB -import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* -import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData -import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobOref1Thread -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobThread import info.nightscout.androidaps.skins.SkinListPreference @Module diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt deleted file mode 100644 index 6ee0c902dc..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/dependency-injection-todo.txt +++ /dev/null @@ -1,16 +0,0 @@ -PreferenceActivity is an Example how to make an Activity injectable. -We might undo that as we don't actually have us inject things. - -MyPreferencesFragment is an injectable Fragment. Here we actually have Dagger2 provide us an InsulinOrefFreePeakPlugin instance. - -If we use multiple Fragments, we should generate a base-class. Then we only have to add a "provides***Fragment" to the FragmentsModule and derive from that class. - -InsulinOrefFreePeakPlugin is an example how to get things injected via the constructor. -You could call "new InsulinOrefFreePeakPlugin(new SPImpl(SPImpl(PreferenceManager.getDefaultSharedPreferences(context))), new ResourceHelper())"... but Dagger will resolve that for you in MainApp. :) - -SPImpl is an example how to bind an implementation to an Interface via Dagger. - -ResourceHelper is an example how to generate simple classes that Dagger can auto-resolve how to inject them. No need for a provider here. -ResourceHelper might have a weak reference at some point and not a static dependency on MainApp... but at least we reduced the static dependencies within a plugin. - -In order to Test: Any dependency of InsulinOrefFreePeakPlugin is passed via the constructor. Instead of static mocking MainApp you now can Mock ResourceHelper with a very small interface. \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt index ff1b401b0d..10c10b27f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -9,7 +9,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt index caba26346f..31ced947d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator @@ -40,6 +40,7 @@ class CarbsDialog : DialogFragmentWithDate() { @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var carbsGenerator: CarbsGenerator companion object { @@ -170,7 +171,7 @@ class CarbsDialog : DialogFragmentWithDate() { eventTime -= eventTime % 1000 val time = eventTime + timeOffset * 1000 * 60 if (timeOffset != 0) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) val duration = overview_carbs_duration.value.toInt() if (duration > 0) actions.add(resourceHelper.gs(R.string.duration) + ": " + duration + resourceHelper.gs(R.string.shorthour)) @@ -184,7 +185,7 @@ class CarbsDialog : DialogFragmentWithDate() { actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) if (carbsAfterConstraints > 0 || activitySelected || eatingSoonSelected || hypoSelected) { activity?.let { activity -> @@ -233,7 +234,7 @@ class CarbsDialog : DialogFragmentWithDate() { } else { aapsLogger.debug("USER ENTRY: CARBS $carbsAfterConstraints time: $time duration: $duration") carbsGenerator.generateCarbs(carbsAfterConstraints, time, duration, notes) - NSUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) + nsUpload.uploadEvent(CareportalEvent.NOTE, DateUtil.now() - 2000, resourceHelper.gs(R.string.generated_ecarbs_note, carbsAfterConstraints, duration, timeOffset)) } } }, null) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt index e561cb0890..d52e3d26e6 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -15,13 +15,13 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent import info.nightscout.androidaps.db.Source -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.Translator +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.dialog_care.* import kotlinx.android.synthetic.main.notes.* @@ -36,6 +36,7 @@ class CareDialog : DialogFragmentWithDate() { @Inject lateinit var mainApp: MainApp @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var translator: Translator enum class EventType { @@ -43,10 +44,13 @@ class CareDialog : DialogFragmentWithDate() { SENSOR_INSERT, BATTERY_CHANGE, NOTE, - EXERCISE + EXERCISE, + QUESTION, + ANNOUNCEMENT } private var options: EventType = EventType.BGCHECK + @StringRes private var event: Int = R.string.none @@ -79,11 +83,13 @@ class CareDialog : DialogFragmentWithDate() { } actions_care_icon.setImageResource(when (options) { - EventType.BGCHECK -> R.drawable.icon_cp_bgcheck - EventType.SENSOR_INSERT -> R.drawable.icon_cp_cgm_insert - EventType.BATTERY_CHANGE -> R.drawable.icon_cp_pump_battery - EventType.NOTE -> R.drawable.icon_cp_note - EventType.EXERCISE -> R.drawable.icon_cp_exercise + EventType.BGCHECK -> R.drawable.ic_cp_bgcheck + EventType.SENSOR_INSERT -> R.drawable.ic_cp_cgm_insert + EventType.BATTERY_CHANGE -> R.drawable.ic_cp_pump_battery + EventType.NOTE -> R.drawable.ic_cp_note + EventType.EXERCISE -> R.drawable.ic_cp_exercise + EventType.QUESTION -> R.drawable.ic_cp_question + EventType.ANNOUNCEMENT -> R.drawable.ic_cp_announcement }) actions_care_title.text = resourceHelper.gs(when (options) { EventType.BGCHECK -> R.string.careportal_bgcheck @@ -91,9 +97,13 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> R.string.careportal_pumpbatterychange EventType.NOTE -> R.string.careportal_note EventType.EXERCISE -> R.string.careportal_exercise + EventType.QUESTION -> R.string.careportal_question + EventType.ANNOUNCEMENT -> R.string.careportal_announcement }) when (options) { + EventType.QUESTION, + EventType.ANNOUNCEMENT, EventType.BGCHECK -> { action_care_duration_layout.visibility = View.GONE } @@ -133,7 +143,7 @@ class CareDialog : DialogFragmentWithDate() { } actions_care_duration.setParams(savedInstanceState?.getDouble("actions_care_duration") ?: 0.0, 0.0, Constants.MAX_PROFILE_SWITCH_DURATION, 10.0, DecimalFormat("0"), false, ok) - if (options == EventType.NOTE) + if (options == EventType.NOTE || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT) notes_layout?.visibility = View.VISIBLE // independent to preferences } @@ -143,7 +153,7 @@ class CareDialog : DialogFragmentWithDate() { val json = JSONObject() val actions: LinkedList = LinkedList() - if (options == EventType.BGCHECK) { + if (options == EventType.BGCHECK || options == EventType.QUESTION || options == EventType.ANNOUNCEMENT) { val type = when { actions_care_meter.isChecked -> "Finger" @@ -167,7 +177,7 @@ class CareDialog : DialogFragmentWithDate() { eventTime -= eventTime % 1000 if (eventTimeChanged) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) json.put("created_at", DateUtil.toISOString(eventTime)) json.put("mills", eventTime) @@ -177,6 +187,8 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.NOTE -> CareportalEvent.NOTE EventType.EXERCISE -> CareportalEvent.EXERCISE + EventType.QUESTION -> CareportalEvent.QUESTION + EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT }) json.put("units", profileFunction.getUnits()) if (enteredBy.isNotEmpty()) @@ -193,11 +205,13 @@ class CareDialog : DialogFragmentWithDate() { EventType.BATTERY_CHANGE -> CareportalEvent.PUMPBATTERYCHANGE EventType.NOTE -> CareportalEvent.NOTE EventType.EXERCISE -> CareportalEvent.EXERCISE + EventType.QUESTION -> CareportalEvent.QUESTION + EventType.ANNOUNCEMENT -> CareportalEvent.ANNOUNCEMENT } careportalEvent.json = json.toString() aapsLogger.debug("USER ENTRY: CAREPORTAL ${careportalEvent.eventType} json: ${careportalEvent.json}") MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(json) + nsUpload.uploadCareportalEntryToNS(json) }, null) } return true diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index 081589f526..73921c0067 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -24,6 +24,7 @@ import javax.inject.Inject abstract class DialogFragmentWithDate : DaggerDialogFragment() { @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil var eventTime = DateUtil.now() var eventTimeChanged = false @@ -57,7 +58,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { eventTime = savedInstanceState?.getLong("eventTime") ?: DateUtil.now() eventTimeChanged = savedInstanceState?.getBoolean("eventTimeChanged") ?: false overview_eventdate?.text = DateUtil.dateString(eventTime) - overview_eventtime?.text = DateUtil.timeString(eventTime) + overview_eventtime?.text = dateUtil.timeString(eventTime) // create an OnDateSetListener val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> @@ -92,7 +93,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { cal.set(Calendar.SECOND, seconds++) // randomize seconds to prevent creating record of the same time, if user choose time manually eventTime = cal.timeInMillis eventTimeChanged = true - overview_eventtime?.text = DateUtil.timeString(eventTime) + overview_eventtime?.text = dateUtil.timeString(eventTime) } overview_eventtime?.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index 62da94d3ff..02e46e5c17 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -62,7 +62,7 @@ class ExtendedBolusDialog : DialogFragmentWithDate() { override fun submit(): Boolean { val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text) - val durationInMinutes = SafeParse.stringToInt(actions_extendedbolus_duration.text) + val durationInMinutes = actions_extendedbolus_duration.value.toInt() val actions: LinkedList = LinkedList() val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() actions.add(resourceHelper.gs(R.string.formatinsulinunits, insulinAfterConstraint)) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 135eeb0e09..580b27228c 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -23,9 +23,10 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.SafeParse +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import kotlinx.android.synthetic.main.dialog_fill.* import kotlinx.android.synthetic.main.notes.* import kotlinx.android.synthetic.main.okcancel.* @@ -39,9 +40,9 @@ class FillDialog : DialogFragmentWithDate() { @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var ctx: Context + @Inject lateinit var nsUpload: NSUpload @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var activePlugin: ActivePluginProvider - @Inject lateinit var injector: HasAndroidInjector override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) @@ -112,7 +113,7 @@ class FillDialog : DialogFragmentWithDate() { eventTime -= eventTime % 1000 if (eventTimeChanged) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) if (insulinAfterConstraints > 0 || fill_catheter_change.isChecked || fill_cartridge_change.isChecked) { activity?.let { activity -> @@ -123,12 +124,12 @@ class FillDialog : DialogFragmentWithDate() { } if (siteChange) { aapsLogger.debug("USER ENTRY: SITE CHANGE") - generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes) + nsUpload.generateCareportalEvent(CareportalEvent.SITECHANGE, eventTime, notes) } if (insulinChange) { // add a second for case of both checked aapsLogger.debug("USER ENTRY: INSULIN CHANGE") - generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes) + nsUpload.generateCareportalEvent(CareportalEvent.INSULINCHANGE, eventTime + 1000, notes) } }, null) } @@ -161,28 +162,4 @@ class FillDialog : DialogFragmentWithDate() { } }) } - - private fun generateCareportalEvent(eventType: String, time: Long, notes: String) { - val careportalEvent = CareportalEvent(injector) - careportalEvent.source = Source.USER - careportalEvent.date = time - careportalEvent.json = generateJson(eventType, time, notes).toString() - careportalEvent.eventType = eventType - MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadEvent(eventType, time, notes) - } - - private fun generateJson(careportalEvent: String, time: Long, notes: String): JSONObject { - val data = JSONObject() - try { - data.put("eventType", careportalEvent) - data.put("created_at", DateUtil.toISOString(time)) - data.put("mills", time) - data.put("enteredBy", sp.getString("careportal_enteredby", resourceHelper.gs(R.string.app_name))) - if (notes.isNotEmpty()) data.put("notes", notes) - } catch (ignored: JSONException) { - } - return data - } - } diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt index 333de055ca..b5b3a8f252 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -9,6 +9,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity @@ -21,7 +22,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog @@ -45,6 +46,7 @@ class InsulinDialog : DialogFragmentWithDate() { @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var ctx: Context + @Inject lateinit var config: Config companion object { private const val PLUS1_DEFAULT = 0.5 @@ -88,6 +90,10 @@ class InsulinDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + if (config.NSCLIENT) { + overview_insulin_record_only.isChecked = true + overview_insulin_record_only.isEnabled = false + } val maxInsulin = constraintChecker.getMaxBolusAllowed().value() overview_insulin_time.setParams(savedInstanceState?.getDouble("overview_insulin_time") @@ -145,7 +151,7 @@ class InsulinDialog : DialogFragmentWithDate() { val timeOffset = overview_insulin_time.value.toInt() val time = DateUtil.now() + T.mins(timeOffset.toLong()).msecs() if (timeOffset != 0) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(time)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(time)) val notes = notes.text.toString() if (notes.isNotEmpty()) diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt index 45491761d7..5ea091fa28 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -9,7 +9,7 @@ import com.google.common.base.Joiner import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper @@ -28,6 +28,8 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var activePlugin: ActivePluginProvider + var profileIndex: Int? = null + override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("overview_profileswitch_duration", overview_profileswitch_duration.value) @@ -38,6 +40,9 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { onCreateViewGeneral() + arguments?.let { bundle -> + profileIndex = bundle.getInt("profileIndex", 0) + } return inflater.inflate(R.layout.dialog_profileswitch, container, false) } @@ -59,9 +64,12 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { val adapter = ArrayAdapter(context, R.layout.spinner_centered, profileList) overview_profileswitch_profile.adapter = adapter // set selected to actual profile - for (p in profileList.indices) - if (profileList[p] == profileFunction.getProfileName(false)) - overview_profileswitch_profile.setSelection(p) + if (profileIndex != null) + overview_profileswitch_profile.setSelection(profileIndex as Int) + else + for (p in profileList.indices) + if (profileList[p] == profileFunction.getProfileName(false)) + overview_profileswitch_profile.setSelection(p) } ?: return treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now())?.let { ps -> @@ -98,7 +106,7 @@ class ProfileSwitchDialog : DialogFragmentWithDate() { if (notes.isNotEmpty()) actions.add(resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + notes) if (eventTimeChanged) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt deleted file mode 100644 index 382e6359a5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ /dev/null @@ -1,114 +0,0 @@ -package info.nightscout.androidaps.dialogs - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.view.Window -import android.view.WindowManager -import dagger.android.HasAndroidInjector -import dagger.android.support.DaggerDialogFragment -import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.R -import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import kotlinx.android.synthetic.main.close.* -import kotlinx.android.synthetic.main.dialog_profileviewer.* -import org.json.JSONObject -import javax.inject.Inject - -class ProfileViewerDialog : DaggerDialogFragment() { - @Inject lateinit var injector: HasAndroidInjector - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var treatmentsPlugin: TreatmentsPlugin - - private var time: Long = 0 - - enum class Mode(val i: Int) { - RUNNING_PROFILE(1), - CUSTOM_PROFILE(2) - } - - private var mode: Mode = Mode.RUNNING_PROFILE - private var customProfileJson: String = "" - private var customProfileName: String = "" - private var customProfileUnits: String = Constants.MGDL - - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, - savedInstanceState: Bundle?): View? { - // load data from bundle - (savedInstanceState ?: arguments)?.let { bundle -> - time = bundle.getLong("time", 0) - mode = Mode.values()[bundle.getInt("mode", Mode.RUNNING_PROFILE.ordinal)] - customProfileJson = bundle.getString("customProfile", "") - customProfileUnits = bundle.getString("customProfileUnits", Constants.MGDL) - customProfileName = bundle.getString("customProfileName", "") - } - - dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) - dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) - isCancelable = true - dialog?.setCanceledOnTouchOutside(false) - - return inflater.inflate(R.layout.dialog_profileviewer, container, false) - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - - close.setOnClickListener { dismiss() } - - val profile: Profile? - val profileName: String? - val date: String? - when (mode) { - Mode.RUNNING_PROFILE -> { - profile = treatmentsPlugin.getProfileSwitchFromHistory(time)?.profileObject - profileName = treatmentsPlugin.getProfileSwitchFromHistory(time)?.customizedName - date = DateUtil.dateAndTimeString(treatmentsPlugin.getProfileSwitchFromHistory(time)?.date - ?: 0) - profileview_datelayout.visibility = View.VISIBLE - } - - Mode.CUSTOM_PROFILE -> { - profile = Profile(injector, JSONObject(customProfileJson), customProfileUnits) - profileName = customProfileName - date = "" - profileview_datelayout.visibility = View.GONE - } - } - profileview_noprofile.visibility = View.VISIBLE - - profile?.let { - profileview_units.text = it.units - profileview_dia.text = resourceHelper.gs(R.string.format_hours, it.dia) - profileview_activeprofile.text = profileName - profileview_date.text = date - profileview_ic.text = it.icList - profileview_isf.text = it.isfList - profileview_basal.text = it.basalList - profileview_target.text = it.targetList - basal_graph.show(it) - - profileview_noprofile.visibility = View.GONE - profileview_invalidprofile.visibility = if (it.isValid("ProfileViewDialog")) View.GONE else View.VISIBLE - } - } - - override fun onStart() { - super.onStart() - dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) - } - - override fun onSaveInstanceState(bundle: Bundle) { - super.onSaveInstanceState(bundle) - bundle.putLong("time", time) - bundle.putInt("mode", mode.ordinal) - bundle.putString("customProfile", customProfileJson) - bundle.putString("customProfileName", customProfileName) - bundle.putString("customProfileUnits", customProfileUnits) - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt index bcba2ae87b..7ab5850f87 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog @@ -83,25 +83,25 @@ class TempBasalDialog : DialogFragmentWithDate() { override fun submit(): Boolean { var percent = 0 var absolute = 0.0 - val durationInMinutes = SafeParse.stringToInt(actions_tempbasal_duration.text) + val durationInMinutes = actions_tempbasal_duration.value.toInt() val profile = profileFunction.getProfile() ?: return false val actions: LinkedList = LinkedList() if (isPercentPump) { val basalPercentInput = SafeParse.stringToInt(actions_tempbasal_basalpercentinput.text) percent = constraintChecker.applyBasalPercentConstraints(Constraint(basalPercentInput), profile).value() - actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": $percent%") + actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": $percent%") actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (percent != basalPercentInput) actions.add(resourceHelper.gs(R.string.constraintapllied)) } else { val basalAbsoluteInput = SafeParse.stringToDouble(actions_tempbasal_basalabsoluteinput.text) absolute = constraintChecker.applyBasalConstraints(Constraint(basalAbsoluteInput), profile).value() - actions.add(resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) + actions.add(resourceHelper.gs(R.string.tempbasal_label) + ": " + resourceHelper.gs(R.string.pump_basebasalrate, absolute)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, durationInMinutes)) if (abs(absolute - basalAbsoluteInput) > 0.01) actions.add("" + resourceHelper.gs(R.string.constraintapllied) + "") } activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { val callback: Callback = object : Callback() { override fun run() { if (!result.success) { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt index ba114c9b21..e4f5208471 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -14,9 +14,8 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.db.TempTarget import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog @@ -77,7 +76,7 @@ class TempTargetDialog : DialogFragmentWithDate() { val adapterReason = ArrayAdapter(context, R.layout.spinner_centered, reasonList) overview_temptarget_reason.adapter = adapterReason overview_temptarget_reason.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { val defaultDuration: Double val defaultTarget: Double when (reasonList[position]) { @@ -123,13 +122,13 @@ class TempTargetDialog : DialogFragmentWithDate() { val duration = overview_temptarget_duration.value.toInt() if (target != 0.0 && duration != 0) { actions.add(resourceHelper.gs(R.string.reason) + ": " + reason) - actions.add(resourceHelper.gs(R.string.nsprofileview_target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) + actions.add(resourceHelper.gs(R.string.target_label) + ": " + Profile.toCurrentUnitsString(profileFunction, target) + " " + resourceHelper.gs(unitResId)) actions.add(resourceHelper.gs(R.string.duration) + ": " + resourceHelper.gs(R.string.format_mins, duration)) } else { actions.add(resourceHelper.gs(R.string.stoptemptarget)) } if (eventTimeChanged) - actions.add(resourceHelper.gs(R.string.time) + ": " + DateUtil.dateAndTimeString(eventTime)) + actions.add(resourceHelper.gs(R.string.time) + ": " + dateUtil.dateAndTimeString(eventTime)) activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_temporarytarget), HtmlHelper.fromHtml(Joiner.on("
").join(actions)), Runnable { diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index c5f4d1ec53..84663a1cfe 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -9,6 +9,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner +import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo @@ -25,6 +26,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.resources.ResourceHelper +import kotlinx.android.synthetic.main.dialog_insulin.* import kotlinx.android.synthetic.main.dialog_treatment.* import kotlinx.android.synthetic.main.okcancel.* import java.text.DecimalFormat @@ -38,6 +40,7 @@ class TreatmentDialog : DialogFragmentWithDate() { @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var ctx: Context + @Inject lateinit var config: Config private val textWatcher: TextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable) {} @@ -75,6 +78,10 @@ class TreatmentDialog : DialogFragmentWithDate() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) + if (config.NSCLIENT) { + overview_treatment_record_only.isChecked = true + overview_treatment_record_only.isEnabled = false + } val maxCarbs = constraintChecker.getMaxCarbsAllowed().value().toDouble() val maxInsulin = constraintChecker.getMaxBolusAllowed().value() val pumpDescription = activePlugin.activePump.pumpDescription diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index cc3c6c7a98..faf27af7b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -24,7 +24,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.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin @@ -261,7 +261,7 @@ class WizardDialog : DaggerDialogFragment() { private fun calculateInsulin() { val profileStore = activePlugin.activeProfileInterface.profile - if (treatments_wizard_profile.selectedItem == null || profileStore == null) + if (treatments_wizard_profile?.selectedItem == null || profileStore == null) return // not initialized yet var profileName = treatments_wizard_profile.selectedItem.toString() val specificProfile: Profile? diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt index 2c25836f8d..2bac82dbc6 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt @@ -9,7 +9,7 @@ import android.view.WindowManager import dagger.android.support.DaggerDialogFragment import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.resources.ResourceHelper diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt b/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt deleted file mode 100644 index aa0db3467a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventRebuildTabs.kt +++ /dev/null @@ -1,3 +0,0 @@ -package info.nightscout.androidaps.events - -class EventRebuildTabs @JvmOverloads constructor(var recreate: Boolean = false) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt index 9cbc9d1563..679b62ee30 100644 --- a/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt +++ b/app/src/main/java/info/nightscout/androidaps/events/EventTreatmentChange.kt @@ -1,5 +1,5 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment class EventTreatmentChange(val treatment: Treatment?) : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt index 0b260e9470..df22cabde6 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt @@ -3,10 +3,10 @@ package info.nightscout.androidaps.historyBrowser import android.app.DatePickerDialog import android.graphics.Color import android.os.Bundle -import android.os.SystemClock import android.util.DisplayMetrics import android.view.ViewGroup import android.widget.LinearLayout +import android.widget.RelativeLayout import android.widget.TextView import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector @@ -15,12 +15,13 @@ import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.events.EventCustomCalculationFinished import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.OverviewMenus import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.utils.DateUtil @@ -33,6 +34,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.android.schedulers.AndroidSchedulers 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 @@ -49,11 +51,13 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var defaultValueHelper: DefaultValueHelper - @Inject lateinit var iobCobStaticCalculatorPlugin: IobCobStaticCalculatorPlugin + @Inject lateinit var iobCobCalculatorPluginHistory: IobCobCalculatorPluginHistory + @Inject lateinit var treatmentsPluginHistory: TreatmentsPluginHistory @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var overviewMenus: OverviewMenus + @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() @@ -72,12 +76,10 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { historybrowse_left.setOnClickListener { start -= T.hours(rangeToDisplay.toLong()).msecs() - updateGUI("onClickLeft") runCalculation("onClickLeft") } historybrowse_right.setOnClickListener { start += T.hours(rangeToDisplay.toLong()).msecs() - updateGUI("onClickRight") runCalculation("onClickRight") } historybrowse_end.setOnClickListener { @@ -88,13 +90,12 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { calendar[Calendar.MINUTE] = 0 calendar[Calendar.HOUR_OF_DAY] = 0 start = calendar.timeInMillis - updateGUI("onClickEnd") runCalculation("onClickEnd") } historybrowse_zoom.setOnClickListener { rangeToDisplay += 6 rangeToDisplay = if (rangeToDisplay > 24) 6 else rangeToDisplay - updateGUI("rangeChange") + updateGUI("rangeChange", false) } historybrowse_zoom.setOnLongClickListener { val calendar = Calendar.getInstance() @@ -104,7 +105,6 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { calendar[Calendar.MINUTE] = 0 calendar[Calendar.HOUR_OF_DAY] = 0 start = calendar.timeInMillis - updateGUI("resetToMidnight") runCalculation("onLongClickZoom") true } @@ -113,12 +113,15 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> val cal = Calendar.getInstance() cal.timeInMillis = start - cal.set(Calendar.YEAR, year) - cal.set(Calendar.MONTH, monthOfYear) - cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) + cal[Calendar.YEAR] = year + cal[Calendar.MONTH] = monthOfYear + cal[Calendar.DAY_OF_MONTH] = dayOfMonth + cal[Calendar.MILLISECOND] = 0 + cal[Calendar.SECOND] = 0 + cal[Calendar.MINUTE] = 0 + cal[Calendar.HOUR_OF_DAY] = 0 start = cal.timeInMillis - historybrowse_date?.text = DateUtil.dateAndTimeString(start) - updateGUI("onClickDate") + historybrowse_date?.text = dateUtil.dateAndTimeString(start) runCalculation("onClickDate") } @@ -142,24 +145,38 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { overviewMenus.setupChartMenu(overview_chartMenuButton) prepareGraphs() + savedInstanceState?.let { bundle -> + rangeToDisplay = bundle.getInt("rangeToDisplay", 0) + start = bundle.getLong("start", 0) + } + } public override fun onPause() { super.onPause() disposable.clear() - iobCobStaticCalculatorPlugin.stopCalculation("onPause") + iobCobCalculatorPluginHistory.stopCalculation("onPause") } public override fun onResume() { super.onResume() disposable.add(rxBus .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ event: EventAutosensCalculationFinished -> - // catch only events from iobCobStaticCalculatorPlugin - if (event.cause === eventCustomCalculationFinished) { - aapsLogger.debug(LTag.AUTOSENS, "EventAutosensCalculationFinished") - updateGUI("EventAutosensCalculationFinished") + .observeOn(Schedulers.io()) + .subscribe({ + // catch only events from iobCobCalculatorPluginHistory + if (it.cause is EventCustomCalculationFinished) { + updateGUI("EventAutosensCalculationFinished", bgOnly = false) + } + }) { fabricPrivacy::logException } + ) + disposable.add(rxBus + .toObservable(EventAutosensBgLoaded::class.java) + .observeOn(Schedulers.io()) + .subscribe({ + // catch only events from iobCobCalculatorPluginHistory + if (it.cause is EventCustomCalculationFinished) { + updateGUI("EventAutosensCalculationFinished", bgOnly = true) } }) { fabricPrivacy::logException } ) @@ -172,21 +189,32 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { .toObservable(EventRefreshOverview::class.java) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ - prepareGraphs() - updateGUI("EventRefreshOverview") + if (it.now) { + prepareGraphs() + updateGUI("EventRefreshOverview", bgOnly = false) + } }) { fabricPrivacy::logException } ) - // set start of current day - val calendar = Calendar.getInstance() - calendar.timeInMillis = System.currentTimeMillis() - calendar[Calendar.MILLISECOND] = 0 - calendar[Calendar.SECOND] = 0 - calendar[Calendar.MINUTE] = 0 - calendar[Calendar.HOUR_OF_DAY] = 0 - start = calendar.timeInMillis - runCalculation("onResume") - SystemClock.sleep(1000) - updateGUI("onResume") + if (start == 0L) { + // set start of current day + val calendar = Calendar.getInstance() + calendar.timeInMillis = System.currentTimeMillis() + calendar[Calendar.MILLISECOND] = 0 + calendar[Calendar.SECOND] = 0 + calendar[Calendar.MINUTE] = 0 + calendar[Calendar.HOUR_OF_DAY] = 0 + start = calendar.timeInMillis + runCalculation("onResume") + } else { + updateGUI("onResume", bgOnly = false) + } + } + + override fun onSaveInstanceState(outState: Bundle) { + super.onSaveInstanceState(outState) + outState.putInt("rangeToDisplay", rangeToDisplay) + outState.putLong("start", start) + } private fun prepareGraphs() { @@ -199,19 +227,28 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { secondaryGraphsLabel.clear() history_iobgraph.removeAllViews() for (i in 1 until numOfGraphs) { - val label = TextView(this) - label.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(100, 0, 0, -50) } - history_iobgraph.addView(label) - secondaryGraphsLabel.add(label) + val relativeLayout = RelativeLayout(this) + relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) + val graph = GraphView(this) - graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, 0, 0, resourceHelper.dpToPx(10)) } + graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) } graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.numVerticalLabels = 3 graph.viewport.backgroundColor = Color.argb(20, 255, 255, 255) // 8% of gray - history_iobgraph.addView(graph) + relativeLayout.addView(graph) + + val label = TextView(this) + val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) } + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) + label.layoutParams = layoutParams + relativeLayout.addView(label) + secondaryGraphsLabel.add(label) + + history_iobgraph.addView(relativeLayout) secondaryGraphs.add(graph) } } @@ -219,36 +256,38 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { } private fun runCalculation(from: String) { - val end = start + T.hours(rangeToDisplay.toLong()).msecs() - iobCobStaticCalculatorPlugin.stopCalculation(from) - iobCobStaticCalculatorPlugin.clearCache() - iobCobStaticCalculatorPlugin.runCalculation(from, end, true, false, eventCustomCalculationFinished) + GlobalScope.launch(Dispatchers.Default) { + treatmentsPluginHistory.initializeData(start - T.hours(8).msecs()) + val end = start + T.hours(rangeToDisplay.toLong()).msecs() + iobCobCalculatorPluginHistory.stopCalculation(from) + iobCobCalculatorPluginHistory.clearCache() + iobCobCalculatorPluginHistory.runCalculation(from, end, true, false, eventCustomCalculationFinished) + } } - @Synchronized - fun updateGUI(from: String) { + fun updateGUI(from: String, bgOnly: Boolean) { aapsLogger.debug(LTag.UI, "updateGUI from: $from") val pump = activePlugin.activePump val profile = profileFunction.getProfile() - historybrowse_noprofile?.visibility = (profile == null).toVisibility() - profile ?: return - val lowLine = defaultValueHelper.determineLowLine() val highLine = defaultValueHelper.determineHighLine() - historybrowse_date?.text = DateUtil.dateAndTimeString(start) - historybrowse_zoom?.text = rangeToDisplay.toString() GlobalScope.launch(Dispatchers.Main) { + historybrowse_noprofile?.visibility = (profile == null).toVisibility() + profile ?: return@launch + historybrowse_bggraph ?: return@launch - val graphData = GraphData(injector, historybrowse_bggraph, iobCobStaticCalculatorPlugin) + historybrowse_date?.text = dateUtil.dateAndTimeString(start) + historybrowse_zoom?.text = rangeToDisplay.toString() + val graphData = GraphData(injector, historybrowse_bggraph, iobCobCalculatorPluginHistory, treatmentsPluginHistory) val secondaryGraphsData: ArrayList = ArrayList() // do preparation in different thread withContext(Dispatchers.Default) { val fromTime: Long = start + T.secs(100).msecs() - val toTime: Long = start + T.hours(rangeToDisplay.toLong()).msecs() - aapsLogger.debug(LTag.UI, "Period: " + DateUtil.dateAndTimeString(fromTime) + " - " + DateUtil.dateAndTimeString(toTime)) + val toTime: Long = start + T.hours(rangeToDisplay.toLong()).msecs() + T.secs(100).msecs() + aapsLogger.debug(LTag.UI, "Period: " + dateUtil.dateAndTimeString(fromTime) + " - " + dateUtil.dateAndTimeString(toTime)) val pointer = System.currentTimeMillis() // **** In range Area **** @@ -260,71 +299,73 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { // set manual x bounds to have nice steps graphData.formatAxis(fromTime, toTime) - // Treatments - graphData.addTreatments(fromTime, toTime) - if (overviewMenus.setting[0][OverviewMenus.CharType.ACT.ordinal]) - graphData.addActivity(fromTime, toTime, false, 0.8) - - // add basal data - if (pump.pumpDescription.isTempBasalCapable && overviewMenus.setting[0][OverviewMenus.CharType.BAS.ordinal]) { - graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2) - } - // add target line graphData.addTargetLine(fromTime, toTime, profile, null) // **** NOW line **** graphData.addNowLine(pointer) - // ------------------ 2nd graph - for (g in 0 until secondaryGraphs.size) { - val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobStaticCalculatorPlugin) - var useIobForScale = false - var useCobForScale = false - var useDevForScale = false - var useRatioForScale = false - var useDSForScale = false - var useIAForScale = false - var useABSForScale = false - when { - overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true + if (!bgOnly) { + // Treatments + graphData.addTreatments(fromTime, toTime) + if (overviewMenus.setting[0][OverviewMenus.CharType.ACT.ordinal]) + graphData.addActivity(fromTime, toTime, false, 0.8) + + // add basal data + if (pump.pumpDescription.isTempBasalCapable && overviewMenus.setting[0][OverviewMenus.CharType.BAS.ordinal]) { + graphData.addBasals(fromTime, toTime, lowLine / graphData.maxY / 1.2) } + // ------------------ 2nd graph + for (g in 0 until secondaryGraphs.size) { + val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculatorPluginHistory, treatmentsPluginHistory) + var useIobForScale = false + var useCobForScale = false + var useDevForScale = false + var useRatioForScale = false + var useDSForScale = false + var useIAForScale = false + var useABSForScale = false + when { + overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true + overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true + } - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, toTime, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal]) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, toTime, useCobForScale, if (useCobForScale) 1.0 else 0.5) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1.0) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1.0) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, toTime, useIAForScale, 0.8) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, toTime, useABSForScale, 1.0) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1.0) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, toTime, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal]) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, toTime, useCobForScale, if (useCobForScale) 1.0 else 0.5) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, toTime, useDevForScale, 1.0) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, toTime, useRatioForScale, 1.0) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, toTime, useIAForScale, 0.8) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, toTime, useABSForScale, 1.0) + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, toTime, useDSForScale, 1.0) - // set manual x bounds to have nice steps - secondGraphData.formatAxis(fromTime, toTime) - secondGraphData.addNowLine(pointer) - secondaryGraphsData.add(secondGraphData) + // set manual x bounds to have nice steps + secondGraphData.formatAxis(fromTime, toTime) + secondGraphData.addNowLine(pointer) + secondaryGraphsData.add(secondGraphData) + } } } // finally enforce drawing of graphs in UI thread graphData.performUpdate() - for (g in 0 until secondaryGraphs.size) { - secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) - secondaryGraphs[g].visibility = ( - overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] - ).toVisibility() - secondaryGraphsData[g].performUpdate() - } + if (!bgOnly) + for (g in 0 until secondaryGraphs.size) { + secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) + secondaryGraphs[g].visibility = (!bgOnly && ( + overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] + )).toVisibility() + secondaryGraphsData[g].performUpdate() + } } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt similarity index 74% rename from app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt rename to app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt index 87276a50a9..bf7401036a 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobCalculatorPluginHistory.kt @@ -2,20 +2,22 @@ package info.nightscout.androidaps.historyBrowser import dagger.android.HasAndroidInjector import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject +import javax.inject.Singleton -class IobCobStaticCalculatorPlugin @Inject constructor( +@Singleton +class IobCobCalculatorPluginHistory @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, rxBus: RxBusWrapper, @@ -23,13 +25,14 @@ class IobCobStaticCalculatorPlugin @Inject constructor( resourceHelper: ResourceHelper, profileFunction: ProfileFunction, activePlugin: ActivePluginProvider, - treatmentsPlugin: TreatmentsPlugin, + treatmentsPluginHistory: TreatmentsPluginHistory, sensitivityOref1Plugin: SensitivityOref1Plugin, sensitivityAAPSPlugin: SensitivityAAPSPlugin, sensitivityWeightedAveragePlugin: SensitivityWeightedAveragePlugin, - fabricPrivacy: FabricPrivacy + fabricPrivacy: FabricPrivacy, + dateUtil: DateUtil ) : IobCobCalculatorPlugin(injector, aapsLogger, rxBus, sp, resourceHelper, profileFunction, - activePlugin, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy) { + activePlugin, treatmentsPluginHistory, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) { override fun onStart() { // do not attach to rxbus } diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt new file mode 100644 index 0000000000..caa0fb1b1a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/TreatmentsPluginHistory.kt @@ -0,0 +1,41 @@ +package info.nightscout.androidaps.historyBrowser + +import android.content.Context +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.bus.RxBusWrapper +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload +import info.nightscout.androidaps.plugins.treatments.TreatmentService +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class TreatmentsPluginHistory @Inject constructor( + injector: HasAndroidInjector, + aapsLogger: AAPSLogger, + rxBus: RxBusWrapper, + resourceHelper: ResourceHelper, + context: Context, + sp: SP, + profileFunction: ProfileFunction, + activePlugin: ActivePluginProvider, + nsUpload: NSUpload, + fabricPrivacy: FabricPrivacy, dateUtil: DateUtil +) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, context, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil) { + + init { + onStart() + } + + override fun onStart() { + service = TreatmentService(injector) + initializeData(range()) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java index 815cf2fa24..2fa1816ad5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/logger/LoggerCallback.java @@ -4,7 +4,7 @@ import org.mozilla.javascript.ScriptableObject; import javax.inject.Inject; -import info.nightscout.androidaps.MainApp; +import info.nightscout.androidaps.db.StaticInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -26,7 +26,7 @@ public class LoggerCallback extends ScriptableObject { //empty constructor needed for Rhino errorBuffer = new StringBuffer(); logBuffer = new StringBuffer(); - MainApp.instance().androidInjector().inject(this); + StaticInjector.Companion.getInstance().androidInjector().inject(this); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/CarbSuggestionReceiver.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/CarbSuggestionReceiver.kt new file mode 100644 index 0000000000..5382184d15 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/CarbSuggestionReceiver.kt @@ -0,0 +1,15 @@ +package info.nightscout.androidaps.plugins.aps.loop + +import android.content.Context +import android.content.Intent +import dagger.android.DaggerBroadcastReceiver +import javax.inject.Inject + +class CarbSuggestionReceiver : DaggerBroadcastReceiver() { + @Inject lateinit var loopPlugin: LoopPlugin + override fun onReceive(context: Context, intent: Intent) { + super.onReceive(context, intent) + val duration = intent.getIntExtra("ignoreDuration", 5) + loopPlugin.disableCarbSuggestions(duration) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index 8463e8f133..4092f1d602 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt @@ -29,6 +29,7 @@ class LoopFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var loopPlugin: LoopPlugin + @Inject lateinit var dateUtil: DateUtil private var disposable: CompositeDisposable = CompositeDisposable() @@ -81,12 +82,12 @@ class LoopFragment : DaggerFragment() { loop_request?.text = it.request?.toSpanned() ?: "" loop_constraintsprocessed?.text = it.constraintsProcessed?.toSpanned() ?: "" loop_source?.text = it.source ?: "" - loop_lastrun?.text = DateUtil.dateAndTimeString(it.lastAPSRun) + loop_lastrun?.text = dateUtil.dateAndTimeString(it.lastAPSRun) ?: "" - loop_smbrequest_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest) - loop_smbexecution_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact) - loop_tbrrequest_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) - loop_tbrexecution_time?.text = DateUtil.dateAndTimeAndSecondsString(it.lastTBREnact) + loop_smbrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBRequest) + loop_smbexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastSMBEnact) + loop_tbrrequest_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBRRequest) + loop_tbrexecution_time?.text = dateUtil.dateAndTimeAndSecondsString(it.lastTBREnact) loop_tbrsetbypump?.text = it.tbrSetByPump?.let { tbrSetByPump -> HtmlHelper.fromHtml(tbrSetByPump.toHtml()) } ?: "" diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java index 93fcef0f0b..dcbb0bb9d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.java @@ -1,7 +1,6 @@ package info.nightscout.androidaps.plugins.aps.loop; import android.annotation.SuppressLint; -import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; @@ -22,6 +21,7 @@ import javax.inject.Singleton; import dagger.Lazy; import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainActivity; import info.nightscout.androidaps.MainApp; @@ -41,9 +41,11 @@ import info.nightscout.androidaps.interfaces.APSInterface; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.interfaces.CommandQueueProvider; import info.nightscout.androidaps.interfaces.Constraint; +import info.nightscout.androidaps.interfaces.LoopInterface; 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.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; @@ -53,7 +55,9 @@ 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.configBuilder.ProfileFunction; +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; @@ -65,15 +69,15 @@ import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import info.nightscout.androidaps.utils.HardLimits; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @Singleton -public class LoopPlugin extends PluginBase { +public class LoopPlugin extends PluginBase implements LoopInterface { private final HasAndroidInjector injector; private final SP sp; private final RxBusWrapper rxBus; @@ -89,7 +93,9 @@ public class LoopPlugin extends PluginBase { private final IobCobCalculatorPlugin iobCobCalculatorPlugin; private final ReceiverStatusStore receiverStatusStore; private final FabricPrivacy fabricPrivacy; + private final NSUpload nsUpload; private final HardLimits hardLimits; + private Notification notification; private CompositeDisposable disposable = new CompositeDisposable(); @@ -101,21 +107,18 @@ public class LoopPlugin extends PluginBase { private boolean isSuperBolus; private boolean isDisconnected; - public class LastRun { - public APSResult request = null; - public APSResult constraintsProcessed = null; - public PumpEnactResult tbrSetByPump = null; - public PumpEnactResult smbSetByPump = null; - public String source = null; - public long lastAPSRun = DateUtil.now(); - public long lastTBREnact = 0; - public long lastSMBEnact = 0; - public long lastTBRRequest = 0; - public long lastSMBRequest = 0; - public long lastOpenModeAccept; + private long carbsSuggestionsSuspendedUntil = 0; + private int prevCarbsreq = 0; + + @Nullable private LastRun lastRun = null; + + @Nullable @Override public LastRun getLastRun() { + return lastRun; } - @Nullable public LastRun lastRun = null; + @Override public void setLastRun(@Nullable LastRun lastRun) { + this.lastRun = lastRun; + } @Inject public LoopPlugin( @@ -135,6 +138,7 @@ public class LoopPlugin extends PluginBase { IobCobCalculatorPlugin iobCobCalculatorPlugin, ReceiverStatusStore receiverStatusStore, FabricPrivacy fabricPrivacy, + NSUpload nsUpload, HardLimits hardLimits ) { super(new PluginDescription() @@ -161,6 +165,7 @@ public class LoopPlugin extends PluginBase { this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; this.receiverStatusStore = receiverStatusStore; this.fabricPrivacy = fabricPrivacy; + this.nsUpload = nsUpload; this.hardLimits = hardLimits; loopSuspendedTill = sp.getLong("loopSuspendedTill", 0L); @@ -292,7 +297,7 @@ public class LoopPlugin extends PluginBase { return true; } - public boolean isLGS(){ + public boolean isLGS() { Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); Double MaxIOBallowed = constraintChecker.getMaxIOBAllowed().value(); String APSmode = sp.getString(R.string.key_aps_mode, "open"); @@ -333,6 +338,14 @@ public class LoopPlugin extends PluginBase { } return isDisconnected; } + public boolean treatmentTimethreshold(int duartionMinutes) { + long threshold = System.currentTimeMillis() + (duartionMinutes*60*1000); + boolean bool = false; + if (treatmentsPlugin.getLastBolusTime() > threshold || treatmentsPlugin.getLastCarbTime() > threshold) + bool = true; + + return bool; + } public synchronized void invoke(String initiator, boolean allowNotification) { invoke(initiator, allowNotification, false); @@ -384,7 +397,7 @@ public class LoopPlugin extends PluginBase { } result.percent = (int) (result.rate / profile.getBasal() * 100); - // check rate for constrais + // check rate for constraints final APSResult resultAfterConstraints = result.newAndClone(injector); resultAfterConstraints.rateConstraint = new Constraint<>(resultAfterConstraints.rate); resultAfterConstraints.rate = constraintChecker.applyBasalConstraints(resultAfterConstraints.rateConstraint, profile).value(); @@ -402,19 +415,23 @@ public class LoopPlugin extends PluginBase { resultAfterConstraints.smb = 0; } - if (lastRun == null) lastRun = new LastRun(); - lastRun.request = result; - lastRun.constraintsProcessed = resultAfterConstraints; - lastRun.lastAPSRun = DateUtil.now(); - lastRun.source = ((PluginBase) usedAPS).getName(); - lastRun.tbrSetByPump = null; - lastRun.smbSetByPump = null; - lastRun.lastTBREnact = 0; - lastRun.lastTBRRequest = 0; - lastRun.lastSMBEnact = 0; - lastRun.lastSMBRequest = 0; + if (lastRun != null) { + prevCarbsreq = lastRun.getConstraintsProcessed().carbsReq; + } - NSUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore); + if (lastRun == null) lastRun = new LastRun(); + lastRun.setRequest(result); + lastRun.setConstraintsProcessed(resultAfterConstraints); + lastRun.setLastAPSRun(DateUtil.now()); + lastRun.setSource(((PluginBase) usedAPS).getName()); + lastRun.setTbrSetByPump(null); + lastRun.setSmbSetByPump(null); + lastRun.setLastTBREnact(0); + lastRun.setLastTBRRequest(0); + lastRun.setLastSMBEnact(0); + lastRun.setLastSMBRequest(0); + + nsUpload.uploadDeviceStatus(this, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); if (isSuspended()) { getAapsLogger().debug(LTag.APS, resourceHelper.gs(R.string.loopsuspended)); @@ -431,33 +448,100 @@ public class LoopPlugin extends PluginBase { Constraint closedLoopEnabled = constraintChecker.isClosedLoopAllowed(); if (closedLoopEnabled.value()) { + if (allowNotification) { + if (resultAfterConstraints.isCarbsRequired() + && resultAfterConstraints.carbsReq >= sp.getInt(R.string.key_smb_enable_carbs_suggestions_threshold, 0) + && carbsSuggestionsSuspendedUntil < System.currentTimeMillis() && !treatmentTimethreshold(-15)) { + + if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local,true) && !sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)) { + Notification carbreqlocal = new Notification(Notification.CARBS_REQUIRED, resultAfterConstraints.getCarbsRequiredText(), Notification.NORMAL); + rxBus.send(new EventNewNotification(carbreqlocal)); + } + if (sp.getBoolean(R.string.key_ns_create_announcements_from_carbs_req, false)) { + nsUpload.uploadError(resultAfterConstraints.getCarbsRequiredText()); + } + if (sp.getBoolean(R.string.key_enable_carbs_required_alert_local,true) && sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)){ + Intent intentAction5m = new Intent(context, CarbSuggestionReceiver.class); + intentAction5m.putExtra("ignoreDuration", 5); + PendingIntent pendingIntent5m = PendingIntent.getBroadcast(context, 1, intentAction5m, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionIgnore5m = new + NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore5m,"Ignore 5m"), pendingIntent5m); + + Intent intentAction15m = new Intent(context, CarbSuggestionReceiver.class); + intentAction15m.putExtra("ignoreDuration", 15); + PendingIntent pendingIntent15m = PendingIntent.getBroadcast(context, 1, intentAction15m, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionIgnore15m = new + NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore15m,"Ignore 15m"), pendingIntent15m); + + Intent intentAction30m = new Intent(context, CarbSuggestionReceiver.class); + intentAction30m.putExtra("ignoreDuration", 30); + PendingIntent pendingIntent30m = PendingIntent.getBroadcast(context, 1, intentAction30m, PendingIntent.FLAG_UPDATE_CURRENT); + NotificationCompat.Action actionIgnore30m = new + NotificationCompat.Action(R.drawable.ic_notif_aaps, resourceHelper.gs(R.string.ignore30m,"Ignore 30m"), pendingIntent30m); + + NotificationCompat.Builder builder = new NotificationCompat.Builder(context, CHANNEL_ID); + builder.setSmallIcon(R.drawable.notif_icon) + .setContentTitle(resourceHelper.gs(R.string.carbssuggestion)) + .setContentText(resultAfterConstraints.getCarbsRequiredText()) + .setAutoCancel(true) + .setPriority(Notification.IMPORTANCE_HIGH) + .setCategory(Notification.CATEGORY_ALARM) + .addAction(actionIgnore5m) + .addAction(actionIgnore15m) + .addAction(actionIgnore30m) + .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) + .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}); + + NotificationManager mNotificationManager = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + + // mId allows you to update the notification later on. + mNotificationManager.notify(Constants.notificationID, builder.build()); + rxBus.send(new EventNewOpenLoopNotification()); + + //only send to wear if Native notifications are turned off + if (!sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, false)) { + // Send to Wear + actionStringHandler.get().handleInitiate("changeRequest"); + } + } + + } else { + //If carbs were required previously, but are no longer needed, dismiss notifications + if ( prevCarbsreq > 0 ) { + dismissSuggestion(); + rxBus.send(new EventDismissNotification(Notification.CARBS_REQUIRED)); + } + } + } + if (resultAfterConstraints.isChangeRequested() && !commandQueue.bolusInQueue() && !commandQueue.isRunning(Command.CommandType.BOLUS)) { final PumpEnactResult waiting = new PumpEnactResult(getInjector()); waiting.queued = true; if (resultAfterConstraints.tempBasalRequested) - lastRun.tbrSetByPump = waiting; + lastRun.setTbrSetByPump(waiting); if (resultAfterConstraints.bolusRequested) - lastRun.smbSetByPump = waiting; + lastRun.setSmbSetByPump(waiting); rxBus.send(new EventLoopUpdateGui()); fabricPrivacy.logCustom("APSRequest"); applyTBRRequest(resultAfterConstraints, profile, new Callback() { @Override public void run() { if (result.enacted || result.success) { - lastRun.tbrSetByPump = result; - lastRun.lastTBRRequest = lastRun.lastAPSRun; - lastRun.lastTBREnact = DateUtil.now(); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); rxBus.send(new EventLoopUpdateGui()); applySMBRequest(resultAfterConstraints, new Callback() { @Override public void run() { //Callback is only called if a bolus was acutally requested if (result.enacted || result.success) { - lastRun.smbSetByPump = result; - lastRun.lastSMBRequest = lastRun.lastAPSRun; - lastRun.lastSMBEnact = DateUtil.now(); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); } else { new Thread(() -> { SystemClock.sleep(1000); @@ -472,8 +556,8 @@ public class LoopPlugin extends PluginBase { } }); } else { - lastRun.tbrSetByPump = null; - lastRun.smbSetByPump = null; + lastRun.setTbrSetByPump(null); + lastRun.setSmbSetByPump(null); } } else { if (resultAfterConstraints.isChangeRequested() && allowNotification) { @@ -483,42 +567,15 @@ public class LoopPlugin extends PluginBase { .setContentTitle(resourceHelper.gs(R.string.openloop_newsuggestion)) .setContentText(resultAfterConstraints.toString()) .setAutoCancel(true) - .setPriority(Notification.PRIORITY_HIGH) + .setPriority(Notification.IMPORTANCE_HIGH) .setCategory(Notification.CATEGORY_ALARM) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC); if (sp.getBoolean("wearcontrol", false)) { builder.setLocalOnly(true); } - - // Creates an explicit intent for an Activity in your app - Intent resultIntent = new Intent(context, MainActivity.class); - - // The stack builder object will contain an artificial back stack for the - // started Activity. - // This ensures that navigating backward from the Activity leads out of - // your application to the Home screen. - TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); - stackBuilder.addParentStack(MainActivity.class); - // Adds the Intent that starts the Activity to the top of the stack - stackBuilder.addNextIntent(resultIntent); - PendingIntent resultPendingIntent = - stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); - builder.setContentIntent(resultPendingIntent); - builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}); - NotificationManager mNotificationManager = - (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - // mId allows you to update the notification later on. - mNotificationManager.notify(Constants.notificationID, builder.build()); - rxBus.send(new EventNewOpenLoopNotification()); - - // Send to Wear - actionStringHandler.get().handleInitiate("changeRequest"); + presentSuggestion(builder); } else if (allowNotification) { - // dismiss notifications - NotificationManager notificationManager = - (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - notificationManager.cancel(Constants.notificationID); - actionStringHandler.get().handleInitiate("cancelChangeRequest"); + dismissSuggestion(); } } @@ -528,18 +585,57 @@ public class LoopPlugin extends PluginBase { } } + public void disableCarbSuggestions(int duartionMinutes) { + carbsSuggestionsSuspendedUntil = System.currentTimeMillis() + (duartionMinutes*60*1000); + dismissSuggestion(); + } + + private void presentSuggestion(NotificationCompat.Builder builder) { + // Creates an explicit intent for an Activity in your app + Intent resultIntent = new Intent(context, MainActivity.class); + + // The stack builder object will contain an artificial back stack for the + // started Activity. + // This ensures that navigating backward from the Activity leads out of + // your application to the Home screen. + TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); + stackBuilder.addParentStack(MainActivity.class); + // Adds the Intent that starts the Activity to the top of the stack + stackBuilder.addNextIntent(resultIntent); + PendingIntent resultPendingIntent = + stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); + builder.setContentIntent(resultPendingIntent); + builder.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}); + NotificationManager mNotificationManager = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + // mId allows you to update the notification later on. + mNotificationManager.notify(Constants.notificationID, builder.build()); + rxBus.send(new EventNewOpenLoopNotification()); + + // Send to Wear + actionStringHandler.get().handleInitiate("changeRequest"); + } + + private void dismissSuggestion() { + // dismiss notifications + NotificationManager notificationManager = + (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + notificationManager.cancel(Constants.notificationID); + actionStringHandler.get().handleInitiate("cancelChangeRequest"); + } + public void acceptChangeRequest() { Profile profile = profileFunction.getProfile(); final LoopPlugin lp = this; - applyTBRRequest(lastRun.constraintsProcessed, profile, new Callback() { + applyTBRRequest(lastRun.getConstraintsProcessed(), profile, new Callback() { @Override public void run() { if (result.enacted) { - lastRun.tbrSetByPump = result; - lastRun.lastTBRRequest = lastRun.lastAPSRun; - lastRun.lastTBREnact = DateUtil.now(); - lastRun.lastOpenModeAccept = DateUtil.now(); - NSUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore); + lastRun.setTbrSetByPump(result); + lastRun.setLastTBRRequest(lastRun.getLastAPSRun()); + lastRun.setLastTBREnact(DateUtil.now()); + lastRun.setLastOpenModeAccept(DateUtil.now()); + nsUpload.uploadDeviceStatus(lp, iobCobCalculatorPlugin, profileFunction, activePlugin.getActivePump(), receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); sp.incInt(R.string.key_ObjectivesmanualEnacts); } rxBus.send(new EventAcceptOpenLoopChange()); @@ -773,6 +869,7 @@ public class LoopPlugin extends PluginBase { event.eventType = CareportalEvent.OPENAPSOFFLINE; event.json = data.toString(); MainApp.getDbHelper().createOrUpdate(event); - NSUpload.uploadOpenAPSOffline(event); + nsUpload.uploadOpenAPSOffline(event); } + } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java index 50a6c6e018..c6b5afbdeb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/DetermineBasalAdapterAMAJS.java @@ -32,7 +32,7 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt index 342a1395f5..fcd78a9adc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAFragment.kt @@ -32,6 +32,7 @@ class OpenAPSAMAFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var openAPSAMAPlugin: OpenAPSAMAPlugin + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -96,7 +97,7 @@ class OpenAPSAMAFragment : DaggerFragment() { openapsma_scriptdebugdata.text = determineBasalAdapterAMAJS.scriptDebug } if (openAPSAMAPlugin.lastAPSRun != 0L) { - openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun) + openapsma_lastrun.text = dateUtil.dateAndTimeString(openAPSAMAPlugin.lastAPSRun) } openAPSAMAPlugin.lastAutosensResult?.let { openapsma_autosensdata.text = JSONFormatter.format(it.json()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java index 42003d1b13..0cb082f368 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.java @@ -27,8 +27,8 @@ import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; +import info.nightscout.androidaps.interfaces.ProfileFunction; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java index 4d3a0db704..35ba0d3abe 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.java @@ -26,16 +26,16 @@ import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.MealData; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback; +import info.nightscout.androidaps.plugins.aps.loop.ScriptReader; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.interfaces.ActivePluginProvider; - import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.SafeParse; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -237,7 +237,8 @@ public class DetermineBasalAdapterSMBJS { ) throws JSONException { String units = profile.getUnits(); - Double pumpbolusstep = activePluginProvider.getActivePump().getPumpDescription().bolusStep; + PumpInterface pump = activePluginProvider.getActivePump(); + Double pumpbolusstep = pump.getPumpDescription().bolusStep; mProfile = new JSONObject(); mProfile.put("max_iob", maxIob); @@ -259,13 +260,13 @@ public class DetermineBasalAdapterSMBJS { mProfile.put("low_temptarget_lowers_sensitivity", false); - mProfile.put("sensitivity_raises_target", SMBDefaults.sensitivity_raises_target); - mProfile.put("resistance_lowers_target", SMBDefaults.resistance_lowers_target); + mProfile.put("sensitivity_raises_target", sp.getBoolean(resourceHelper.gs(R.string.key_sensitivity_raises_target),SMBDefaults.sensitivity_raises_target)); + mProfile.put("resistance_lowers_target", sp.getBoolean(resourceHelper.gs(R.string.key_resistance_lowers_target),SMBDefaults.resistance_lowers_target)); mProfile.put("adv_target_adjustments", SMBDefaults.adv_target_adjustments); mProfile.put("exercise_mode", SMBDefaults.exercise_mode); mProfile.put("half_basal_exercise_target", SMBDefaults.half_basal_exercise_target); mProfile.put("maxCOB", SMBDefaults.maxCOB); - mProfile.put("skip_neutral_temps", SMBDefaults.skip_neutral_temps); + mProfile.put("skip_neutral_temps", pump.setNeutralTempAtFullHour()); // min_5m_carbimpact is not used within SMB determinebasal //if (mealData.usedMinCarbsImpact > 0) { // mProfile.put("min_5m_carbimpact", mealData.usedMinCarbsImpact); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java index dae170d5d9..640d1b1585 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalResultSMB.java @@ -3,13 +3,17 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; import org.json.JSONException; import org.json.JSONObject; +import javax.inject.Inject; + import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.sharedPreferences.SP; public class DetermineBasalResultSMB extends APSResult { + @Inject SP sp; private double eventualBG; private double snoozeBG; @@ -33,7 +37,10 @@ public class DetermineBasalResultSMB extends APSResult { if (result.has("eventualBG")) eventualBG = result.getDouble("eventualBG"); if (result.has("snoozeBG")) snoozeBG = result.getDouble("snoozeBG"); //if (result.has("insulinReq")) insulinReq = result.getDouble("insulinReq"); - //if (result.has("carbsReq")) carbsReq = result.getDouble("carbsReq"); + + if (result.has("carbsReq")) carbsReq = result.getInt("carbsReq"); + if (result.has("carbsReqWithin")) carbsReqWithin = result.getInt("carbsReqWithin"); + if (result.has("rate") && result.has("duration")) { tempBasalRequested = true; @@ -51,6 +58,9 @@ public class DetermineBasalResultSMB extends APSResult { } else { smb = 0d; } + if (result.has("targetBG")) { + targetBG = result.getDouble("targetBG"); + } if (result.has("deliverAt")) { String date = result.getString("deliverAt"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt index 95b0f7f7b8..c16a432370 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt @@ -33,6 +33,7 @@ class OpenAPSSMBFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var openAPSSMBPlugin: OpenAPSSMBPlugin + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -99,7 +100,7 @@ class OpenAPSSMBFragment : DaggerFragment() { } } if (openAPSSMBPlugin.lastAPSRun != 0L) { - openapsma_lastrun.text = DateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun) + openapsma_lastrun.text = dateUtil.dateAndTimeString(openAPSSMBPlugin.lastAPSRun) } openAPSSMBPlugin.lastAutosensResult?.let { openapsma_autosensdata.text = JSONFormatter.format(it.json()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java index 878d260bca..3e54eb8a3a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.java @@ -2,6 +2,9 @@ package info.nightscout.androidaps.plugins.aps.openAPSSMB; import android.content.Context; +import androidx.preference.PreferenceFragmentCompat; +import androidx.preference.SwitchPreference; + import org.jetbrains.annotations.NotNull; import org.json.JSONException; @@ -30,8 +33,8 @@ import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui; import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateResultGui; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; +import info.nightscout.androidaps.interfaces.ProfileFunction; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; @@ -42,6 +45,7 @@ import info.nightscout.androidaps.utils.HardLimits; import info.nightscout.androidaps.utils.Profiler; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, ConstraintsInterface { @@ -56,6 +60,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr private final HardLimits hardLimits; private final Profiler profiler; private final FabricPrivacy fabricPrivacy; + private final SP sp; // last values DetermineBasalAdapterSMBJS lastDetermineBasalAdapterSMBJS = null; @@ -77,7 +82,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr IobCobCalculatorPlugin iobCobCalculatorPlugin, HardLimits hardLimits, Profiler profiler, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + SP sp ) { super(new PluginDescription() .mainType(PluginType.APS) @@ -100,6 +106,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr this.hardLimits = hardLimits; this.profiler = profiler; this.fabricPrivacy = fabricPrivacy; + this.sp = sp; } @Override @@ -119,6 +126,25 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr return pump.getPumpDescription().isTempBasalCapable; } + @Override + public void preprocessPreferences(@NotNull PreferenceFragmentCompat preferenceFragment) { + super.preprocessPreferences(preferenceFragment); + boolean smbAlwaysEnabled = sp.getBoolean(R.string.key_enableSMB_always, false); + + SwitchPreference withCOB = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_COB)); + if (withCOB != null) { + withCOB.setVisible(!smbAlwaysEnabled); + } + SwitchPreference withTempTarget = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_with_temptarget)); + if (withTempTarget != null) { + withTempTarget.setVisible(!smbAlwaysEnabled); + } + SwitchPreference afterCarbs = preferenceFragment.findPreference(resourceHelper.gs(R.string.key_enableSMB_after_carbs)); + if (afterCarbs != null) { + afterCarbs.setVisible(!smbAlwaysEnabled); + } + } + @Override public APSResult getLastAPSResult() { return lastAPSResult; @@ -174,7 +200,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr long startPart = System.currentTimeMillis(); MealData mealData = iobCobCalculatorPlugin.getMealData(); - profiler.log(LTag.APS, "getMealData()", startPart); + profiler.log(LTag.APS, "getMealData()", startPart); Constraint maxIOBAllowedConstraint = constraintChecker.getMaxIOBAllowed(); inputConstraints.copyReasons(maxIOBAllowedConstraint); @@ -219,7 +245,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr } IobTotal[] iobArray = iobCobCalculatorPlugin.calculateIobArrayForSMB(lastAutosensResult, SMBDefaults.exercise_mode, SMBDefaults.half_basal_exercise_target, isTempTarget); - profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart); + profiler.log(LTag.APS, "calculateIobArrayInDia()", startPart); startPart = System.currentTimeMillis(); Constraint smbAllowed = new Constraint<>(!tempBasalFallback); @@ -234,8 +260,8 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr constraintChecker.isUAMEnabled(uam); inputConstraints.copyReasons(uam); - profiler.log(LTag.APS, "detectSensitivityandCarbAbsorption()", startPart); - profiler.log(LTag.APS, "SMB data gathering", start); + profiler.log(LTag.APS, "detectSensitivityandCarbAbsorption()", startPart); + profiler.log(LTag.APS, "SMB data gathering", start); start = System.currentTimeMillis(); try { @@ -254,7 +280,7 @@ public class OpenAPSSMBPlugin extends PluginBase implements APSInterface, Constr long now = System.currentTimeMillis(); DetermineBasalResultSMB determineBasalResultSMB = determineBasalAdapterSMBJS.invoke(); - profiler.log(LTag.APS, "SMB calculation", start); + profiler.log(LTag.APS, "SMB calculation", start); if (determineBasalResultSMB == null) { getAapsLogger().error(LTag.APS, "SMB calculation returned null"); lastDetermineBasalAdapterSMBJS = null; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 57781a090a..3badb56824 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -12,6 +12,7 @@ import android.widget.RadioButton import android.widget.TextView import androidx.annotation.StringRes import dagger.android.support.DaggerFragment +import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.PreferencesActivity import info.nightscout.androidaps.events.EventRebuildTabs @@ -20,9 +21,9 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.extensions.plusAssign +import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.extensions.toVisibility import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.configbuilder_fragment.* @@ -36,6 +37,7 @@ class ConfigBuilderFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var protectionCheck: ProtectionCheck + @Inject lateinit var config: Config private var disposable: CompositeDisposable = CompositeDisposable() private val pluginViewHolders = ArrayList() @@ -86,14 +88,20 @@ class ConfigBuilderFragment : DaggerFragment() { @Synchronized private fun updateGUI() { configbuilder_categories.removeAllViews() - createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE)) + if (!config.NSCLIENT) { + createViewsForPlugins(R.string.configbuilder_profile, R.string.configbuilder_profile_description, PluginType.PROFILE, activePlugin.getSpecificPluginsVisibleInListByInterface(ProfileInterface::class.java, PluginType.PROFILE)) + } createViewsForPlugins(R.string.configbuilder_insulin, R.string.configbuilder_insulin_description, PluginType.INSULIN, activePlugin.getSpecificPluginsVisibleInListByInterface(InsulinInterface::class.java, PluginType.INSULIN)) - createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE)) - createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP)) + if (!config.NSCLIENT) { + createViewsForPlugins(R.string.configbuilder_bgsource, R.string.configbuilder_bgsource_description, PluginType.BGSOURCE, activePlugin.getSpecificPluginsVisibleInListByInterface(BgSourceInterface::class.java, PluginType.BGSOURCE)) + createViewsForPlugins(R.string.configbuilder_pump, R.string.configbuilder_pump_description, PluginType.PUMP, activePlugin.getSpecificPluginsVisibleInList(PluginType.PUMP)) + } createViewsForPlugins(R.string.configbuilder_sensitivity, R.string.configbuilder_sensitivity_description, PluginType.SENSITIVITY, activePlugin.getSpecificPluginsVisibleInListByInterface(SensitivityInterface::class.java, PluginType.SENSITIVITY)) - createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS)) - createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP)) - createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS)) + if (config.APS) { + createViewsForPlugins(R.string.configbuilder_aps, R.string.configbuilder_aps_description, PluginType.APS, activePlugin.getSpecificPluginsVisibleInList(PluginType.APS)) + createViewsForPlugins(R.string.configbuilder_loop, R.string.configbuilder_loop_description, PluginType.LOOP, activePlugin.getSpecificPluginsVisibleInList(PluginType.LOOP)) + createViewsForPlugins(R.string.constraints, R.string.configbuilder_constraints_description, PluginType.CONSTRAINTS, activePlugin.getSpecificPluginsVisibleInListByInterface(ConstraintsInterface::class.java, PluginType.CONSTRAINTS)) + } createViewsForPlugins(R.string.configbuilder_treatments, R.string.configbuilder_treatments_description, PluginType.TREATMENT, activePlugin.getSpecificPluginsVisibleInList(PluginType.TREATMENT)) createViewsForPlugins(R.string.configbuilder_general, R.string.configbuilder_general_description, PluginType.GENERAL, activePlugin.getSpecificPluginsVisibleInList(PluginType.GENERAL)) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt index 5d274d933b..598ddf085f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt @@ -36,7 +36,7 @@ class ConfigBuilderPlugin @Inject constructor( .shortName(R.string.configbuilder_shortname) .description(R.string.description_config_builder), aapsLogger, resourceHelper, injector -) { +), ConfigBuilderInterface { fun initialize() { (activePlugin as PluginStore).loadDefaults() @@ -52,7 +52,7 @@ class ConfigBuilderPlugin @Inject constructor( storeSettings("setAlwaysEnabledPluginsEnabled") } - fun storeSettings(from: String) { + override fun storeSettings(from: String) { activePlugin.pluginsList aapsLogger.debug(LTag.CONFIGBUILDER, "Storing settings from: $from") activePlugin.verifySelectionInCategories() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt index 35ba1db642..3958f17d78 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt @@ -9,7 +9,8 @@ import javax.inject.Singleton @Singleton class PluginStore @Inject constructor( - val aapsLogger: AAPSLogger + private val aapsLogger: AAPSLogger, + private val config: Config ) : ActivePluginProvider { lateinit var plugins: List<@JvmSuppressWildcards PluginBase> @@ -68,7 +69,7 @@ class PluginStore @Inject constructor( var pluginsInCategory: ArrayList? // PluginType.APS - if (!Config.NSCLIENT && !Config.PUMPCONTROL) { + if (!config.NSCLIENT && !config.PUMPCONTROL) { pluginsInCategory = getSpecificPluginsList(PluginType.APS) activeAPS = getTheOneEnabledInArray(pluginsInCategory, PluginType.APS) as APSInterface? if (activeAPS == null) { @@ -107,7 +108,7 @@ class PluginStore @Inject constructor( (activeProfile as PluginBase).setPluginEnabled(PluginType.PROFILE, true) aapsLogger.debug(LTag.CONFIGBUILDER, "Defaulting ProfileInterface") } - setFragmentVisiblities((activeSensitivity as PluginBase).name, pluginsInCategory, PluginType.PROFILE) + setFragmentVisiblities((activeProfile as PluginBase).name, pluginsInCategory, PluginType.PROFILE) // PluginType.BGSOURCE pluginsInCategory = getSpecificPluginsList(PluginType.BGSOURCE) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt index 5fe20f2968..69a8892bdc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesFragment.kt @@ -22,8 +22,8 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.constraints.objectives.activities.ObjectivesExamDialog -import info.nightscout.androidaps.plugins.constraints.objectives.dialogs.NtpProgressDialog -import info.nightscout.androidaps.plugins.constraints.objectives.events.EventNtpStatus +import info.nightscout.androidaps.dialogs.NtpProgressDialog +import info.nightscout.androidaps.events.EventNtpStatus import info.nightscout.androidaps.plugins.constraints.objectives.events.EventObjectivesUpdateGui import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective.ExamTask import info.nightscout.androidaps.receivers.ReceiverStatusStore @@ -49,6 +49,8 @@ class ObjectivesFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var objectivesPlugin: ObjectivesPlugin @Inject lateinit var receiverStatusStore: ReceiverStatusStore + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var sntpClient: SntpClient private val objectivesAdapter = ObjectivesAdapter() private val handler = Handler(Looper.getMainLooper()) @@ -221,7 +223,7 @@ class ObjectivesFragment : DaggerFragment() { holder.progress.addView(separator, LinearLayout.LayoutParams.MATCH_PARENT, 2) } } - holder.accomplished.text = resourceHelper.gs(R.string.accomplished, DateUtil.dateAndTimeString(objective.accomplishedOn)) + holder.accomplished.text = resourceHelper.gs(R.string.accomplished, dateUtil.dateAndTimeString(objective.accomplishedOn)) holder.accomplished.setTextColor(-0x3e3e3f) holder.verify.setOnClickListener { receiverStatusStore.updateNetworkStatus() @@ -236,7 +238,7 @@ class ObjectivesFragment : DaggerFragment() { Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) - SntpClient.ntpTime(object : SntpClient.Callback() { + sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") SystemClock.sleep(300) @@ -275,7 +277,7 @@ class ObjectivesFragment : DaggerFragment() { Thread { NtpProgressDialog().show((context as AppCompatActivity).supportFragmentManager, "NtpCheck") rxBus.send(EventNtpStatus(resourceHelper.gs(R.string.timedetection), 0)) - SntpClient.ntpTime(object : SntpClient.Callback() { + sntpClient.ntpTime(object : SntpClient.Callback() { override fun run() { aapsLogger.debug("NTP time: $time System time: ${DateUtil.now()}") SystemClock.sleep(300) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt index 209a74f44a..cc57908438 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPlugin.kt @@ -24,13 +24,14 @@ class ObjectivesPlugin @Inject constructor( aapsLogger: AAPSLogger, resourceHelper: ResourceHelper, private val activePlugin: ActivePluginProvider, - private val sp: SP + private val sp: SP, + private val config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.CONSTRAINTS) .fragmentClass(ObjectivesFragment::class.qualifiedName) - .alwaysEnabled(Config.APS) - .showInList(Config.APS) + .alwaysEnabled(config.APS) + .showInList(config.APS) .pluginName(R.string.objectives) .shortName(R.string.objectives_shortname) .description(R.string.description_objectives), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt index 2ea9743cee..e44135eb45 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/activities/ObjectivesExamDialog.kt @@ -21,6 +21,7 @@ import javax.inject.Inject class ObjectivesExamDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var dateUtil: DateUtil companion object { var objective: Objective? = null @@ -76,7 +77,7 @@ class ObjectivesExamDialog : DaggerDialogFragment() { objectives_exam_hints.addView(h.generate(context)) } // Disabled to - objectives_exam_disabledto.text = resourceHelper.gs(R.string.answerdisabledto, DateUtil.timeString(task.disabledTo)) + objectives_exam_disabledto.text = resourceHelper.gs(R.string.answerdisabledto, dateUtil.timeString(task.disabledTo)) objectives_exam_disabledto.visibility = if (task.isEnabledAnswer) View.GONE else View.VISIBLE // Buttons objectives_exam_verify.isEnabled = !task.answered && task.isEnabledAnswer diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java index 68c9ee7112..62eb212ee3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective2.java @@ -19,7 +19,7 @@ public class Objective2 extends Objective { @Override protected void setupTasks(List tasks) { - tasks.add(new ExamTask(R.string.dia_label, R.string.dia_whatmeansdia,"dia") + tasks.add(new ExamTask(R.string.dia_label_exam, R.string.dia_whatmeansdia,"dia") .option(new Option(R.string.dia_minimumis3h, false)) .option(new Option(R.string.dia_minimumis5h, true)) .option(new Option(R.string.dia_meaningisequaltodiapump, false)) @@ -160,7 +160,7 @@ public class Objective2 extends Objective { .option(new Option(R.string.nsclient_spikeiphone, true)) .hint(new Hint(R.string.nsclient_hint1)) ); - tasks.add(new ExamTask(R.string.isf_label, R.string.whatistrue,"isf") + tasks.add(new ExamTask(R.string.isf_label_exam, R.string.whatistrue,"isf") .option(new Option(R.string.isf_increasingvalue, true)) .option(new Option(R.string.isf_decreasingvalue, false)) .option(new Option(R.string.isf_noeffect, false)) @@ -169,7 +169,7 @@ public class Objective2 extends Objective { .hint(new Hint(R.string.isf_hint1)) .hint(new Hint(R.string.isf_hint2)) ); - tasks.add(new ExamTask(R.string.ic_label, R.string.whatistrue,"ic") + tasks.add(new ExamTask(R.string.ic_label_exam, R.string.whatistrue,"ic") .option(new Option(R.string.ic_increasingvalue, true)) .option(new Option(R.string.ic_decreasingvalue, false)) .option(new Option(R.string.ic_noeffect, false)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java index ab325f1f0c..b6f25325f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.java @@ -47,6 +47,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { private HardLimits hardLimits; private BuildHelper buildHelper; private TreatmentsPlugin treatmentsPlugin; + private Config config; @Inject public SafetyPlugin( @@ -62,7 +63,8 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { ActivePluginProvider activePlugin, HardLimits hardLimits, BuildHelper buildHelper, - TreatmentsPlugin treatmentsPlugin + TreatmentsPlugin treatmentsPlugin, + Config config ) { super(new PluginDescription() .mainType(PluginType.CONSTRAINTS) @@ -83,6 +85,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { this.hardLimits = hardLimits; this.buildHelper = buildHelper; this.treatmentsPlugin = treatmentsPlugin; + this.config = config; } /** @@ -159,7 +162,7 @@ public class SafetyPlugin extends PluginBase implements ConstraintsInterface { absoluteRate.setIfGreater(getAapsLogger(), 0d, String.format(getResourceHelper().gs(R.string.limitingbasalratio), 0d, getResourceHelper().gs(R.string.itmustbepositivevalue)), this); - if (Config.APS) { + if (config.getAPS()) { double maxBasal = sp.getDouble(R.string.key_openapsma_max_basal, 1d); if (maxBasal < profile.getMaxDailyBasal()) { maxBasal = profile.getMaxDailyBasal(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt index 6a324d74cc..22973b3caf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsFragment.kt @@ -18,9 +18,9 @@ import info.nightscout.androidaps.events.* import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.queue.Callback @@ -54,6 +54,7 @@ class ActionsFragment : DaggerFragment() { @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var protectionCheck: ProtectionCheck + @Inject lateinit var config: Config private var disposable: CompositeDisposable = CompositeDisposable() @@ -143,6 +144,12 @@ class ActionsFragment : DaggerFragment() { actions_exercise.setOnClickListener { CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions") } + actions_question.setOnClickListener { + CareDialog().setOptions(CareDialog.EventType.QUESTION, R.string.careportal_question).show(childFragmentManager, "Actions") + } + actions_announcement.setOnClickListener { + CareDialog().setOptions(CareDialog.EventType.ANNOUNCEMENT, R.string.careportal_announcement).show(childFragmentManager, "Actions") + } sp.putBoolean(R.string.key_objectiveuseactions, true) } @@ -185,23 +192,15 @@ class ActionsFragment : DaggerFragment() { @Synchronized fun updateGui() { - actions_profileswitch?.visibility = (activePlugin.activeProfileInterface.profile != null).toVisibility() val profile = profileFunction.getProfile() val pump = activePlugin.activePump - actions_temptarget?.visibility = (profile != null).toVisibility() - actions_canceltempbasal.visibility = (profile == null).toVisibility() - actions_settempbasal.visibility = (profile == null).toVisibility() - actions_fill.visibility = (profile == null).toVisibility() - actions_extendedbolus.visibility = (profile == null).toVisibility() - actions_extendedbolus_cancel.visibility = (profile == null).toVisibility() - actions_historybrowser.visibility = (profile == null).toVisibility() - actions_tddstats.visibility = (profile == null).toVisibility() - - val basalProfileEnabled = buildHelper.isEngineeringModeOrRelease() && pump.pumpDescription.isSetBasalProfileCapable - - actions_profileswitch?.visibility = if (!basalProfileEnabled || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE + actions_profileswitch?.visibility = ( + activePlugin.activeProfileInterface.profile != null && + pump.pumpDescription.isSetBasalProfileCapable && + pump.isInitialized && + !pump.isSuspended).toVisibility() if (!pump.pumpDescription.isExtendedBolusCapable || !pump.isInitialized || pump.isSuspended || pump.isFakingTempsByExtendedBoluses) { actions_extendedbolus?.visibility = View.GONE @@ -235,12 +234,11 @@ class ActionsFragment : DaggerFragment() { } } - actions_fill?.visibility = - if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE - else View.VISIBLE - - actions_temptarget?.visibility = Config.APS.toVisibility() + actions_historybrowser.visibility = (profile != null).toVisibility() + actions_fill?.visibility = (pump.pumpDescription.isRefillingCapable && pump.isInitialized && !pump.isSuspended).toVisibility() + actions_temptarget?.visibility = (profile != null && config.APS).toVisibility() actions_tddstats?.visibility = pump.pumpDescription.supportsTDDs.toVisibility() + statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null) checkPumpCustomActions() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt index 91125a9e1e..ff3927da71 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/actions/ActionsPlugin.kt @@ -15,12 +15,13 @@ import javax.inject.Singleton class ActionsPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper + resourceHelper: ResourceHelper, + config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(ActionsFragment::class.qualifiedName) - .enableByDefault(Config.APS || Config.PUMPCONTROL) - .visibleByDefault(Config.APS || Config.PUMPCONTROL) + .enableByDefault(config.APS || config.PUMPCONTROL) + .visibleByDefault(config.APS || config.PUMPCONTROL) .pluginName(R.string.actions) .shortName(R.string.actions_shortname) .description(R.string.description_actions), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index 9a1c4d5c3a..dff373058e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -4,6 +4,8 @@ import android.content.Context import android.content.Intent import android.os.Build import android.os.Handler +import android.os.HandlerThread +import android.os.SystemClock import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.events.EventBTChange @@ -37,10 +39,8 @@ import io.reactivex.schedulers.Schedulers import org.json.JSONArray import org.json.JSONException import org.json.JSONObject -import java.util.* import javax.inject.Inject import javax.inject.Singleton -import kotlin.collections.ArrayList @Singleton class AutomationPlugin @Inject constructor( @@ -52,7 +52,8 @@ class AutomationPlugin @Inject constructor( private val loopPlugin: LoopPlugin, private val rxBus: RxBusWrapper, private val constraintChecker: ConstraintChecker, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val dateUtil: DateUtil ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(AutomationFragment::class.qualifiedName) @@ -71,7 +72,7 @@ class AutomationPlugin @Inject constructor( var executionLog: MutableList = ArrayList() var btConnects : MutableList = ArrayList() - private val loopHandler = Handler() + private val loopHandler : Handler = Handler(HandlerThread(AutomationPlugin::class.java.simpleName + "Handler").also { it.start() }.looper) private lateinit var refreshLoop: Runnable init { @@ -177,10 +178,9 @@ class AutomationPlugin @Inject constructor( @Synchronized private fun processActions() { - if (!isEnabled(PluginType.GENERAL)) - return - if (loopPlugin.isSuspended || !loopPlugin.isEnabled(PluginType.LOOP)) { + if (loopPlugin.isSuspended || !loopPlugin.isEnabled()) { aapsLogger.debug(LTag.AUTOMATION, "Loop deactivated") + executionLog.add(resourceHelper.gs(R.string.smscommunicator_loopisdisabled)) return } val enabled = constraintChecker.isAutomationEnabled() @@ -197,7 +197,7 @@ class AutomationPlugin @Inject constructor( action.doAction(object : Callback() { override fun run() { val sb = StringBuilder() - sb.append(DateUtil.timeString(DateUtil.now())) + sb.append(dateUtil.timeString(DateUtil.now())) sb.append(" ") sb.append(if (result.success) "☺" else "▼") sb.append(" ") @@ -212,6 +212,7 @@ class AutomationPlugin @Inject constructor( } }) } + SystemClock.sleep(1100) event.lastRun = DateUtil.now() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt index 4e155bcdcc..051e1c8bb0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionLoopResume.kt @@ -8,7 +8,6 @@ import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt index 76152b8861..43342f35e5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotification.kt @@ -12,7 +12,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithE 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.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationUserMessage import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper @@ -23,6 +22,7 @@ import javax.inject.Inject class ActionNotification(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var rxBus: RxBusWrapper + @Inject lateinit var nsUpload: NSUpload var text = InputString(injector) @@ -33,7 +33,7 @@ class ActionNotification(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { val notification = NotificationUserMessage(text.value) rxBus.send(EventNewNotification(notification)) - NSUpload.uploadError(text.value) + nsUpload.uploadError(text.value) rxBus.send(EventRefreshOverview("ActionNotification")) callback.result(PumpEnactResult(injector).success(true).comment(R.string.ok))?.run() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt index 3e6406fac0..9d4bc5f81d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitch.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder @@ -27,7 +27,7 @@ class ActionProfileSwitch(injector: HasAndroidInjector) : Action(injector) { override fun friendlyName(): Int = R.string.profilename override fun shortDescription(): String = resourceHelper.gs(R.string.changengetoprofilename, inputProfileName.value) - @DrawableRes override fun icon(): Int = R.drawable.icon_actions_profileswitch + @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch override fun doAction(callback: Callback) { val activeProfileName = profileFunction.getProfileName() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt index f45e8d19e9..b0cb5f555f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionProfileSwitchPercent.kt @@ -30,7 +30,7 @@ class ActionProfileSwitchPercent(injector: HasAndroidInjector) : Action(injector if (duration.value == 0) resourceHelper.gs(R.string.startprofileforever, pct.value.toInt()) else resourceHelper.gs(R.string.startprofile, pct.value.toInt(), duration.value) - @DrawableRes override fun icon(): Int = R.drawable.icon_actions_profileswitch + @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch init { precondition = TriggerProfilePercent(injector, 100.0, Comparator.Compare.IS_EQUAL) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt index 5db3c14add..61f727c9a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt @@ -26,7 +26,7 @@ class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) { override fun doAction(callback: Callback) { val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value) - callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.danar_error))?.run() + callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.error))?.run() } override fun toJSON(): String { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt index d0cb6b09e7..812a572df9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionStartTempTarget.kt @@ -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.icon_cp_cgm_target + @DrawableRes override fun icon(): Int = R.drawable.ic_cp_cgm_target override fun doAction(callback: Callback) { activePlugin.activeTreatments.addToHistoryTempTarget(tt()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt index 86fd8dc73e..11b8d1b952 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt @@ -74,7 +74,7 @@ class Comparator(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { value = Compare.values()[position] } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt index 3e293fef5a..5d2d47edf9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt @@ -48,7 +48,7 @@ class ComparatorConnect(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { value = Compare.values()[position] } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt index 2e7e437bd9..cb7eb8a32e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt @@ -48,7 +48,7 @@ class ComparatorExists(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { value = Compare.values()[position] } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt index c7ee4a5d6a..24b48e0fb7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputBg.kt @@ -4,8 +4,8 @@ import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt index f61d1d5719..2c92fcb75f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt @@ -18,6 +18,7 @@ import javax.inject.Inject class InputDateTime(injector: HasAndroidInjector) : Element(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var context: Context + @Inject lateinit var dateUtil: DateUtil var value: Long = DateUtil.now() @@ -30,7 +31,7 @@ class InputDateTime(injector: HasAndroidInjector) : Element(injector) { val dateButton = TextView(root.context) val timeButton = TextView(root.context) dateButton.text = DateUtil.dateString(value) - timeButton.text = DateUtil.timeString(value) + timeButton.text = dateUtil.timeString(value) // create an OnDateSetListener val dateSetListener = DatePickerDialog.OnDateSetListener { _, year, monthOfYear, dayOfMonth -> @@ -63,7 +64,7 @@ class InputDateTime(injector: HasAndroidInjector) : Element(injector) { cal.set(Calendar.MINUTE, minute) cal.set(Calendar.SECOND, 0) // randomize seconds to prevent creating record of the same time, if user choose time manually value = cal.timeInMillis - timeButton.text = DateUtil.timeString(value) + timeButton.text = dateUtil.timeString(value) } timeButton.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt index a667b51099..46b696eaec 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt @@ -9,7 +9,7 @@ import android.widget.Spinner import androidx.annotation.StringRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import info.nightscout.androidaps.utils.resources.ResourceHelper import java.text.DecimalFormat import java.util.* @@ -76,7 +76,7 @@ class InputDelta(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { deltaType = DeltaType.values()[position] } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt index 7824b51960..566315b9eb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDouble.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat class InputDouble(injector: HasAndroidInjector) : Element(injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt index 7f894293f9..473d26bb4b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt @@ -38,7 +38,7 @@ class InputDropdownMenu(injector: HasAndroidInjector) : Element(injector) { ).also { it.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) } spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { setValue(itemList[position].toString()) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt index cab16d2502..08647735cd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDuration.kt @@ -3,7 +3,8 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.MinutesNumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat class InputDuration(injector: HasAndroidInjector) : Element(injector) { @@ -20,11 +21,14 @@ class InputDuration(injector: HasAndroidInjector) : Element(injector) { var value: Int = 0 override fun addToLayout(root: LinearLayout) { - val numberPicker = NumberPicker(root.context, null) - if (unit == TimeUnit.MINUTES) + val numberPicker : NumberPicker + if (unit == TimeUnit.MINUTES) { + numberPicker = MinutesNumberPicker(root.context, null) numberPicker.setParams(0.0, 0.0, 24 * 60.0, 10.0, DecimalFormat("0"), false, root.findViewById(R.id.ok)) - else + } else { + numberPicker = NumberPicker(root.context, null) numberPicker.setParams(0.0, 0.0, 24.0, 1.0, DecimalFormat("0"), false, root.findViewById(R.id.ok)) + } numberPicker.value = value.toDouble() numberPicker.setOnValueChangedListener { value: Double -> this.value = value.toInt() } root.addView(numberPicker) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt index f822a971f4..0903824a94 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputInsulin.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat class InputInsulin(injector: HasAndroidInjector) : Element(injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt index 9e3f7280cc..e5e42fa60a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt @@ -62,7 +62,7 @@ class InputLocationMode(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { value = Mode.values()[position] } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt index 7b1f739ed7..05524abc40 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.automation.elements import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat class InputPercent(injector: HasAndroidInjector) : Element(injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt index 57e010eabe..57f2b904b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt @@ -36,7 +36,7 @@ class InputProfileName(injector: HasAndroidInjector) : Element(injector) { spinnerParams.setMargins(0, resourceHelper.dpToPx(4), 0, resourceHelper.dpToPx(4)) spinner.layoutParams = spinnerParams spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { value = profileList[position].toString() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt index fa1939e951..4f58be8167 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTempTarget.kt @@ -4,14 +4,18 @@ import android.widget.LinearLayout import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat +import javax.inject.Inject class InputTempTarget(injector: HasAndroidInjector) : Element(injector) { var units = Constants.MGDL var value = 0.0 + @Inject lateinit var profileFunction: ProfileFunction init { + units = profileFunction.getUnits() value = if (units == Constants.MMOL) 6.0 else 110.0 } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt index 01a7854e35..bd0622b29b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt @@ -12,7 +12,6 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -20,17 +19,18 @@ import javax.inject.Inject class InputTime(injector: HasAndroidInjector) : Element(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var context: Context + @Inject lateinit var dateUtil: DateUtil var value: Int = getMinSinceMidnight(DateUtil.now()) override fun addToLayout(root: LinearLayout) { val label = TextView(root.context) val startButton = TextView(root.context) - startButton.text = DateUtil.timeString(toMills(value)) + startButton.text = dateUtil.timeString(toMills(value)) val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> value = 60 * hour + minute - startButton.text = DateUtil.timeString(toMills(value)) + startButton.text = dateUtil.timeString(toMills(value)) } startButton.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt index 4775990d16..f8d0a369dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt @@ -12,7 +12,6 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -20,6 +19,7 @@ import javax.inject.Inject class InputTimeRange(injector: HasAndroidInjector) : Element(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var context: Context + @Inject lateinit var dateUtil: DateUtil var start: Int = getMinSinceMidnight(DateUtil.now()) var end: Int = getMinSinceMidnight(DateUtil.now()) @@ -28,13 +28,13 @@ class InputTimeRange(injector: HasAndroidInjector) : Element(injector) { val label = TextView(root.context) val startButton = TextView(root.context) val endButton = TextView(root.context) - startButton.text = DateUtil.timeString(toMills(start)) + startButton.text = dateUtil.timeString(toMills(start)) @Suppress("SetTextI18n") - endButton.text = resourceHelper.gs(R.string.and) + " " + DateUtil.timeString(toMills(end)) + endButton.text = resourceHelper.gs(R.string.and) + " " + dateUtil.timeString(toMills(end)) val startTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> start = 60 * hour + minute - startButton.text = DateUtil.timeString(toMills(start)) + startButton.text = dateUtil.timeString(toMills(start)) } startButton.setOnClickListener { @@ -51,7 +51,7 @@ class InputTimeRange(injector: HasAndroidInjector) : Element(injector) { val endTimeSetListener = TimePickerDialog.OnTimeSetListener { _, hour, minute -> end = 60 * hour + minute - endButton.text = DateUtil.timeString(toMills(end)) + endButton.text = dateUtil.timeString(toMills(end)) } endButton.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index 3890deb60d..fce6bb41c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseTriggerDialog import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerChanged import info.nightscout.androidaps.plugins.general.automation.events.EventTriggerClone @@ -98,7 +98,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { ) params.gravity = Gravity.CENTER buttonAdd.layoutParams = params - buttonAdd.setImageResource(R.drawable.add) + buttonAdd.setImageResource(R.drawable.ic_add) buttonAdd.contentDescription = resourceHelper.gs(R.string.add_short) buttonAdd.setOnClickListener { scanForActivity(context)?.supportFragmentManager?.let { @@ -124,7 +124,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { ) params.gravity = Gravity.CENTER buttonRemove.layoutParams = params - buttonRemove.setImageResource(R.drawable.remove) + buttonRemove.setImageResource(R.drawable.ic_remove) buttonRemove.contentDescription = resourceHelper.gs(R.string.delete_short) buttonRemove.setOnClickListener { rxBus.send(EventTriggerRemove(trigger)) @@ -141,7 +141,7 @@ abstract class Trigger(val injector: HasAndroidInjector) { ) params.gravity = Gravity.CENTER buttonClone.layoutParams = params - buttonClone.setImageResource(R.drawable.clone) + buttonClone.setImageResource(R.drawable.ic_clone) buttonClone.contentDescription = resourceHelper.gs(R.string.copy_short) buttonClone.setOnClickListener { rxBus.send(EventTriggerClone(trigger)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt index d6f8a607ff..3b3dbe1f68 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerAutosensValue.kt @@ -68,7 +68,7 @@ class TriggerAutosensValue(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String = resourceHelper.gs(R.string.autosenscompared, resourceHelper.gs(comparator.value.stringRes), autosens.value) - override fun icon(): Optional = Optional.of(R.drawable.`as`) + override fun icon(): Optional = Optional.of(R.drawable.`ic_as`) override fun duplicate(): Trigger = TriggerAutosensValue(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt index 75b30edb3b..558bc9ac4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBg.kt @@ -91,7 +91,7 @@ class TriggerBg(injector: HasAndroidInjector) : Trigger(injector) { resourceHelper.gs(if (bg.units == Constants.MGDL) R.string.glucosecomparedmgdl else R.string.glucosecomparedmmol, resourceHelper.gs(comparator.value.stringRes), bg.value, bg.units) } - override fun icon(): Optional = Optional.of(R.drawable.icon_cp_bgcheck) + override fun icon(): Optional = Optional.of(R.drawable.ic_cp_bgcheck) override fun duplicate(): Trigger = TriggerBg(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt index db57bb159a..2e2360daf3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerBolusAgo.kt @@ -35,7 +35,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { } override fun shouldRun(): Boolean { - val lastBolusTime = treatmentsPlugin.getLastBolusTime(false) + val lastBolusTime = treatmentsPlugin.getLastBolusTime(true) if (lastBolusTime == 0L) return if (comparator.value == Comparator.Compare.IS_NOT_AVAILABLE) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) @@ -77,7 +77,7 @@ class TriggerBolusAgo(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String = resourceHelper.gs(R.string.lastboluscompared, resourceHelper.gs(comparator.value.stringRes), minutesAgo.getMinutes()) - override fun icon(): Optional = Optional.of(R.drawable.icon_bolus) + override fun icon(): Optional = Optional.of(R.drawable.ic_bolus) override fun duplicate(): Trigger = TriggerBolusAgo(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt index 82aa8cd6f1..6d07ef1188 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerCOB.kt @@ -77,7 +77,7 @@ class TriggerCOB(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String = resourceHelper.gs(R.string.cobcompared, resourceHelper.gs(comparator.value.stringRes), cob.value) - override fun icon(): Optional = Optional.of(R.drawable.icon_cp_bolus_carbs) + override fun icon(): Optional = Optional.of(R.drawable.ic_cp_bolus_carbs) override fun duplicate(): Trigger = TriggerCOB(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt index 8574bfa05c..6d19c24441 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt @@ -160,7 +160,7 @@ class TriggerConnector(injector: HasAndroidInjector) : Trigger(injector) { params.weight = 1.0f spinner.layoutParams = params spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) { + override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { setType(Type.values()[position]) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt index 0a7972461a..78702bb975 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDelta.kt @@ -108,7 +108,7 @@ class TriggerDelta(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String = resourceHelper.gs(R.string.deltacompared, resourceHelper.gs(comparator.value.stringRes), delta.value, resourceHelper.gs(delta.deltaType.stringRes)) - override fun icon(): Optional = Optional.of(R.drawable.icon_auto_delta) + override fun icon(): Optional = Optional.of(R.drawable.ic_auto_delta) override fun duplicate(): Trigger = TriggerDelta(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt index a9f3c936d9..da1ebd4914 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerLocation.kt @@ -21,8 +21,8 @@ class TriggerLocation(injector: HasAndroidInjector) : Trigger(injector) { var lastMode = InputLocationMode.Mode.INSIDE private val buttonAction = Runnable { locationDataContainer.lastLocation?.let { - latitude.value = it.latitude - longitude.value = it.longitude + latitude.setValue(it.latitude) + longitude.setValue(it.longitude) aapsLogger.debug(LTag.AUTOMATION, String.format("Grabbed location: %f %f", latitude.value, longitude.value)) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt index 1dea3cd15f..9a13ebedeb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerProfilePercent.kt @@ -77,7 +77,7 @@ class TriggerProfilePercent(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyDescription(): String = resourceHelper.gs(R.string.percentagecompared, resourceHelper.gs(comparator.value.stringRes), pct.value.toInt()) - override fun icon(): Optional = Optional.of(R.drawable.icon_actions_profileswitch) + override fun icon(): Optional = Optional.of(R.drawable.ic_actions_profileswitch) override fun duplicate(): Trigger = TriggerProfilePercent(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt index 0e2228cf5e..3248269997 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerPumpLastConnection.kt @@ -77,7 +77,7 @@ class TriggerPumpLastConnection(injector: HasAndroidInjector) : Trigger(injector override fun friendlyDescription(): String = resourceHelper.gs(R.string.automation_trigger_pump_last_connection_compared, resourceHelper.gs(comparator.value.stringRes), minutesAgo.value) - override fun icon(): Optional = Optional.of(R.drawable.remove) + override fun icon(): Optional = Optional.of(R.drawable.ic_remove) override fun duplicate(): Trigger = TriggerPumpLastConnection(injector, this) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt index 8982a12669..ffc79e39e1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerRecurringTime.kt @@ -13,11 +13,13 @@ import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabe import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.T import org.json.JSONObject import java.util.* +import javax.inject.Inject class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { + @Inject lateinit var dateUtil: DateUtil + val days = InputWeekDay(injector) val time = InputTime(injector) @@ -27,17 +29,16 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { System.arraycopy(triggerRecurringTime.days.weekdays, 0, days.weekdays, 0, triggerRecurringTime.days.weekdays.size) } - fun time(minutes:Int): TriggerRecurringTime { + fun time(minutes: Int): TriggerRecurringTime { time.value = minutes - return this + return this } - override fun shouldRun(): Boolean { - val currentMinSinceMidnight = getMinSinceMidnight(DateUtil.now()) + override fun shouldRun() : Boolean { + val currentMinSinceMidnight = getMinSinceMidnight(dateUtil._now()) val scheduledDayOfWeek = Calendar.getInstance()[Calendar.DAY_OF_WEEK] - val scheduled = getMinSinceMidnight(time.value.toLong()) if (days.isSet(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(scheduledDayOfWeek)))) { - if (currentMinSinceMidnight >= scheduled && currentMinSinceMidnight - scheduled < 5) { + if (currentMinSinceMidnight >= time.value && currentMinSinceMidnight - time.value < 5) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } @@ -85,7 +86,7 @@ class TriggerRecurringTime(injector: HasAndroidInjector) : Trigger(injector) { sb.append(resourceHelper.gs(Objects.requireNonNull(InputWeekDay.DayOfWeek.fromCalendarInt(i)).shortName)) } sb.append(" ") - sb.append(DateUtil.timeString(toMills(time.value))) + sb.append(dateUtil.timeString(toMills(time.value))) return if (counter == 0) resourceHelper.gs(R.string.never) else sb.toString() } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt index 015cfce079..26aa0c81b7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTempTarget.kt @@ -5,7 +5,6 @@ import com.google.common.base.Optional import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.general.automation.elements.Comparator import info.nightscout.androidaps.plugins.general.automation.elements.ComparatorExists import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt index 4726eb5e95..6641286484 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTime.kt @@ -12,8 +12,11 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T import org.json.JSONObject +import javax.inject.Inject class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { + @Inject lateinit var dateUtil: DateUtil + var time = InputDateTime(injector) constructor(injector: HasAndroidInjector, runAt: Long) : this(injector) { @@ -57,7 +60,7 @@ class TriggerTime(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.time override fun friendlyDescription(): String = - resourceHelper.gs(R.string.atspecifiedtime, DateUtil.dateAndTimeString(time.value)) + resourceHelper.gs(R.string.atspecifiedtime, dateUtil.dateAndTimeString(time.value)) override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt index 2c565fa733..08f54025bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerTimeRange.kt @@ -12,12 +12,14 @@ import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabe import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper.safeGetInt import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.T import org.json.JSONObject +import javax.inject.Inject // Trigger for time range ( from 10:00AM till 13:00PM ) class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { + @Inject lateinit var dateUtil: DateUtil + // in minutes since midnight 60 means 1AM var range = InputTimeRange(injector) @@ -31,7 +33,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { range.end = triggerTimeRange.range.end } - fun period(start: Int, end:Int) : TriggerTimeRange { + fun period(start: Int, end: Int): TriggerTimeRange { this.range.start = start this.range.end = end return this @@ -70,7 +72,7 @@ class TriggerTimeRange(injector: HasAndroidInjector) : Trigger(injector) { override fun friendlyName(): Int = R.string.time_range override fun friendlyDescription(): String = - resourceHelper.gs(R.string.timerange_value, DateUtil.timeString(toMills(range.start)), DateUtil.timeString(toMills(range.end))) + resourceHelper.gs(R.string.timerange_value, dateUtil.timeString(toMills(range.start)), dateUtil.timeString(toMills(range.end))) override fun icon(): Optional = Optional.of(R.drawable.ic_access_alarm_24dp) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt index cef73c1339..71839a8fae 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerWifiSsid.kt @@ -10,7 +10,6 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputStrin import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel -import info.nightscout.androidaps.receivers.NetworkChangeReceiver import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.JsonHelper import org.json.JSONObject @@ -48,7 +47,7 @@ class TriggerWifiSsid(injector: HasAndroidInjector) : Trigger(injector) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } - if (eventNetworkChange.wifiConnected && comparator.value.check(eventNetworkChange.connectedSsid(), ssid.value)) { + if (eventNetworkChange.wifiConnected && comparator.value.check(eventNetworkChange.ssid, ssid.value)) { aapsLogger.debug(LTag.AUTOMATION, "Ready for execution: " + friendlyDescription()) return true } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt deleted file mode 100644 index 4007e43b45..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalFragment.kt +++ /dev/null @@ -1,134 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal - -import android.os.Bundle -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import dagger.android.support.DaggerFragment -import info.nightscout.androidaps.R -import info.nightscout.androidaps.events.EventCareportalEventChange -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.general.careportal.Dialogs.NewNSTreatmentDialog -import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler -import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper -import io.reactivex.android.schedulers.AndroidSchedulers -import io.reactivex.disposables.CompositeDisposable -import kotlinx.android.synthetic.main.careportal_fragment.* -import kotlinx.android.synthetic.main.careportal_stats_fragment.* -import javax.inject.Inject - -class CareportalFragment : DaggerFragment(), View.OnClickListener { - @Inject lateinit var resourceHelper: ResourceHelper - @Inject lateinit var rxBus: RxBusWrapper - @Inject lateinit var statusLightHandler: StatusLightHandler - @Inject lateinit var fabricPrivacy: FabricPrivacy - @Inject lateinit var activePlugin: ActivePluginProvider - - private val disposable = CompositeDisposable() - - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { - return inflater.inflate(R.layout.careportal_fragment, container, false) - } - - override fun onViewCreated(view: View, savedInstanceState: Bundle?) { - super.onViewCreated(view, savedInstanceState) - careportal_bgcheck.setOnClickListener(this) - careportal_announcement.setOnClickListener(this) - careportal_cgmsensorinsert.setOnClickListener(this) - careportal_cgmsensorstart.setOnClickListener(this) - careportal_combobolus.setOnClickListener(this) - careportal_correctionbolus.setOnClickListener(this) - careportal_carbscorrection.setOnClickListener(this) - careportal_exercise.setOnClickListener(this) - careportal_insulincartridgechange.setOnClickListener(this) - careportal_pumpbatterychange.setOnClickListener(this) - careportal_mealbolus.setOnClickListener(this) - careportal_note.setOnClickListener(this) - careportal_profileswitch.setOnClickListener(this) - careportal_pumpsitechange.setOnClickListener(this) - careportal_question.setOnClickListener(this) - careportal_snackbolus.setOnClickListener(this) - careportal_tempbasalend.setOnClickListener(this) - careportal_tempbasalstart.setOnClickListener(this) - careportal_openapsoffline.setOnClickListener(this) - careportal_temporarytarget.setOnClickListener(this) - - val profileStore = activePlugin.activeProfileInterface.profile - if (profileStore == null) { - profileview_noprofile.visibility = View.VISIBLE - careportal_buttons.visibility = View.GONE - } else { - profileview_noprofile.visibility = View.GONE - careportal_buttons.visibility = View.VISIBLE - } - } - - @Synchronized override fun onResume() { - super.onResume() - disposable.add(rxBus - .toObservable(EventCareportalEventChange::class.java) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe({ updateGUI() }) { fabricPrivacy.logException(it) } - ) - updateGUI() - } - - @Synchronized override fun onPause() { - super.onPause() - disposable.clear() - } - - override fun onClick(view: View) { - val BGCHECK = OptionsToShow(R.id.careportal_bgcheck, R.string.careportal_bgcheck).date().bg() - val SNACKBOLUS = OptionsToShow(R.id.careportal_snackbolus, R.string.careportal_snackbolus).date().bg().insulin().carbs().prebolus() - val MEALBOLUS = OptionsToShow(R.id.careportal_mealbolus, R.string.careportal_mealbolus).date().bg().insulin().carbs().prebolus() - val CORRECTIONBOLUS = OptionsToShow(R.id.careportal_correctionbolus, R.string.careportal_correctionbolus).date().bg().insulin().carbs().prebolus() - val CARBCORRECTION = OptionsToShow(R.id.careportal_carbscorrection, R.string.careportal_carbscorrection).date().bg().carbs() - val COMBOBOLUS = OptionsToShow(R.id.careportal_combobolus, R.string.careportal_combobolus).date().bg().insulin().carbs().prebolus().duration().split() - val ANNOUNCEMENT = OptionsToShow(R.id.careportal_announcement, R.string.careportal_announcement).date().bg() - val NOTE = OptionsToShow(R.id.careportal_note, R.string.careportal_note).date().bg().duration() - val QUESTION = OptionsToShow(R.id.careportal_question, R.string.careportal_question).date().bg() - val EXERCISE = OptionsToShow(R.id.careportal_exercise, R.string.careportal_exercise).date().duration() - val SITECHANGE = OptionsToShow(R.id.careportal_pumpsitechange, R.string.careportal_pumpsitechange).date().bg() - val SENSORSTART = OptionsToShow(R.id.careportal_cgmsensorstart, R.string.careportal_cgmsensorstart).date().bg() - val SENSORCHANGE = OptionsToShow(R.id.careportal_cgmsensorinsert, R.string.careportal_cgmsensorinsert).date().bg() - val INSULINCHANGE = OptionsToShow(R.id.careportal_insulincartridgechange, R.string.careportal_insulincartridgechange).date().bg() - val PUMPBATTERYCHANGE = OptionsToShow(R.id.careportal_pumpbatterychange, R.string.careportal_pumpbatterychange).date().bg() - val TEMPBASALSTART = OptionsToShow(R.id.careportal_tempbasalstart, R.string.careportal_tempbasalstart).date().bg().duration().percent().absolute() - val TEMPBASALEND = OptionsToShow(R.id.careportal_tempbasalend, R.string.careportal_tempbasalend).date().bg() - val PROFILESWITCH = OptionsToShow(R.id.careportal_profileswitch, R.string.careportal_profileswitch).date().duration().profile() - val OPENAPSOFFLINE = OptionsToShow(R.id.careportal_openapsoffline, R.string.careportal_openapsoffline).date().duration() - val TEMPTARGET = OptionsToShow(R.id.careportal_temporarytarget, R.string.careportal_temporarytarget).date().duration().tempTarget() - - val newDialog = NewNSTreatmentDialog() - when (view.id) { - R.id.careportal_bgcheck -> newDialog.setOptions(BGCHECK, R.string.careportal_bgcheck) - R.id.careportal_announcement -> newDialog.setOptions(ANNOUNCEMENT, R.string.careportal_announcement) - R.id.careportal_cgmsensorinsert -> newDialog.setOptions(SENSORCHANGE, R.string.careportal_cgmsensorinsert) - R.id.careportal_cgmsensorstart -> newDialog.setOptions(SENSORSTART, R.string.careportal_cgmsensorstart) - R.id.careportal_combobolus -> newDialog.setOptions(COMBOBOLUS, R.string.careportal_combobolus) - R.id.careportal_correctionbolus -> newDialog.setOptions(CORRECTIONBOLUS, R.string.careportal_correctionbolus) - R.id.careportal_carbscorrection -> newDialog.setOptions(CARBCORRECTION, R.string.careportal_carbscorrection) - R.id.careportal_exercise -> newDialog.setOptions(EXERCISE, R.string.careportal_exercise) - R.id.careportal_insulincartridgechange -> newDialog.setOptions(INSULINCHANGE, R.string.careportal_insulincartridgechange) - R.id.careportal_pumpbatterychange -> newDialog.setOptions(PUMPBATTERYCHANGE, R.string.careportal_pumpbatterychange) - R.id.careportal_mealbolus -> newDialog.setOptions(MEALBOLUS, R.string.careportal_mealbolus) - R.id.careportal_note -> newDialog.setOptions(NOTE, R.string.careportal_note) - R.id.careportal_profileswitch -> newDialog.setOptions(PROFILESWITCH, R.string.careportal_profileswitch) - R.id.careportal_pumpsitechange -> newDialog.setOptions(SITECHANGE, R.string.careportal_pumpsitechange) - R.id.careportal_question -> newDialog.setOptions(QUESTION, R.string.careportal_question) - R.id.careportal_snackbolus -> newDialog.setOptions(SNACKBOLUS, R.string.careportal_snackbolus) - R.id.careportal_tempbasalstart -> newDialog.setOptions(TEMPBASALSTART, R.string.careportal_tempbasalstart) - R.id.careportal_tempbasalend -> newDialog.setOptions(TEMPBASALEND, R.string.careportal_tempbasalend) - R.id.careportal_openapsoffline -> newDialog.setOptions(OPENAPSOFFLINE, R.string.careportal_openapsoffline) - R.id.careportal_temporarytarget -> newDialog.setOptions(TEMPTARGET, R.string.careportal_temporarytarget) - } - NewNSTreatmentDialog().show(childFragmentManager, "CareportalFragment") - } - - private fun updateGUI() { - statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, null, careportal_sensorage, careportal_pbage, null) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt deleted file mode 100644 index e3328aefc9..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/CareportalPlugin.kt +++ /dev/null @@ -1,28 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.Config -import info.nightscout.androidaps.R -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.utils.resources.ResourceHelper -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class CareportalPlugin @Inject constructor( - injector: HasAndroidInjector, - aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper -) : PluginBase(PluginDescription() - .mainType(PluginType.GENERAL) - .fragmentClass(CareportalFragment::class.java.name) - .pluginName(R.string.careportal) - .shortName(R.string.careportal_shortname) - .visibleByDefault(Config.NSCLIENT) - .enableByDefault(Config.NSCLIENT) - .description(R.string.description_careportal), - aapsLogger, resourceHelper, injector -) \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java deleted file mode 100644 index 0c7dd11e83..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/Dialogs/NewNSTreatmentDialog.java +++ /dev/null @@ -1,738 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal.Dialogs; - - -import android.os.Bundle; -import android.text.Editable; -import android.text.TextWatcher; -import android.text.format.DateFormat; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.view.Window; -import android.view.WindowManager; -import android.widget.AdapterView; -import android.widget.ArrayAdapter; -import android.widget.Button; -import android.widget.EditText; -import android.widget.LinearLayout; -import android.widget.RadioButton; -import android.widget.Spinner; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.StringRes; -import androidx.fragment.app.DialogFragment; - -import com.google.common.collect.Lists; -import com.wdullaer.materialdatetimepicker.date.DatePickerDialog; -import com.wdullaer.materialdatetimepicker.time.TimePickerDialog; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; - -import javax.inject.Inject; - -import dagger.android.HasAndroidInjector; -import dagger.android.support.DaggerDialogFragment; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; -import info.nightscout.androidaps.db.BgReading; -import info.nightscout.androidaps.db.CareportalEvent; -import info.nightscout.androidaps.db.ProfileSwitch; -import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.general.careportal.OptionsToShow; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DefaultValueHelper; -import info.nightscout.androidaps.utils.HardLimits; -import info.nightscout.androidaps.utils.JsonHelper; -import info.nightscout.androidaps.utils.NumberPicker; -import info.nightscout.androidaps.utils.alertDialogs.OKDialog; -import info.nightscout.androidaps.utils.SafeParse; -import info.nightscout.androidaps.utils.Translator; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; - -public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener { - @Inject HasAndroidInjector injector; - @Inject AAPSLogger aapsLogger; - @Inject DefaultValueHelper defaultValueHelper; - @Inject ProfileFunction profileFunction; - @Inject ResourceHelper resourceHelper; - @Inject ConstraintChecker constraintChecker; - @Inject SP sp; - @Inject ActivePluginProvider activePlugin; - @Inject TreatmentsPlugin treatmentsPlugin; - @Inject HardLimits hardLimits; - @Inject Translator translator; - - private static OptionsToShow options; - private static @StringRes int event; - - private Profile profile; - public ProfileStore profileStore; - - TextView eventTypeText; - LinearLayout layoutPercent; - LinearLayout layoutAbsolute; - LinearLayout layoutReuse; - - - TextView dateButton; - TextView timeButton; - - TextView bgUnitsView; - RadioButton meterRadioButton; - RadioButton sensorRadioButton; - RadioButton otherRadioButton; - EditText notesEdit; - Spinner profileSpinner; - Spinner reasonSpinner; - Button reuseButton; - - NumberPicker editBg; - NumberPicker editCarbs; - NumberPicker editInsulin; - NumberPicker editSplit; - NumberPicker editDuration; - NumberPicker editPercent; - NumberPicker editAbsolute; - NumberPicker editCarbTime; - NumberPicker editTemptarget; - NumberPicker editPercentage; - NumberPicker editTimeshift; - - Date eventTime; - - private static Integer seconds = null; - - public NewNSTreatmentDialog setOptions(OptionsToShow options, int event) { - this.options = options; - this.event = event; - return this; - } - - public NewNSTreatmentDialog() { - super(); - - if (seconds == null) { - seconds = Double.valueOf(Math.random() * 59).intValue(); - } - } - - @Override - public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - if (options == null) return null; - getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); - getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); - setCancelable(true); - getDialog().setCanceledOnTouchOutside(false); - setStyle(DialogFragment.STYLE_NORMAL, getTheme()); - View view = inflater.inflate(R.layout.careportal_newnstreatment_dialog, container, false); - - layoutPercent = view.findViewById(R.id.careportal_newnstreatment_percent_layout); - layoutAbsolute = view.findViewById(R.id.careportal_newnstreatment_absolute_layout); - - layoutReuse = view.findViewById(R.id.careportal_newnstreatment_reuse_layout); - - eventTypeText = view.findViewById(R.id.careportal_newnstreatment_eventtype); - eventTypeText.setText(event); - bgUnitsView = view.findViewById(R.id.careportal_newnstreatment_bgunits); - meterRadioButton = view.findViewById(R.id.careportal_newnstreatment_meter); - sensorRadioButton = view.findViewById(R.id.careportal_newnstreatment_sensor); - otherRadioButton = view.findViewById(R.id.careportal_newnstreatment_other); - profileSpinner = view.findViewById(R.id.careportal_newnstreatment_profile); - - reuseButton = view.findViewById(R.id.careportal_newnstreatment_reusebutton); - - notesEdit = view.findViewById(R.id.careportal_newnstreatment_notes); - - reasonSpinner = view.findViewById(R.id.careportal_newnstreatment_temptarget_reason); - - eventTime = new Date(); - dateButton = view.findViewById(R.id.careportal_newnstreatment_eventdate); - timeButton = view.findViewById(R.id.careportal_newnstreatment_eventtime); - dateButton.setText(DateUtil.dateString(eventTime)); - timeButton.setText(DateUtil.timeString(eventTime)); - dateButton.setOnClickListener(this); - timeButton.setOnClickListener(this); - - view.findViewById(R.id.ok).setOnClickListener(this); - view.findViewById(R.id.cancel).setOnClickListener(this); - - // profile - profile = profileFunction.getProfile(); - profileStore = activePlugin.getActiveProfileInterface().getProfile(); - if (profileStore == null) { - if (options.eventType == R.id.careportal_profileswitch) { - aapsLogger.error("Profile switch called but plugin doesn't contain valid profile"); - } - } else { - ArrayList profileList; - profileList = profileStore.getProfileList(); - ArrayAdapter adapter = new ArrayAdapter<>(getContext(), - R.layout.spinner_centered, profileList); - profileSpinner.setAdapter(adapter); - // set selected to actual profile - for (int p = 0; p < profileList.size(); p++) { - if (profileList.get(p).equals(profileFunction.getProfileName(false))) - profileSpinner.setSelection(p); - } - } - final Double bg = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); - - // temp target - final List reasonList = Lists.newArrayList( - resourceHelper.gs(R.string.manual), - resourceHelper.gs(R.string.eatingsoon), - resourceHelper.gs(R.string.activity), - resourceHelper.gs(R.string.hypo)); - ArrayAdapter adapterReason = new ArrayAdapter<>(getContext(), - R.layout.spinner_centered, reasonList); - reasonSpinner.setAdapter(adapterReason); - reasonSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { - @Override - public void onItemSelected(AdapterView parent, View view, int position, long id) { - double defaultDuration; - double defaultTarget; - if (profile != null && editTemptarget.getValue().equals(bg)) { - defaultTarget = bg; - } else { - //prevent changes on screen rotate - defaultTarget = editTemptarget.getValue(); - } - boolean erase = false; - - if (resourceHelper.gs(R.string.eatingsoon).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineEatingSoonTTDuration(); - defaultTarget = defaultValueHelper.determineEatingSoonTT(); - } else if (resourceHelper.gs(R.string.activity).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineActivityTTDuration(); - defaultTarget = defaultValueHelper.determineActivityTT(); - } else if (resourceHelper.gs(R.string.hypo).equals(reasonList.get(position))) { - defaultDuration = defaultValueHelper.determineHypoTTDuration(); - defaultTarget = defaultValueHelper.determineHypoTT(); - } else if (editDuration.getValue() != 0) { - defaultDuration = editDuration.getValue(); - } else { - defaultDuration = 0; - erase = true; - } - - if (defaultTarget != 0 || erase) { - editTemptarget.setValue(defaultTarget); - } - if (defaultDuration != 0) { - editDuration.setValue(defaultDuration); - } else if (erase) { - editDuration.setValue(0d); - } - } - - @Override - public void onNothingSelected(AdapterView parent) { - - } - }); - - // bg - bgUnitsView.setText(profileFunction.getUnits()); - - TextWatcher bgTextWatcher = new TextWatcher() { - - public void afterTextChanged(Editable s) { - } - - public void beforeTextChanged(CharSequence s, int start, int count, int after) { - } - - public void onTextChanged(CharSequence s, int start, int before, int count) { - if (sensorRadioButton.isChecked()) meterRadioButton.setChecked(true); - } - }; - editBg = view.findViewById(R.id.careportal_newnstreatment_bginput); - editTemptarget = view.findViewById(R.id.careportal_newnstreatment_temptarget); - if (profile == null) { - editBg.setParams(bg, 0d, 500d, 0.1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok)); - } else if (profileFunction.getUnits().equals(Constants.MMOL)) { - editBg.setParams(bg, 0d, 30d, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MMOL, Constants.MIN_TT_MMOL, Constants.MAX_TT_MMOL, 0.1d, new DecimalFormat("0.0"), false, view.findViewById(R.id.ok)); - } else { - editBg.setParams(bg, 0d, 500d, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok), bgTextWatcher); - editTemptarget.setParams(Constants.MIN_TT_MGDL, Constants.MIN_TT_MGDL, Constants.MAX_TT_MGDL, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - } - - sensorRadioButton.setOnCheckedChangeListener((buttonView, isChecked) -> { - double bg1 = Profile.fromMgdlToUnits(new GlucoseStatus(injector).getGlucoseStatusData() != null ? new GlucoseStatus(injector).getGlucoseStatusData().glucose : 0d, profileFunction.getUnits()); - if (savedInstanceState != null && savedInstanceState.getDouble("editBg") != bg1) { - editBg.setValue(savedInstanceState.getDouble("editBg")); - } else { - editBg.setValue(bg1); - } - }); - - Integer maxCarbs = constraintChecker.getMaxCarbsAllowed().value(); - editCarbs = view.findViewById(R.id.careportal_newnstreatment_carbsinput); - editCarbs.setParams(0d, 0d, (double) maxCarbs, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - Double maxInsulin = constraintChecker.getMaxBolusAllowed().value(); - editInsulin = view.findViewById(R.id.careportal_newnstreatment_insulininput); - editInsulin.setParams(0d, 0d, maxInsulin, 0.05d, new DecimalFormat("0.00"), false, view.findViewById(R.id.ok)); - - editSplit = view.findViewById(R.id.careportal_newnstreatment_splitinput); - editSplit.setParams(100d, 0d, 100d, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok)); - editDuration = view.findViewById(R.id.careportal_newnstreatment_durationinput); - editDuration.setParams(0d, 0d, Constants.MAX_PROFILE_SWITCH_DURATION, 10d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - TextWatcher percentTextWatcher = new TextWatcher() { - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - layoutPercent.setVisibility(View.VISIBLE); - layoutAbsolute.setVisibility(View.GONE); - } - }; - - Integer maxPercent = 200; - if (profile != null) - maxPercent = constraintChecker.getMaxBasalPercentAllowed(profile).value(); - editPercent = view.findViewById(R.id.careportal_newnstreatment_percentinput); - editPercent.setParams(0d, -100d, (double) maxPercent, 5d, new DecimalFormat("0"), true, view.findViewById(R.id.ok), percentTextWatcher); - - TextWatcher absoluteTextWatcher = new TextWatcher() { - @Override - public void afterTextChanged(Editable s) { - } - - @Override - public void beforeTextChanged(CharSequence s, int start, - int count, int after) { - } - - @Override - public void onTextChanged(CharSequence s, int start, - int before, int count) { - layoutPercent.setVisibility(View.GONE); - layoutAbsolute.setVisibility(View.VISIBLE); - } - }; - - Double maxAbsolute = hardLimits.maxBasal(); - if (profile != null) - maxAbsolute = constraintChecker.getMaxBasalAllowed(profile).value(); - editAbsolute = view.findViewById(R.id.careportal_newnstreatment_absoluteinput); - editAbsolute.setParams(0d, 0d, maxAbsolute, 0.05d, new DecimalFormat("0.00"), true, view.findViewById(R.id.ok), absoluteTextWatcher); - - editCarbTime = view.findViewById(R.id.careportal_newnstreatment_carbtimeinput); - editCarbTime.setParams(0d, -60d, 60d, 5d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - editPercentage = view.findViewById(R.id.careportal_newnstreatment_percentage); - editPercentage.setParams(100d, (double) Constants.CPP_MIN_PERCENTAGE, (double) Constants.CPP_MAX_PERCENTAGE, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - editTimeshift = view.findViewById(R.id.careportal_newnstreatment_timeshift); - editTimeshift.setParams(0d, (double) Constants.CPP_MIN_TIMESHIFT, (double) Constants.CPP_MAX_TIMESHIFT, 1d, new DecimalFormat("0"), false, view.findViewById(R.id.ok)); - - ProfileSwitch ps = treatmentsPlugin.getProfileSwitchFromHistory(DateUtil.now()); - if (ps != null && ps.isCPP) { - final int percentage = ps.percentage; - final int timeshift = ps.timeshift; - reuseButton.setText(reuseButton.getText() + " " + percentage + "% " + timeshift + "h"); - reuseButton.setOnClickListener(v -> { - editPercentage.setValue((double) percentage); - editTimeshift.setValue((double) timeshift); - }); - } - if (ps == null) { - options.duration = false; - } - - showOrHide(view.findViewById(R.id.careportal_newnstreatment_eventtime_layout), options.date); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_bg_layout), options.bg); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_bgsource_layout), options.bg); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_insulin_layout), options.insulin); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbs_layout), options.carbs); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_split_layout), options.split); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_duration_layout), options.duration); - showOrHide(layoutPercent, options.percent); - showOrHide(layoutAbsolute, options.absolute); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_carbtime_layout), options.prebolus); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_profile_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_percentage_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_timeshift_layout), options.profile); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_reuse_layout), options.profile && ps != null && ps.isCPP); - showOrHide(view.findViewById(R.id.careportal_newnstreatment_temptarget_layout), options.tempTarget); - - setCancelable(true); - getDialog().setCanceledOnTouchOutside(false); - //recovering state if there is something - // only numberPickers and editTexts - if (savedInstanceState != null) { - editBg.setValue(savedInstanceState.getDouble("editBg")); - editTemptarget.setValue(savedInstanceState.getDouble("editTemptarget")); - notesEdit.setText(savedInstanceState.getString("notesEdit")); - editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); - editCarbs.setValue(savedInstanceState.getDouble("editCarbs")); - editInsulin.setValue(savedInstanceState.getDouble("editInsulin")); - editDuration.setValue(savedInstanceState.getDouble("editDuration")); - editPercent.setValue(savedInstanceState.getDouble("editPercent")); - editAbsolute.setValue(savedInstanceState.getDouble("editAbsolute")); - editCarbTime.setValue(savedInstanceState.getDouble("editCarbTime")); - editPercentage.setValue(savedInstanceState.getDouble("editPercentage")); - editTimeshift.setValue(savedInstanceState.getDouble("editTimeshift")); - // time and date - dateButton.setText(savedInstanceState.getString("dateButton")); - timeButton.setText(savedInstanceState.getString("timeButton")); - } - return view; - } - - @Override - public void onResume() { - super.onResume(); - getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); - - } - - @Override - public void onClick(View view) { - Calendar calendar = Calendar.getInstance(); - calendar.setTime(eventTime); - switch (view.getId()) { - case R.id.careportal_newnstreatment_eventdate: - DatePickerDialog dpd = DatePickerDialog.newInstance( - this, - calendar.get(Calendar.YEAR), - calendar.get(Calendar.MONTH), - calendar.get(Calendar.DAY_OF_MONTH) - ); - dpd.setThemeDark(true); - dpd.dismissOnPause(true); - dpd.show(getActivity().getSupportFragmentManager(), "Datepickerdialog"); - break; - case R.id.careportal_newnstreatment_eventtime: - TimePickerDialog tpd = TimePickerDialog.newInstance( - this, - calendar.get(Calendar.HOUR_OF_DAY), - calendar.get(Calendar.MINUTE), - DateFormat.is24HourFormat(getContext()) - ); - tpd.setThemeDark(true); - tpd.dismissOnPause(true); - tpd.show(getActivity().getSupportFragmentManager(), "Timepickerdialog"); - break; - case R.id.ok: - confirmNSTreatmentCreation(); - dismiss(); - break; - case R.id.cancel: - dismiss(); - break; - } - } - - private void showOrHide(ViewGroup layout, boolean visible) { - if (visible) layout.setVisibility(View.VISIBLE); - else layout.setVisibility(View.GONE); - } - - private void updateBGforDateTime() { - long millis = eventTime.getTime() - (150 * 1000L); // 2,5 * 60 * 1000 - List data = MainApp.getDbHelper().getBgreadingsDataFromTime(millis, true); - if ((data.size() > 0) && - (data.get(0).date > millis - 7 * 60 * 1000L) && - (data.get(0).date < millis + 7 * 60 * 1000L)) { - editBg.setValue(Profile.fromMgdlToUnits(data.get(0).value, profileFunction.getUnits())); - } - } - - @Override - public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) { - eventTime.setYear(year - 1900); - eventTime.setMonth(monthOfYear); - eventTime.setDate(dayOfMonth); - dateButton.setText(DateUtil.dateString(eventTime)); - updateBGforDateTime(); - } - - @Override - public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) { - eventTime.setHours(hourOfDay); - eventTime.setMinutes(minute); - eventTime.setSeconds(this.seconds++); // randomize seconds to prevent creating record of the same time, if user choose time manually - timeButton.setText(DateUtil.timeString(eventTime)); - updateBGforDateTime(); - } - - private JSONObject gatherData() { - String enteredBy = sp.getString("careportal_enteredby", ""); - JSONObject data = new JSONObject(); - try { - boolean allowZeroDuration = false; - data.put("created_at", DateUtil.toISOString(eventTime)); - switch (options.eventType) { - case R.id.careportal_bgcheck: - data.put("eventType", CareportalEvent.BGCHECK); - break; - case R.id.careportal_announcement: - data.put("eventType", CareportalEvent.ANNOUNCEMENT); - data.put("isAnnouncement", true); - break; - case R.id.careportal_cgmsensorinsert: - data.put("eventType", CareportalEvent.SENSORCHANGE); - break; - case R.id.careportal_cgmsensorstart: - data.put("eventType", "Sensor Start"); - break; - case R.id.careportal_combobolus: - data.put("splitNow", SafeParse.stringToDouble(editSplit.getText())); - data.put("splitExt", 100 - SafeParse.stringToDouble(editSplit.getText())); - data.put("eventType", CareportalEvent.COMBOBOLUS); - break; - case R.id.careportal_correctionbolus: - data.put("eventType", "Correction Bolus"); - break; - case R.id.careportal_carbscorrection: - data.put("eventType", "Carb Correction"); - break; - case R.id.careportal_exercise: - data.put("eventType", CareportalEvent.EXERCISE); - break; - case R.id.careportal_insulincartridgechange: - data.put("eventType", CareportalEvent.INSULINCHANGE); - break; - case R.id.careportal_pumpbatterychange: - data.put("eventType", CareportalEvent.PUMPBATTERYCHANGE); - break; - case R.id.careportal_mealbolus: - data.put("eventType", "Meal Bolus"); - break; - case R.id.careportal_note: - data.put("eventType", CareportalEvent.NOTE); - break; - case R.id.careportal_profileswitch: - data.put("eventType", CareportalEvent.PROFILESWITCH); - allowZeroDuration = true; - break; - case R.id.careportal_pumpsitechange: - data.put("eventType", CareportalEvent.SITECHANGE); - break; - case R.id.careportal_question: - data.put("eventType", CareportalEvent.QUESTION); - break; - case R.id.careportal_snackbolus: - data.put("eventType", "Snack Bolus"); - break; - case R.id.careportal_tempbasalstart: - data.put("eventType", CareportalEvent.TEMPBASAL); - break; - case R.id.careportal_tempbasalend: - data.put("eventType", CareportalEvent.TEMPBASAL); - break; - case R.id.careportal_openapsoffline: - data.put("eventType", CareportalEvent.OPENAPSOFFLINE); - break; - case R.id.careportal_temporarytarget: - data.put("eventType", CareportalEvent.TEMPORARYTARGET); - if (!reasonSpinner.getSelectedItem().toString().equals("")) - data.put("reason", reasonSpinner.getSelectedItem().toString()); - if (SafeParse.stringToDouble(editTemptarget.getText()) != 0d) { - data.put("targetBottom", SafeParse.stringToDouble(editTemptarget.getText())); - data.put("targetTop", SafeParse.stringToDouble(editTemptarget.getText())); - } - allowZeroDuration = true; - break; - } - if (options.bg && SafeParse.stringToDouble(editBg.getText()) != 0d) { - data.put("glucose", SafeParse.stringToDouble(editBg.getText())); - if (meterRadioButton.isChecked()) data.put("glucoseType", "Finger"); - if (sensorRadioButton.isChecked()) data.put("glucoseType", "Sensor"); - if (otherRadioButton.isChecked()) data.put("glucoseType", "Manual"); - } - if (SafeParse.stringToDouble(editCarbs.getText()) != 0d) - data.put("carbs", SafeParse.stringToDouble(editCarbs.getText())); - if (SafeParse.stringToDouble(editInsulin.getText()) != 0d) - data.put("insulin", SafeParse.stringToDouble(editInsulin.getText())); - if (allowZeroDuration || SafeParse.stringToDouble(editDuration.getText()) != 0d) - data.put("duration", SafeParse.stringToDouble(editDuration.getText())); - if (layoutPercent.getVisibility() != View.GONE) - data.put("percent", SafeParse.stringToDouble(editPercent.getText())); - if (layoutAbsolute.getVisibility() != View.GONE) - data.put("absolute", SafeParse.stringToDouble(editAbsolute.getText())); - if (options.profile && profileSpinner.getSelectedItem() != null) - data.put("profile", profileSpinner.getSelectedItem().toString()); - if (options.profile) - data.put("percentage", SafeParse.stringToInt(editPercentage.getText())); - if (options.profile) - data.put("timeshift", SafeParse.stringToInt(editTimeshift.getText())); - if (SafeParse.stringToDouble(editCarbTime.getText()) != 0d) - data.put("preBolus", SafeParse.stringToDouble(editCarbTime.getText())); - if (!notesEdit.getText().toString().equals("")) - data.put("notes", notesEdit.getText().toString()); - data.put("units", profileFunction.getUnits()); - if (!enteredBy.equals("")) data.put("enteredBy", enteredBy); - if (options.eventType == R.id.careportal_combobolus) { - Double enteredInsulin = SafeParse.stringToDouble(editInsulin.getText()); - data.put("enteredinsulin", enteredInsulin); - data.put("insulin", enteredInsulin * SafeParse.stringToDouble(editSplit.getText()) / 100); - data.put("relative", enteredInsulin * (100 - SafeParse.stringToDouble(editSplit.getText())) / 100 / SafeParse.stringToDouble(editDuration.getText()) * 60); - } - } catch (JSONException e) { - aapsLogger.error("Unhandled exception", e); - } - return data; - } - - private String buildConfirmText(JSONObject data) { - String ret = ""; -// if (data.has("eventType")) { -// ret += resourceHelper.gs(R.string.careportal_newnstreatment_eventtype); -// ret += ": "; -// ret += Translator.translate(JsonHelper.safeGetString(data, "eventType", "")); -// ret += "\n"; -// } - if (data.has("glucose")) { - ret += resourceHelper.gs(R.string.treatments_wizard_bg_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "glucose", ""); - ret += " " + profileFunction.getUnits() + "\n"; - } - if (data.has("glucoseType")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_glucosetype); - ret += ": "; - ret += translator.translate(JsonHelper.safeGetString(data, "glucoseType", "")); - ret += "\n"; - } - if (data.has("carbs")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbs_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "carbs", ""); - ret += " g\n"; - } - if (data.has("insulin")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_insulin_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "insulin", ""); - ret += " U\n"; - } - if (data.has("duration")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_duration_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "duration", ""); - ret += " min\n"; - } - if (data.has("percent")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_percent_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "percent", ""); - ret += " %\n"; - } - if (data.has("absolute")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_absolute_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "absolute", ""); - ret += " U/h\n"; - } - if (data.has("preBolus")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_carbtime_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "preBolus", ""); - ret += " min\n"; - } - if (data.has("notes")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_notes_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "notes", ""); - ret += "\n"; - } - if (data.has("profile")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_profile_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "profile", ""); - ret += "\n"; - } - if (data.has("percentage")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_percentage_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "percentage", ""); - ret += " %\n"; - } - if (data.has("timeshift")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_timeshift_label); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "timeshift", ""); - ret += " h\n"; - } - if (data.has("targetBottom") && data.has("targetTop")) { - ret += resourceHelper.gs(R.string.target_range); - ret += " "; - ret += JsonHelper.safeGetObject(data, "targetBottom", ""); - ret += " - "; - ret += JsonHelper.safeGetObject(data, "targetTop", ""); - ret += "\n"; - } - if (data.has("created_at")) { - ret += resourceHelper.gs(R.string.event_time_label); - ret += ": "; - ret += DateUtil.dateAndTimeString(eventTime); - ret += "\n"; - } - if (data.has("enteredBy")) { - ret += resourceHelper.gs(R.string.careportal_newnstreatment_enteredby_title); - ret += ": "; - ret += JsonHelper.safeGetObject(data, "enteredBy", ""); - ret += "\n"; - } - - return ret; - } - - private void confirmNSTreatmentCreation() { - final JSONObject data = gatherData(); - OKDialog.showConfirmation(getContext(), translator.translate(JsonHelper.safeGetString(data, "eventType", resourceHelper.gs(R.string.overview_treatment_label))), buildConfirmText(data), () -> NSUpload.createNSTreatment(data, profileStore, profileFunction, eventTime.getTime())); - } - - - @Override - public void onSaveInstanceState(Bundle savedInstanceState) { - savedInstanceState.putString("notesEdit", notesEdit.getText().toString()); - savedInstanceState.putString("dateButton", dateButton.getText().toString()); - savedInstanceState.putString("timeButton", timeButton.getText().toString()); - savedInstanceState.putDouble("editBg", editBg.getValue()); - savedInstanceState.putDouble("editCarbs", editCarbs.getValue()); - savedInstanceState.putDouble("editInsulin", editInsulin.getValue()); - savedInstanceState.putDouble("editDuration", editDuration.getValue()); - savedInstanceState.putDouble("editPercent", editPercent.getValue()); - savedInstanceState.putDouble("editAbsolute", editAbsolute.getValue()); - savedInstanceState.putDouble("editCarbTime", editCarbTime.getValue()); - savedInstanceState.putDouble("editTemptarget", editTemptarget.getValue()); - savedInstanceState.putDouble("editPercentage", editPercentage.getValue()); - savedInstanceState.putDouble("editTimeshift", editTimeshift.getValue()); - super.onSaveInstanceState(savedInstanceState); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java deleted file mode 100644 index e1effcd561..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/careportal/OptionsToShow.java +++ /dev/null @@ -1,81 +0,0 @@ -package info.nightscout.androidaps.plugins.general.careportal; - -/** - * Created by mike on 05.11.2016. - */ - -public class OptionsToShow { - public int eventType; - public int eventName; - public boolean date; - public boolean bg; - public boolean insulin; - public boolean carbs; - public boolean prebolus; - public boolean duration; - public boolean percent; - public boolean absolute; - public boolean profile; - public boolean split; - public boolean tempTarget; - - public OptionsToShow(int eventType, int eventName) { - this.eventType = eventType; - this.eventName = eventName; - } - - public OptionsToShow date() { - date = true; - return this; - } - - public OptionsToShow bg() { - bg = true; - return this; - } - - public OptionsToShow insulin() { - insulin = true; - return this; - } - - public OptionsToShow carbs() { - carbs = true; - return this; - } - - public OptionsToShow prebolus() { - prebolus = true; - return this; - } - - public OptionsToShow duration() { - duration = true; - return this; - } - - public OptionsToShow percent() { - percent = true; - return this; - } - - public OptionsToShow absolute() { - absolute = true; - return this; - } - - public OptionsToShow profile() { - profile = true; - return this; - } - - public OptionsToShow split() { - split = true; - return this; - } - - public OptionsToShow tempTarget() { - tempTarget = true; - return this; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt index 63a32edc41..28d2b378b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/dataBroadcaster/DataBroadcastPlugin.kt @@ -14,16 +14,12 @@ import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.events.EventNewBasalProfile import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.events.EventTreatmentChange -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui +import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus @@ -53,8 +49,9 @@ class DataBroadcastPlugin @Inject constructor( private val nsDeviceStatus: NSDeviceStatus, private val loopPlugin: LoopPlugin, private val activePlugin: ActivePluginProvider, - private var receiverStatusStore: ReceiverStatusStore - + private var receiverStatusStore: ReceiverStatusStore, + private val config: Config, + private val databaseHelper: DatabaseHelperInterface ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) @@ -131,7 +128,7 @@ class DataBroadcastPlugin @Inject constructor( bundle.putDouble("glucoseMgdl", lastBG.value) // last BG in mgdl bundle.putLong("glucoseTimeStamp", lastBG.date) // timestamp bundle.putString("units", profileFunction.getUnits()) // units used in AAPS "mg/dl" or "mmol" - bundle.putString("slopeArrow", lastBG.directionToSymbol()) // direction arrow as string + bundle.putString("slopeArrow", lastBG.directionToSymbol(databaseHelper)) // direction arrow as string bundle.putDouble("deltaMgdl", glucoseStatus.delta) // bg delta in mgdl bundle.putDouble("avgDeltaMgdl", glucoseStatus.avgdelta) // average bg delta bundle.putDouble("high", defaultValueHelper.determineHighLine()) // predefined top value of in range (green area) @@ -158,7 +155,7 @@ class DataBroadcastPlugin @Inject constructor( bundle.putInt("phoneBattery", receiverStatusStore.batteryLevel) bundle.putInt("rigBattery", nsDeviceStatus.uploaderStatus.replace("%", "").trim { it <= ' ' }.toInt()) - if (Config.APS && loopPlugin.lastRun?.lastTBREnact != 0L) { //we are AndroidAPS + if (config.APS && loopPlugin.lastRun?.lastTBREnact != 0L) { //we are AndroidAPS bundle.putLong("suggestedTimeStamp", loopPlugin.lastRun?.lastAPSRun ?: -1L) bundle.putString("suggested", loopPlugin.lastRun?.request?.json().toString()) if (loopPlugin.lastRun?.tbrSetByPump != null && loopPlugin.lastRun?.tbrSetByPump?.enacted == true) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt index fc8989d36d..c7c7a7689d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt @@ -35,6 +35,7 @@ class FoodFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var foodPlugin: FoodPlugin + @Inject lateinit var nsUpload: NSUpload private val disposable = CompositeDisposable() private lateinit var unfiltered: List @@ -200,7 +201,7 @@ class FoodFragment : DaggerFragment() { activity?.let { activity -> showConfirmation(activity, resourceHelper.gs(R.string.confirmation), resourceHelper.gs(R.string.removerecord) + "\n" + food.name, DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> if (food._id != null && food._id != "") { - NSUpload.removeFoodFromNS(food._id) + nsUpload.removeFoodFromNS(food._id) } foodPlugin.service?.delete(food) }, null) @@ -210,4 +211,4 @@ class FoodFragment : DaggerFragment() { } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index 9c41df2666..3482a9b11a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -28,6 +28,6 @@ class FoodPlugin @Inject constructor( override fun onStart() { super.onStart() - service = FoodService() + service = FoodService(injector) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java index 405fc22b50..8b69403960 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java @@ -15,7 +15,6 @@ import com.j256.ormlite.table.TableUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; import java.util.ArrayList; @@ -25,15 +24,17 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventFoodDatabaseChanged; import info.nightscout.androidaps.events.EventNsFood; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.utils.FabricPrivacy; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; @@ -43,16 +44,20 @@ import io.reactivex.schedulers.Schedulers; */ public class FoodService extends OrmLiteBaseService { - private Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATAFOOD); + @Inject AAPSLogger aapsLogger; + @Inject RxBusWrapper rxBus; + @Inject FabricPrivacy fabricPrivacy; + private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); private static ScheduledFuture scheduledFoodEventPost = null; - public FoodService() { + public FoodService(HasAndroidInjector injector) { + injector.androidInjector().inject(this); onCreate(); dbInitialize(); - disposable.add(RxBus.Companion.getINSTANCE() + disposable.add(rxBus .toObservable(EventNsFood.class) .observeOn(Schedulers.io()) .subscribe(event -> { @@ -62,7 +67,7 @@ public class FoodService extends OrmLiteBaseService { this.createFoodFromJsonIfNotExists(array); else this.deleteNS(array); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); } @@ -88,7 +93,7 @@ public class FoodService extends OrmLiteBaseService { try { return DaoManager.createDao(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Cannot create Dao for Food.class"); + aapsLogger.error("Cannot create Dao for Food.class"); } return null; @@ -98,18 +103,16 @@ public class FoodService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - if (L.isEnabled(LTag.DATAFOOD)) - log.info("onCreate"); + aapsLogger.info(LTag.DATAFOOD, "onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Can't create database", e); + aapsLogger.error("Can't create database", e); throw new RuntimeException(e); } } public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { - if (L.isEnabled(LTag.DATAFOOD)) - log.info("onUpgrade"); + aapsLogger.info(LTag.DATAFOOD, "onUpgrade"); // this.resetFood(); } @@ -122,7 +125,7 @@ public class FoodService extends OrmLiteBaseService { TableUtils.dropTable(this.getConnectionSource(), Food.class, true); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } scheduleFoodChange(); } @@ -147,9 +150,8 @@ public class FoodService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Firing EventFoodChange"); - RxBus.Companion.getINSTANCE().send(event); + aapsLogger.debug(LTag.DATAFOOD, "Firing EventFoodChange"); + rxBus.send(event); callback.setPost(null); } } @@ -183,7 +185,7 @@ public class FoodService extends OrmLiteBaseService { try { return this.getDao().queryForAll(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return new ArrayList<>(); @@ -208,7 +210,7 @@ public class FoodService extends OrmLiteBaseService { Food food = Food.createFromJson(json); this.createFoodFromJsonIfNotExists(food); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -220,7 +222,7 @@ public class FoodService extends OrmLiteBaseService { this.createFoodFromJsonIfNotExists(food); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -233,7 +235,7 @@ public class FoodService extends OrmLiteBaseService { String _id = json.getString("_id"); this.deleteByNSId(_id); } catch (JSONException | SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -244,7 +246,7 @@ public class FoodService extends OrmLiteBaseService { this.deleteNS(json); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -258,8 +260,7 @@ public class FoodService extends OrmLiteBaseService { public void deleteByNSId(String _id) throws SQLException { Food stored = this.findByNSId(_id); if (stored != null) { - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Removing Food record from database: " + stored.toString()); + aapsLogger.debug(LTag.DATAFOOD, "Removing Food record from database: " + stored.toString()); this.delete(stored); } } @@ -276,7 +277,7 @@ public class FoodService extends OrmLiteBaseService { this.getDao().delete(food); this.scheduleFoodChange(); } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -312,10 +313,9 @@ public class FoodService extends OrmLiteBaseService { public void createOrUpdate(Food food) { try { this.getDao().createOrUpdate(food); - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("Created or Updated: " + food.toString()); + aapsLogger.debug(LTag.DATAFOOD, "Created or Updated: " + food.toString()); } catch (SQLException e) { - log.error("Unable to createOrUpdate Food", e); + aapsLogger.error("Unable to createOrUpdate Food", e); } this.scheduleFoodChange(); } @@ -323,10 +323,9 @@ public class FoodService extends OrmLiteBaseService { public void create(Food food) { try { this.getDao().create(food); - if (L.isEnabled(LTag.DATAFOOD)) - log.debug("New record: " + food.toString()); + aapsLogger.debug(LTag.DATAFOOD, "New record: " + food.toString()); } catch (SQLException e) { - log.error("Unable to create Food", e); + aapsLogger.error("Unable to create Food", e); } this.scheduleFoodChange(); } @@ -346,7 +345,7 @@ public class FoodService extends OrmLiteBaseService { return list.get(0); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return null; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt index 4d9021bb71..d90de7a086 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefs.kt @@ -7,7 +7,6 @@ import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.provider.Settings -import androidx.activity.invoke import androidx.annotation.StringRes import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment @@ -20,7 +19,6 @@ 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.plugins.general.smsCommunicator.otp.OneTimePassword import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog @@ -211,18 +209,24 @@ class ImportExportPrefs @Inject constructor( } catch (e: IOException) { ToastUtils.errorToast(activity, e.message) log.error(TAG, "Unhandled exception", e) + } catch (e: PrefFileNotFoundError) { + ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) + + "\n\n" + resourceHelper.gs(R.string.filenotfound) + + ": " + e.message + + "\n\n" + resourceHelper.gs(R.string.needstoragepermission)) + log.error(TAG, "File system exception", e) + } catch (e: PrefIOError) { + ToastUtils.Long.errorToast(activity, resourceHelper.gs(R.string.preferences_export_canceled) + + "\n\n" + resourceHelper.gs(R.string.needstoragepermission) + + ": " + e.message) + log.error(TAG, "File system exception", e) } } } fun importSharedPreferences(fragment: Fragment) { fragment.activity?.let { fragmentAct -> - val callForPrefFile = fragmentAct.registerForActivityResult(PrefsFileContract()) { - it?.let { - importSharedPreferences(fragmentAct, it) - } - } - callForPrefFile.invoke() + importSharedPreferences(fragmentAct) } } @@ -232,7 +236,15 @@ class ImportExportPrefs @Inject constructor( importSharedPreferences(activity, it) } } - callForPrefFile.invoke() + + try { + callForPrefFile.launch(null) + } catch (e: IllegalArgumentException) { + // this exception happens on some early implementations of ActivityResult contracts + // when registered and called for the second time + ToastUtils.errorToast(activity, resourceHelper.gs(R.string.goto_main_try_again)) + log.error(TAG, "Internal android framework exception", e) + } } private fun importSharedPreferences(activity: Activity, importFile: PrefsFile) { @@ -269,7 +281,7 @@ class ImportExportPrefs @Inject constructor( restartAppAfterImport(activity) } else { // for impossible imports it should not be called - ToastUtils.errorToast(activity, "Cannot import preferences!") + ToastUtils.errorToast(activity, resourceHelper.gs(R.string.preferences_import_impossible)) } }) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt index 4a3e5e83ab..86b1e71db6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePlugin.kt @@ -18,7 +18,6 @@ import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference import java.io.* import java.util.* import java.util.zip.ZipEntry @@ -34,7 +33,8 @@ class MaintenancePlugin @Inject constructor( private val sp: SP, private val nsSettingsStatus: NSSettingsStatus, aapsLogger: AAPSLogger, - private val buildHelper: BuildHelper + private val buildHelper: BuildHelper, + private val config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(MaintenanceFragment::class.java.name) @@ -63,31 +63,31 @@ class MaintenancePlugin @Inject constructor( } //todo replace this with a call on startup of the application, specifically to remove -// unnecessary garbage from the log exports + // unnecessary garbage from the log exports fun deleteLogs() { - val logDirectory = LoggerUtils.getLogDirectory() - val logDir = File(logDirectory) - val files = logDir.listFiles { _: File?, name: String -> - (name.startsWith("AndroidAPS") - && name.endsWith(".zip")) - } - Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) } - var delFiles = listOf(*files) - val amount = sp.getInt(R.string.key_logshipper_amount, 2) - val keepIndex = amount - 1 - if (keepIndex < delFiles.size) { - delFiles = delFiles.subList(keepIndex, delFiles.size) - for (file in delFiles) { - file.delete() + LoggerUtils.getLogDirectory()?.let { logDirectory -> + val logDir = File(logDirectory) + val files = logDir.listFiles { _: File?, name: String -> + (name.startsWith("AndroidAPS") && name.endsWith(".zip")) } - } - val exportDir = File(logDirectory, "exports") - if (exportDir.exists()) { - val expFiles = exportDir.listFiles() - for (file in expFiles) { - file.delete() + Arrays.sort(files) { f1: File, f2: File -> f1.name.compareTo(f2.name) } + var delFiles = listOf(*files) + val amount = sp.getInt(R.string.key_logshipper_amount, 2) + val keepIndex = amount - 1 + if (keepIndex < delFiles.size) { + delFiles = delFiles.subList(keepIndex, delFiles.size) + for (file in delFiles) { + file.delete() + } + } + val exportDir = File(logDirectory, "exports") + if (exportDir.exists()) { + val expFiles = exportDir.listFiles() + for (file in expFiles) { + file.delete() + } + exportDir.delete() } - exportDir.delete() } } @@ -171,7 +171,7 @@ class MaintenancePlugin @Inject constructor( builder.append("you have to do it manually)" + System.lineSeparator()) builder.append("-------------------------------------------------------" + System.lineSeparator()) builder.append(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION + System.lineSeparator()) - if (Config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator()) + if (config.NSCLIENT) builder.append("NSCLIENT" + System.lineSeparator()) builder.append("Build: " + BuildConfig.BUILDVERSION + System.lineSeparator()) builder.append("Remote: " + BuildConfig.REMOTE + System.lineSeparator()) builder.append("Flavor: " + BuildConfig.FLAVOR + BuildConfig.BUILD_TYPE + System.lineSeparator()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt index 7703166d04..6be8b5e020 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.general.maintenance.PrefsFileContract import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsFormatsHandler import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsMetadataKey import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsStatus -import info.nightscout.androidaps.utils.LocaleHelper +import info.nightscout.androidaps.utils.locale.LocaleHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import kotlinx.android.synthetic.main.maintenance_importlist_activity.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt index ec88c07bec..122bfe74d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt @@ -2,10 +2,10 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.CryptoUtil -import info.nightscout.androidaps.utils.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.hexStringToByteArray +import info.nightscout.androidaps.utils.extensions.toHex import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage -import info.nightscout.androidaps.utils.toHex import org.json.JSONException import org.json.JSONObject import java.io.File @@ -55,13 +55,13 @@ class EncryptedPrefsFormat @Inject constructor( for ((metaKey, metaEntry) in prefs.metadata) { if (metaKey == PrefsMetadataKey.FILE_FORMAT) - continue; + continue if (metaKey == PrefsMetadataKey.ENCRYPTION) - continue; + continue meta.put(metaKey.key, metaEntry.value) } - container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC); + container.put(PrefsMetadataKey.FILE_FORMAT.key, if (encrypted) FORMAT_KEY_ENC else FORMAT_KEY_NOENC) container.put("metadata", meta) val security = JSONObject() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java index 89d0f65bc7..4ba13a8fb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientN import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.alertDialogs.OKDialog; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -33,6 +34,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList @Inject SP sp; @Inject ResourceHelper resourceHelper; @Inject RxBusWrapper rxBus; + @Inject UploadQueue uploadQueue; @Inject FabricPrivacy fabricPrivacy; private CompositeDisposable disposable = new CompositeDisposable(); @@ -119,13 +121,13 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList break; case R.id.nsclientinternal_clearqueue: OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.nsclientinternal), resourceHelper.gs(R.string.clearqueueconfirm), () -> { - UploadQueue.clearQueue(); + uploadQueue.clearQueue(); updateGui(); fabricPrivacy.logCustom("NSClientClearQueue"); }); break; case R.id.nsclientinternal_showqueue: - rxBus.send(new EventNSClientNewLog("QUEUE", nsClientPlugin.queue().textList())); + rxBus.send(new EventNSClientNewLog("QUEUE", uploadQueue.textList())); break; } } @@ -154,7 +156,7 @@ public class NSClientFragment extends DaggerFragment implements View.OnClickList logScrollview.fullScroll(ScrollView.FOCUS_DOWN); } urlTextView.setText(nsClientPlugin.url()); - Spanned queuetext = Html.fromHtml(resourceHelper.gs(R.string.queue) + " " + UploadQueue.size() + ""); + Spanned queuetext = HtmlHelper.INSTANCE.fromHtml(resourceHelper.gs(R.string.queue) + " " + uploadQueue.size() + ""); queueTextView.setText(queuetext); statusTextView.setText(nsClientPlugin.status); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java index 51f394860a..1764142432 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.java @@ -7,11 +7,9 @@ import android.content.ServiceConnection; import android.os.Handler; import android.os.HandlerThread; import android.os.IBinder; -import android.text.Html; import android.text.Spanned; import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceScreen; import org.jetbrains.annotations.NotNull; @@ -43,6 +41,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientS import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; import info.nightscout.androidaps.utils.FabricPrivacy; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -57,12 +56,14 @@ public class NSClientPlugin extends PluginBase { private final RxBusWrapper rxBus; private final ResourceHelper resourceHelper; private final Context context; + private final FabricPrivacy fabricPrivacy; private final SP sp; + private final Config config; public Handler handler; private final List listLog = new ArrayList<>(); - Spanned textLog = Html.fromHtml(""); + Spanned textLog = HtmlHelper.INSTANCE.fromHtml(""); public boolean paused; boolean autoscroll; @@ -80,8 +81,10 @@ public class NSClientPlugin extends PluginBase { RxBusWrapper rxBus, ResourceHelper resourceHelper, Context context, + FabricPrivacy fabricPrivacy, SP sp, - NsClientReceiverDelegate nsClientReceiverDelegate + NsClientReceiverDelegate nsClientReceiverDelegate, + Config config ) { super(new PluginDescription() .mainType(PluginType.GENERAL) @@ -97,10 +100,12 @@ public class NSClientPlugin extends PluginBase { this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.context = context; + this.fabricPrivacy = fabricPrivacy; this.sp = sp; this.nsClientReceiverDelegate = nsClientReceiverDelegate; + this.config = config; - if (Config.NSCLIENT) { + if (config.getNSCLIENT()) { getPluginDescription().alwaysEnabled(true).visibleByDefault(true); } if (handler == null) { @@ -132,17 +137,17 @@ public class NSClientPlugin extends PluginBase { .subscribe(event -> { status = event.getStatus(resourceHelper); rxBus.send(new EventNSClientUpdateGUI()); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNetworkChange.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventAppExit.class) @@ -151,7 +156,7 @@ public class NSClientPlugin extends PluginBase { if (nsClientService != null) { context.unbindService(mConnection); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientNewLog.class) @@ -159,17 +164,17 @@ public class NSClientPlugin extends PluginBase { .subscribe(event -> { addToLog(event); aapsLogger.debug(LTag.NSCLIENT, event.getAction() + " " + event.getLogText()); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventChargingState.class) .observeOn(Schedulers.io()) - .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> nsClientReceiverDelegate.onStatusEvent(event), fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientResend.class) .observeOn(Schedulers.io()) - .subscribe(event -> resend(event.getReason()), exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(event -> resend(event.getReason()), fabricPrivacy::logException) ); } @@ -184,7 +189,7 @@ public class NSClientPlugin extends PluginBase { public void preprocessPreferences(@NotNull PreferenceFragmentCompat preferenceFragment) { super.preprocessPreferences(preferenceFragment); - if (Config.NSCLIENT) { + if (config.getNSCLIENT()) { preferenceFragment.findPreference(resourceHelper.gs(R.string.key_statuslights_overview_advanced)); } } @@ -234,7 +239,7 @@ public class NSClientPlugin extends PluginBase { newTextLog.append(log.toPreparedHtml()); } } - textLog = Html.fromHtml(newTextLog.toString()); + textLog = HtmlHelper.INSTANCE.fromHtml(newTextLog.toString()); } catch (OutOfMemoryError e) { ToastUtils.showToastInUiThread(context, rxBus, "Out of memory!\nStop using this phone !!!", R.raw.error); } @@ -251,10 +256,6 @@ public class NSClientPlugin extends PluginBase { rxBus.send(new EventPreferenceChange(resourceHelper, R.string.key_nsclientinternal_paused)); } - public UploadQueue queue() { - return NSClientService.uploadQueue; - } - public String url() { return NSClientService.nsURL; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java index 3bc2bde171..d54f48d511 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.java @@ -1,5 +1,7 @@ package info.nightscout.androidaps.plugins.general.nsclient; +import java.util.Arrays; + import javax.inject.Inject; import javax.inject.Singleton; @@ -48,6 +50,7 @@ class NsClientReceiverDelegate { ev.isChanged(resourceHelper, R.string.key_ns_allowroaming) ) { receiverStatusStore.updateNetworkStatus(); + onStatusEvent(receiverStatusStore.getLastNetworkEvent()); } else if (ev.isChanged(resourceHelper, R.string.key_ns_chargingonly)) { receiverStatusStore.broadcastChargingState(); } @@ -92,14 +95,15 @@ class NsClientReceiverDelegate { boolean calculateStatus(final EventNetworkChange ev) { boolean wifiOnly = sp.getBoolean(R.string.key_ns_wifionly, false); - String allowedSSIDs = sp.getString(R.string.key_ns_wifi_ssids, ""); + String allowedSSIDstring = sp.getString(R.string.key_ns_wifi_ssids, ""); + String[] allowedSSIDs = allowedSSIDstring.split(";"); + if (allowedSSIDstring.isEmpty()) allowedSSIDs = new String[0]; boolean allowRoaming = sp.getBoolean(R.string.key_ns_allowroaming, true); boolean newAllowedState = true; if (ev.getWifiConnected()) { - if (!allowedSSIDs.trim().isEmpty() && - (!allowedSSIDs.contains(ev.connectedSsid()) && !allowedSSIDs.contains(ev.getSsid()))) { + if (allowedSSIDs.length != 0 && !Arrays.asList(allowedSSIDs).contains(ev.getSsid())) { newAllowedState = false; } } else { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java index 0786aae250..08fecd9283 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/UploadQueue.java @@ -8,70 +8,86 @@ import com.j256.ormlite.dao.CloseableIterator; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import java.sql.SQLException; -import info.nightscout.androidaps.MainApp; +import javax.inject.Inject; + import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.DbRequest; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; +import info.nightscout.androidaps.interfaces.UploadQueueInterface; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService; -import info.nightscout.androidaps.utils.SP; +import info.nightscout.androidaps.utils.sharedPreferences.SP; /** * Created by mike on 21.02.2016. */ -public class UploadQueue { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); +public class UploadQueue implements UploadQueueInterface { + private final AAPSLogger aapsLogger; + private final DatabaseHelperInterface databaseHelper; + private final Context context; + private final SP sp; + private final RxBusWrapper rxBus; - public static String status() { - return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); + @Inject + public UploadQueue( + AAPSLogger aapsLogger, + DatabaseHelperInterface databaseHelper, + Context context, + SP sp, + RxBusWrapper rxBus + ) { + this.aapsLogger = aapsLogger; + this.databaseHelper = databaseHelper; + this.context = context; + this.sp = sp; + this.rxBus = rxBus; } - public static long size() { - return MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); + public String status() { + return "QUEUE: " + databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); } - private static void startService() { + public long size() { + return databaseHelper.size(DatabaseHelper.DATABASE_DBREQUESTS); + } + + private void startService() { if (NSClientService.handler == null) { - Context context = MainApp.instance(); context.startService(new Intent(context, NSClientService.class)); SystemClock.sleep(2000); } } - public static void add(final DbRequest dbr) { - if (SP.getBoolean(R.string.key_ns_noupload, false)) return; - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Adding to queue: " + dbr.log()); + public void add(final DbRequest dbr) { + if (sp.getBoolean(R.string.key_ns_noupload, false)) return; + aapsLogger.debug(LTag.NSCLIENT, "Adding to queue: " + dbr.log()); try { - MainApp.getDbHelper().create(dbr); + databaseHelper.create(dbr); } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } - RxBus.getINSTANCE().send(new EventNSClientResend("newdata")); + rxBus.send(new EventNSClientResend("newdata")); } - static void clearQueue() { + void clearQueue() { startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("ClearQueue"); - MainApp.getDbHelper().deleteAllDbRequests(); - if (L.isEnabled(LTag.NSCLIENT)) - log.debug(status()); + aapsLogger.debug(LTag.NSCLIENT, "ClearQueue"); + databaseHelper.deleteAllDbRequests(); + aapsLogger.debug(LTag.NSCLIENT, status()); }); } } - public static void removeID(final JSONObject record) { + public void removeID(final JSONObject record) { startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { @@ -82,26 +98,24 @@ public class UploadQueue { } else { return; } - if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Removed item from UploadQueue. " + UploadQueue.status()); + if (databaseHelper.deleteDbRequest(id) == 1) { + aapsLogger.debug(LTag.NSCLIENT, "Removed item from UploadQueue. " + status()); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } }); } } - public static void removeID(final String action, final String _id) { + public void removeID(final String action, final String _id) { if (_id == null || _id.equals("")) return; startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { - MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status()); + databaseHelper.deleteDbRequestbyMongoId(action, _id); + aapsLogger.debug(LTag.NSCLIENT, "Removing " + _id + " from UploadQueue. " + status()); }); } } @@ -110,7 +124,7 @@ public class UploadQueue { String result = ""; CloseableIterator iterator; try { - iterator = MainApp.getDbHelper().getDbRequestInterator(); + iterator = databaseHelper.getDbRequestInterator(); try { while (iterator.hasNext()) { DbRequest dbr = iterator.next(); @@ -123,7 +137,7 @@ public class UploadQueue { iterator.close(); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return result; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java index 8541253f81..dbd9151938 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAddAck.java @@ -2,13 +2,11 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONArray; import org.json.JSONObject; -import org.slf4j.Logger; import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; import io.socket.client.Ack; @@ -16,16 +14,23 @@ import io.socket.client.Ack; * Created by mike on 29.12.2015. */ public class NSAddAck extends Event implements Ack { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + public String _id = null; public String nsClientID = null; public JSONObject json = null; + public NSAddAck(AAPSLogger aapsLogger, RxBusWrapper rxBus) { + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; + } + public void call(Object... args) { // Regular response try { JSONArray responsearray = (JSONArray) (args[0]); - JSONObject response = null; + JSONObject response; if (responsearray.length() > 0) { response = responsearray.getJSONObject(0); _id = response.getString("_id"); @@ -34,10 +39,10 @@ public class NSAddAck extends Event implements Ack { nsClientID = response.getString("NSCLIENT_ID"); } } - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); return; } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } // Check for not authorized try { @@ -45,15 +50,13 @@ public class NSAddAck extends Event implements Ack { if (response.has("result")) { _id = null; if (response.getString("result").contains("Not")) { - RxBus.Companion.getINSTANCE().send(new EventNSClientRestart()); + rxBus.send(new EventNSClientRestart()); return; } - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("DBACCESS " + response.getString("result")); + aapsLogger.debug(LTag.NSCLIENT, "DBACCESS " + response.getString("result")); } - return; } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java index dd6267308a..ea47305be4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSAuthAck.java @@ -3,19 +3,26 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONObject; import info.nightscout.androidaps.events.Event; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import io.socket.client.Ack; -public class NSAuthAck extends Event implements Ack{ +public class NSAuthAck extends Event implements Ack { + + private final RxBusWrapper rxBus; + public boolean read = false; public boolean write = false; public boolean write_treatment = false; - public void call(Object...args) { - JSONObject response = (JSONObject)args[0]; + public NSAuthAck(RxBusWrapper rxBus) { + this.rxBus = rxBus; + } + + public void call(Object... args) { + JSONObject response = (JSONObject) args[0]; read = response.optBoolean("read"); write = response.optBoolean("write"); write_treatment = response.optBoolean("write_treatment"); - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java index bc79bd2739..95a00279cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/acks/NSUpdateAck.java @@ -2,19 +2,20 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; import info.nightscout.androidaps.events.Event; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import io.socket.client.Ack; /** * Created by mike on 21.02.2016. */ public class NSUpdateAck extends Event implements Ack { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + public boolean result = false; public String _id; public String action; @@ -27,17 +28,19 @@ public class NSUpdateAck extends Event implements Ack { result = true; else if (response.getString("result").equals("Missing _id")) { result = true; - log.debug("Internal error: Missing _id returned on dbUpdate ack"); + aapsLogger.debug(LTag.NSCLIENT, "Internal error: Missing _id returned on dbUpdate ack"); } - RxBus.Companion.getINSTANCE().send(this); + rxBus.send(this); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } - public NSUpdateAck(String action, String _id) { + public NSUpdateAck(String action, String _id, AAPSLogger aapsLogger, RxBusWrapper rxBus) { super(); this.action = action; this._id = _id; + this.aapsLogger = aapsLogger; + this.rxBus = rxBus; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java index 8e5da2448d..757692e655 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.java @@ -20,6 +20,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.utils.DateUtil; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -158,7 +159,7 @@ public class NSDeviceStatus { public Spanned getExtendedPumpStatus() { if (deviceStatusPumpData != null && deviceStatusPumpData.extended != null) return deviceStatusPumpData.extended; - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } public Spanned getPumpStatus() { @@ -170,7 +171,7 @@ public class NSDeviceStatus { string.append(": "); if (deviceStatusPumpData == null) - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); // test warning level int level = Levels.INFO; @@ -225,7 +226,7 @@ public class NSDeviceStatus { string.append(""); // color - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } static class DeviceStatusPumpData { @@ -273,7 +274,7 @@ public class NSDeviceStatus { String value = extendedJson.getString(key); exteneded.append("").append(key).append(": ").append(value).append("
"); } - deviceStatusPumpData.extended = Html.fromHtml(exteneded.toString()); + deviceStatusPumpData.extended = HtmlHelper.INSTANCE.fromHtml(exteneded.toString()); } } catch (Exception e) { aapsLogger.error("Unhandled exception", e); @@ -330,7 +331,7 @@ public class NSDeviceStatus { // test warning level int level = Levels.INFO; long now = System.currentTimeMillis(); - if (deviceStatusOpenAPSData.clockSuggested != 0 && deviceStatusOpenAPSData.clockSuggested + sp.getInt(R.string.key_nsalarm_urgent_staledatavalue, 16) * 60 * 1000L < now) + if (deviceStatusOpenAPSData.clockSuggested != 0 && deviceStatusOpenAPSData.clockSuggested + sp.getInt(R.string.key_nsalarm_urgent_staledatavalue, 31) * 60 * 1000L < now) level = Levels.URGENT; else if (deviceStatusOpenAPSData.clockSuggested != 0 && deviceStatusOpenAPSData.clockSuggested + sp.getInt(R.string.key_nsalarm_staledatavalue, 16) * 60 * 1000L < now) level = Levels.WARN; @@ -345,7 +346,7 @@ public class NSDeviceStatus { } string.append(""); // color - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public static long getOpenApsTimestamp() { @@ -365,11 +366,11 @@ public class NSDeviceStatus { string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockEnacted)).append(" ").append(deviceStatusOpenAPSData.enacted.getString("reason")).append("
"); if (deviceStatusOpenAPSData.suggested != null) string.append("").append(DateUtil.minAgo(resourceHelper, deviceStatusOpenAPSData.clockSuggested)).append(" ").append(deviceStatusOpenAPSData.suggested.getString("reason")).append("
"); - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } // ********* Uploader data *********** @@ -441,7 +442,7 @@ public class NSDeviceStatus { string.append(minBattery); string.append("%"); - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public Spanned getExtendedUploaderStatus() { @@ -455,7 +456,7 @@ public class NSDeviceStatus { string.append("").append(device).append(": ").append(uploader.battery).append("%
"); } - return Html.fromHtml(string.toString()); + return HtmlHelper.INSTANCE.fromHtml(string.toString()); } public static APSResult getAPSResult(HasAndroidInjector injector) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt index 8319c143b1..06c853185a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSSettingsStatus.kt @@ -115,7 +115,8 @@ class NSSettingsStatus @Inject constructor( private val resourceHelper: ResourceHelper, private val rxBus: RxBusWrapper, private val defaultValueHelper: DefaultValueHelper, - private val sp: SP + private val sp: SP, + private val config: Config ) { var nightscoutVersionName = "" @@ -126,7 +127,7 @@ class NSSettingsStatus @Inject constructor( fun handleNewData(nightscoutVersionName: String, nightscoutVersionCode: Int, status: JSONObject) { this.nightscoutVersionName = nightscoutVersionName aapsLogger.debug(LTag.NSCLIENT, "Got versions: Nightscout: $nightscoutVersionName") - if (nightscoutVersionCode < Config.SUPPORTEDNSVERSION) { + if (nightscoutVersionCode < config.SUPPORTEDNSVERSION) { val notification = Notification(Notification.OLD_NS, resourceHelper.gs(R.string.unsupportednsversion), Notification.NORMAL) rxBus.send(EventNewNotification(notification)) } else { @@ -138,7 +139,7 @@ class NSSettingsStatus @Inject constructor( val targetlow = getSettingsThreshold("bgTargetBottom") if (targetHigh != null) defaultValueHelper.bgTargetHigh = targetHigh if (targetlow != null) defaultValueHelper.bgTargetLow = targetlow - copyStatusLightsNsSettings(null) + if (config.NSCLIENT) copyStatusLightsNsSettings(null) } fun getName(): String? = diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java index 9c76a6e16b..7c4d41ca86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.java @@ -19,8 +19,6 @@ import com.j256.ormlite.dao.CloseableIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.net.URISyntaxException; import java.sql.SQLException; @@ -31,21 +29,18 @@ import javax.inject.Inject; import dagger.android.DaggerService; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ProfileStore; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; import info.nightscout.androidaps.events.EventNsFood; import info.nightscout.androidaps.events.EventPreferenceChange; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; @@ -85,14 +80,17 @@ public class NSClientService extends DaggerService { @Inject AAPSLogger aapsLogger; @Inject NSSettingsStatus nsSettingsStatus; @Inject NSDeviceStatus nsDeviceStatus; - @Inject MainApp mainApp; + @Inject DatabaseHelperInterface databaseHelper; @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @Inject SP sp; + @Inject FabricPrivacy fabricPrivacy; @Inject NSClientPlugin nsClientPlugin; @Inject BuildHelper buildHelper; + @Inject Config config; + @Inject DateUtil dateUtil; + @Inject UploadQueue uploadQueue; - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); private CompositeDisposable disposable = new CompositeDisposable(); static public PowerManager.WakeLock mWakeLock; @@ -124,8 +122,6 @@ public class NSClientService extends DaggerService { private String nsAPIhashCode = ""; - public static UploadQueue uploadQueue = new UploadQueue(); - private final ArrayList reconnections = new ArrayList<>(); private int WATCHDOG_INTERVAL_MINUTES = 2; private int WATCHDOG_RECONNECT_IN = 15; @@ -143,7 +139,7 @@ public class NSClientService extends DaggerService { @Override public void onCreate() { super.onCreate(); - PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService"); mWakeLock.acquire(); @@ -158,7 +154,7 @@ public class NSClientService extends DaggerService { destroy(); initialize(); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventPreferenceChange.class) @@ -172,17 +168,16 @@ public class NSClientService extends DaggerService { destroy(); initialize(); } - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("EventAppExit received"); + aapsLogger.debug(LTag.NSCLIENT, "EventAppExit received"); destroy(); stopSelf(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(EventNSClientRestart.class) @@ -190,22 +185,22 @@ public class NSClientService extends DaggerService { .subscribe(event -> { latestDateInReceivedData = 0; restart(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) + }, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSAuthAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processAuthAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processAuthAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSUpdateAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processUpdateAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processUpdateAck, fabricPrivacy::logException) ); disposable.add(rxBus .toObservable(NSAddAck.class) .observeOn(Schedulers.io()) - .subscribe(this::processAddAck, exception -> FabricPrivacy.getInstance().logException(exception)) + .subscribe(this::processAddAck, fabricPrivacy::logException) ); } @@ -275,6 +270,7 @@ public class NSClientService extends DaggerService { return START_STICKY; } + @SuppressWarnings("deprecation") public void initialize() { dataCounter = 0; @@ -333,7 +329,7 @@ public class NSClientService extends DaggerService { String socketId = mSocket != null ? mSocket.id() : "NULL"; rxBus.send(new EventNSClientNewLog("NSCLIENT", "connect #" + connectCounter + " event. ID: " + socketId)); if (mSocket != null) - sendAuthMessage(new NSAuthAck()); + sendAuthMessage(new NSAuthAck(rxBus)); watchdog(); } }; @@ -367,8 +363,7 @@ public class NSClientService extends DaggerService { private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("disconnect reason: {}", args); + aapsLogger.debug(LTag.NSCLIENT, "disconnect reason: {}", args); rxBus.send(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } }; @@ -402,7 +397,7 @@ public class NSClientService extends DaggerService { authMessage.put("from", latestDateInReceivedData); // send data newer than authMessage.put("secret", nsAPIhashCode); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); return; } rxBus.send(new EventNSClientNewLog("AUTH", "requesting auth")); @@ -456,8 +451,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleAnnouncement(data); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -483,8 +477,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleAlarm(data); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -495,7 +488,7 @@ public class NSClientService extends DaggerService { data = (JSONObject) args[0]; handleUrgentAlarm(data); } catch (Exception e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } }; @@ -518,8 +511,7 @@ public class NSClientService extends DaggerService { rxBus.send(new EventDismissNotification(Notification.NSURGENTALARM)); aapsLogger.debug(LTag.NSCLIENT, data.toString()); } catch (Exception e) { - log.error("Unhandled exception", e); - return; + aapsLogger.error("Unhandled exception", e); } } }; @@ -528,7 +520,7 @@ public class NSClientService extends DaggerService { @Override public void call(final Object... args) { NSClientService.handler.post(() -> { - PowerManager powerManager = (PowerManager) mainApp.getApplicationContext().getSystemService(Context.POWER_SERVICE); + PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NSClientService_onDataUpdate"); wakeLock.acquire(); @@ -557,7 +549,7 @@ public class NSClientService extends DaggerService { nsSettingsStatus.setData(status); if (!status.has("versionNum")) { - if (status.getInt("versionNum") < Config.SUPPORTEDNSVERSION) { + if (status.getInt("versionNum") < config.getSUPPORTEDNSVERSION()) { rxBus.send(new EventNSClientNewLog("ERROR", "Unsupported Nightscout version !!!!")); } } else { @@ -604,7 +596,7 @@ public class NSClientService extends DaggerService { NSTreatment treatment = new NSTreatment(jsonTreatment); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonTreatment); + uploadQueue.removeID(jsonTreatment); //Find latest date in treatment if (treatment.getMills() != null && treatment.getMills() < System.currentTimeMillis()) if (treatment.getMills() > latestDateInReceivedData) @@ -636,7 +628,7 @@ public class NSClientService extends DaggerService { for (Integer index = 0; index < devicestatuses.length(); index++) { JSONObject jsonStatus = devicestatuses.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonStatus); + uploadQueue.removeID(jsonStatus); } nsDeviceStatus.handleNewData(devicestatuses); } @@ -652,7 +644,7 @@ public class NSClientService extends DaggerService { JSONObject jsonFood = foods.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonFood); + uploadQueue.removeID(jsonFood); String action = JsonHelper.safeGetString(jsonFood, "action"); @@ -684,7 +676,7 @@ public class NSClientService extends DaggerService { for (Integer index = 0; index < mbgs.length(); index++) { JSONObject jsonMbg = mbgs.getJSONObject(index); // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonMbg); + uploadQueue.removeID(jsonMbg); } handleNewMbg(mbgs, isDelta); } @@ -695,7 +687,7 @@ public class NSClientService extends DaggerService { // Retreive actual calibration for (Integer index = 0; index < cals.length(); index++) { // remove from upload queue if Ack is failing - UploadQueue.removeID(cals.optJSONObject(index)); + uploadQueue.removeID(cals.optJSONObject(index)); } handleNewCal(cals, isDelta); } @@ -709,7 +701,7 @@ public class NSClientService extends DaggerService { NSSgv sgv = new NSSgv(jsonSgv); // Handle new sgv here // remove from upload queue if Ack is failing - UploadQueue.removeID(jsonSgv); + uploadQueue.removeID(jsonSgv); //Find latest date in sgv if (sgv.getMills() != null && sgv.getMills() < System.currentTimeMillis()) if (sgv.getMills() > latestDateInReceivedData) @@ -722,9 +714,9 @@ public class NSClientService extends DaggerService { } handleNewSgv(sgvs, isDelta); } - rxBus.send(new EventNSClientNewLog("LAST", DateUtil.dateAndTimeString(latestDateInReceivedData))); + rxBus.send(new EventNSClientNewLog("LAST", dateUtil.dateAndTimeString(latestDateInReceivedData))); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } //rxBus.send(new EventNSClientNewLog("NSCLIENT", "onDataUpdate end"); } finally { @@ -744,7 +736,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbUpdate", message, ack); rxBus.send(new EventNSClientNewLog("DBUPDATE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -758,7 +750,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbUpdateUnset", message, ack); rxBus.send(new EventNSClientNewLog("DBUPDATEUNSET " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -771,7 +763,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbRemove", message, ack); rxBus.send(new EventNSClientNewLog("DBREMOVE " + dbr.collection, "Sent " + dbr._id)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -784,7 +776,7 @@ public class NSClientService extends DaggerService { mSocket.emit("dbAdd", message, ack); rxBus.send(new EventNSClientNewLog("DBADD " + dbr.collection, "Sent " + dbr.nsClientID)); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -795,7 +787,7 @@ public class NSClientService extends DaggerService { } public void resend(final String reason) { - if (UploadQueue.size() == 0) + if (uploadQueue.size() == 0) return; if (!isConnected || !hasWriteAuth) return; @@ -804,8 +796,7 @@ public class NSClientService extends DaggerService { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { - if (L.isEnabled(LTag.NSCLIENT)) - log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); + aapsLogger.debug(LTag.NSCLIENT, "Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } lastResendTime = System.currentTimeMillis(); @@ -815,21 +806,21 @@ public class NSClientService extends DaggerService { CloseableIterator iterator; int maxcount = 30; try { - iterator = mainApp.getDbHelper().getDbRequestInterator(); + iterator = databaseHelper.getDbRequestInterator(); try { while (iterator.hasNext() && maxcount > 0) { DbRequest dbr = iterator.next(); if (dbr.action.equals("dbAdd")) { - NSAddAck addAck = new NSAddAck(); + NSAddAck addAck = new NSAddAck(aapsLogger, rxBus); dbAdd(dbr, addAck); } else if (dbr.action.equals("dbRemove")) { - NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck removeAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbRemove(dbr, removeAck); } else if (dbr.action.equals("dbUpdate")) { - NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck updateAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbUpdate(dbr, updateAck); } else if (dbr.action.equals("dbUpdateUnset")) { - NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id); + NSUpdateAck updateUnsetAck = new NSUpdateAck(dbr.action, dbr._id, aapsLogger, rxBus); dbUpdateUnset(dbr, updateUnsetAck); } maxcount--; @@ -838,7 +829,7 @@ public class NSClientService extends DaggerService { iterator.close(); } } catch (SQLException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } rxBus.send(new EventNSClientNewLog("QUEUE", "Resend ended: " + reason)); @@ -851,33 +842,42 @@ public class NSClientService extends DaggerService { } private void handleAnnouncement(JSONObject announcement) { - NSAlarm nsAlarm = new NSAlarm(announcement); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); - rxBus.send(new EventNewNotification(notification)); - rxBus.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(announcement, "message", "received"))); - aapsLogger.debug(LTag.NSCLIENT, announcement.toString()); + boolean defaultVal = config.getNSCLIENT(); + if (sp.getBoolean(R.string.key_ns_announcements, defaultVal)) { + NSAlarm nsAlarm = new NSAlarm(announcement); + Notification notification = new NotificationWithAction(injector, nsAlarm); + rxBus.send(new EventNewNotification(notification)); + rxBus.send(new EventNSClientNewLog("ANNOUNCEMENT", JsonHelper.safeGetString(announcement, "message", "received"))); + aapsLogger.debug(LTag.NSCLIENT, announcement.toString()); + } } private void handleAlarm(JSONObject alarm) { - long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); - if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - NSAlarm nsAlarm = new NSAlarm(alarm); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); - rxBus.send(new EventNewNotification(notification)); + boolean defaultVal = config.getNSCLIENT(); + if (sp.getBoolean(R.string.key_ns_alarms, defaultVal)) { + long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); + if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { + NSAlarm nsAlarm = new NSAlarm(alarm); + Notification notification = new NotificationWithAction(injector, nsAlarm); + rxBus.send(new EventNewNotification(notification)); + } + rxBus.send(new EventNSClientNewLog("ALARM", JsonHelper.safeGetString(alarm, "message", "received"))); + aapsLogger.debug(LTag.NSCLIENT, alarm.toString()); } - rxBus.send(new EventNSClientNewLog("ALARM", JsonHelper.safeGetString(alarm, "message", "received"))); - aapsLogger.debug(LTag.NSCLIENT, alarm.toString()); } private void handleUrgentAlarm(JSONObject alarm) { - long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); - if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { - NSAlarm nsAlarm = new NSAlarm(alarm); - Notification notification = new NotificationWithAction(mainApp, nsAlarm); - rxBus.send(new EventNewNotification(notification)); + boolean defaultVal = config.getNSCLIENT(); + if (sp.getBoolean(R.string.key_ns_alarms, defaultVal)) { + long snoozedTo = sp.getLong(R.string.key_snoozedTo, 0L); + if (snoozedTo == 0L || System.currentTimeMillis() > snoozedTo) { + NSAlarm nsAlarm = new NSAlarm(alarm); + Notification notification = new NotificationWithAction(injector, nsAlarm); + rxBus.send(new EventNewNotification(notification)); + } + rxBus.send(new EventNSClientNewLog("URGENTALARM", JsonHelper.safeGetString(alarm, "message", "received"))); + aapsLogger.debug(LTag.NSCLIENT, alarm.toString()); } - rxBus.send(new EventNSClientNewLog("URGENTALARM", JsonHelper.safeGetString(alarm, "message", "received"))); - aapsLogger.debug(LTag.NSCLIENT, alarm.toString()); } public void handleNewCal(JSONArray cals, boolean isDelta) { @@ -887,7 +887,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_CAL); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public void handleNewMbg(JSONArray mbgs, boolean isDelta) { @@ -897,7 +897,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_MBG); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } public void handleNewProfile(ProfileStore profile, boolean isDelta) { @@ -907,7 +907,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_PROFILE); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { bundle = new Bundle(); @@ -916,7 +916,7 @@ public class NSClientService extends DaggerService { intent = new Intent(Intents.ACTION_NEW_PROFILE); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.sendBroadcast(intent); + this.sendBroadcast(intent); } } @@ -929,7 +929,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_SGV); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -940,7 +940,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_SGV); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.sendBroadcast(intent); + this.sendBroadcast(intent); } } } @@ -954,7 +954,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -966,7 +966,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_NEW_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } } @@ -980,7 +980,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); } if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -992,7 +992,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_CHANGED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } } @@ -1004,7 +1004,7 @@ public class NSClientService extends DaggerService { Intent intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - LocalBroadcastManager.getInstance(mainApp).sendBroadcast(intent); + LocalBroadcastManager.getInstance(this).sendBroadcast(intent); if (sp.getBoolean(R.string.key_nsclient_localbroadcasts, false)) { @@ -1014,7 +1014,7 @@ public class NSClientService extends DaggerService { intent = new Intent(Intents.ACTION_REMOVED_TREATMENT); intent.putExtras(bundle); intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); - mainApp.getApplicationContext().sendBroadcast(intent); + this.getApplicationContext().sendBroadcast(intent); } } @@ -1040,7 +1040,7 @@ public class NSClientService extends DaggerService { ret.add(newarr); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); ret = new ArrayList<>(); ret.add(array); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt index 4a6455e41c..ecacb42b6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewFragment.kt @@ -7,10 +7,10 @@ import android.content.Context import android.content.Intent import android.graphics.Color import android.graphics.Paint +import android.graphics.drawable.AnimationDrawable import android.os.Bundle import android.os.Handler import android.util.DisplayMetrics -import android.util.TypedValue import android.view.ContextMenu import android.view.ContextMenu.ContextMenuInfo import android.view.LayoutInflater @@ -19,7 +19,9 @@ import android.view.View import android.view.View.OnLongClickListener import android.view.ViewGroup import android.widget.LinearLayout +import android.widget.RelativeLayout import android.widget.TextView +import androidx.core.text.toSpanned import androidx.recyclerview.widget.LinearLayoutManager import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector @@ -36,14 +38,15 @@ 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.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.loop.events.EventNewOpenLoopNotification import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData @@ -134,6 +137,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var skinProvider: SkinProvider + @Inject lateinit var config: Config + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var databaseHelper: DatabaseHelperInterface private val disposable = CompositeDisposable() @@ -151,6 +157,8 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList private val secondaryGraphs = ArrayList() private val secondaryGraphsLabel = ArrayList() + private var carbAnimation: AnimationDrawable? = null + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -170,7 +178,6 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - if (smallWidth) overview_arrow?.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 35f) overview_pumpstatus?.setBackgroundColor(resourceHelper.gc(R.color.colorInitializingBorder)) overview_notifications?.setHasFixedSize(false) @@ -179,6 +186,11 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_bggraph?.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) overview_bggraph?.gridLabelRenderer?.reloadStyles() overview_bggraph?.gridLabelRenderer?.labelVerticalWidth = axisWidth + overview_bggraph?.layoutParams?.height = resourceHelper.dpToPx(skinProvider.activeSkin().mainGraphHeight) + + carbAnimation = overview_carbs_icon?.background as AnimationDrawable? + carbAnimation?.setEnterFadeDuration(1200) + carbAnimation?.setExitFadeDuration(1200) rangeToDisplay = sp.getInt(R.string.key_rangetodisplay, 6) @@ -301,57 +313,62 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList // try to fix https://fabric.io/nightscout3/android/apps/info.nightscout.androidaps/issues/5aca7a1536c7b23527eb4be7?time=last-seven-days // https://stackoverflow.com/questions/14860239/checking-if-state-is-saved-before-committing-a-fragmenttransaction if (childFragmentManager.isStateSaved) return - activity?.let { activity -> - when (v.id) { - R.id.overview_treatmentbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { TreatmentDialog().show(childFragmentManager, "Overview") })) - R.id.overview_wizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { WizardDialog().show(childFragmentManager, "Overview") })) - R.id.overview_insulinbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { InsulinDialog().show(childFragmentManager, "Overview") })) - R.id.overview_quickwizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { onClickQuickWizard() })) - R.id.overview_carbsbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { CarbsDialog().show(childFragmentManager, "Overview") })) + try { + activity?.let { activity -> + when (v.id) { + R.id.overview_treatmentbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { TreatmentDialog().show(childFragmentManager, "Overview") })) + R.id.overview_wizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { WizardDialog().show(childFragmentManager, "Overview") })) + R.id.overview_insulinbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { InsulinDialog().show(childFragmentManager, "Overview") })) + R.id.overview_quickwizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { onClickQuickWizard() })) + R.id.overview_carbsbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { CarbsDialog().show(childFragmentManager, "Overview") })) - R.id.overview_cgmbutton -> { - if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) - openCgmApp("com.eveningoutpost.dexdrip") - else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { - dexcomPlugin.findDexcomPackageName()?.let { - openCgmApp(it) - } - ?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) - } - } - - R.id.overview_calibrationbutton -> { - if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) { - CalibrationDialog().show(childFragmentManager, "CalibrationDialog") - } else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { - try { + R.id.overview_cgmbutton -> { + if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) + openCgmApp("com.eveningoutpost.dexdrip") + else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { dexcomPlugin.findDexcomPackageName()?.let { - startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it)) + openCgmApp(it) } ?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) - } catch (e: ActivityNotFoundException) { - ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.g5appnotdetected)) } } - } - R.id.overview_accepttempbutton -> { - profileFunction.getProfile() ?: return - if (loopPlugin.isEnabled(PluginType.LOOP)) { - val lastRun = loopPlugin.lastRun - loopPlugin.invoke("Accept temp button", false) - if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed.isChangeRequested) { - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.pump_tempbasal_label), lastRun.constraintsProcessed.toSpanned(), Runnable { - aapsLogger.debug("USER ENTRY: ACCEPT TEMP BASAL") - overview_accepttempbutton?.visibility = View.GONE - (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) - actionStringHandler.handleInitiate("cancelChangeRequest") - loopPlugin.acceptChangeRequest() - }) + R.id.overview_calibrationbutton -> { + if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) { + CalibrationDialog().show(childFragmentManager, "CalibrationDialog") + } else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { + try { + dexcomPlugin.findDexcomPackageName()?.let { + startActivity(Intent("com.dexcom.cgm.activities.MeterEntryActivity").setPackage(it)) + } + ?: ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.dexcom_app_not_installed)) + } catch (e: ActivityNotFoundException) { + ToastUtils.showToastInUiThread(activity, resourceHelper.gs(R.string.g5appnotdetected)) + } + } + } + + R.id.overview_accepttempbutton -> { + profileFunction.getProfile() ?: return + if (loopPlugin.isEnabled(PluginType.LOOP)) { + val lastRun = loopPlugin.lastRun + loopPlugin.invoke("Accept temp button", false) + if (lastRun?.lastAPSRun != null && lastRun.constraintsProcessed?.isChangeRequested == true) { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.tempbasal_label), lastRun.constraintsProcessed?.toSpanned() + ?: "".toSpanned(), Runnable { + aapsLogger.debug("USER ENTRY: ACCEPT TEMP BASAL") + overview_accepttempbutton?.visibility = View.GONE + (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) + actionStringHandler.handleInitiate("cancelChangeRequest") + loopPlugin.acceptChangeRequest() + }) + } } } } } + } catch (ignored: IllegalStateException) { + // ignore Can not perform this action after onSaveInstanceState } } @@ -438,7 +455,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val showAcceptButton = !closedLoopEnabled.value() && // Open mode needed lastRun != null && (lastRun.lastOpenModeAccept == 0L || lastRun.lastOpenModeAccept < lastRun.lastAPSRun) &&// never accepted or before last result - lastRun.constraintsProcessed.isChangeRequested // change is requested + lastRun.constraintsProcessed?.isChangeRequested == true // change is requested if (showAcceptButton && pump.isInitialized && !pump.isSuspended && loopPlugin.isEnabled(PluginType.LOOP)) { overview_accepttempbutton?.visibility = View.VISIBLE @@ -461,6 +478,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } + @Synchronized private fun prepareGraphs() { val numOfGraphs = overviewMenus.setting.size @@ -471,19 +489,28 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList secondaryGraphsLabel.clear() overview_iobgraph.removeAllViews() for (i in 1 until numOfGraphs) { - val label = TextView(context) - label.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(100, 0, 0, -50) } - overview_iobgraph.addView(label) - secondaryGraphsLabel.add(label) + val relativeLayout = RelativeLayout(context) + relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) + val graph = GraphView(context) - graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(100)).also { it.setMargins(0, 0, 0, resourceHelper.dpToPx(10)) } + graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, resourceHelper.dpToPx(skinProvider.activeSkin().secondaryGraphHeight)).also { it.setMargins(0, resourceHelper.dpToPx(15), 0, resourceHelper.dpToPx(10)) } graph.gridLabelRenderer?.gridColor = resourceHelper.gc(R.color.graphgrid) graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.numVerticalLabels = 3 graph.viewport.backgroundColor = Color.argb(20, 255, 255, 255) // 8% of gray - overview_iobgraph.addView(graph) + relativeLayout.addView(graph) + + val label = TextView(context) + val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(resourceHelper.dpToPx(30), resourceHelper.dpToPx(25), 0, 0) } + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) + layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) + label.layoutParams = layoutParams + relativeLayout.addView(label) + secondaryGraphsLabel.add(label) + + overview_iobgraph.addView(relativeLayout) secondaryGraphs.add(graph) } } @@ -506,11 +533,12 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList scheduledUpdate = worker.schedule(task, 500, TimeUnit.MILLISECONDS) } + @Synchronized @SuppressLint("SetTextI18n") fun updateGUI(from: String) { aapsLogger.debug("UpdateGUI from $from") - overview_time?.text = DateUtil.timeString(Date()) + overview_time?.text = dateUtil.timeString(Date()) if (!profileFunction.isProfileValid("Overview")) { overview_pumpstatus?.setText(R.string.noprofileset) @@ -541,14 +569,14 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_bg?.text = lastBG.valueToUnitsToString(units) overview_bg?.setTextColor(color) - overview_arrow?.text = lastBG.directionToSymbol() - overview_arrow?.setTextColor(color) + overview_arrow?.setImageResource(lastBG.directionToIcon(databaseHelper)) + overview_arrow?.setColorFilter(color) val glucoseStatus = GlucoseStatus(injector).glucoseStatusData if (glucoseStatus != null) { - overview_delta?.text = "Δ ${Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)}" + overview_delta?.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) overview_deltashort?.text = Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) - overview_avgdelta?.text = "Δ15m: ${Profile.toUnitsString(glucoseStatus.short_avgdelta, glucoseStatus.short_avgdelta * Constants.MGDL_TO_MMOLL, units)}\nΔ40m: ${Profile.toUnitsString(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)}\n${Profile.toSignedUnitsString(glucoseStatus.long_avgdelta, glucoseStatus.long_avgdelta * Constants.MGDL_TO_MMOLL, units)}" } else { overview_delta?.text = "Δ " + resourceHelper.gs(R.string.notavailable) overview_deltashort?.text = "---" @@ -570,76 +598,55 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val closedLoopEnabled = constraintChecker.isClosedLoopAllowed() // open loop mode - if (Config.APS && pump.pumpDescription.isTempBasalCapable) { + if (config.APS && pump.pumpDescription.isTempBasalCapable) { overview_apsmode?.visibility = View.VISIBLE when { loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { - overview_apsmode.setImageResource(R.drawable.loop_superbolus) + overview_apsmode?.setImageResource(R.drawable.ic_loop_superbolus) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) - //overview_apsmode_text?.text = String.format(resourceHelper.gs(R.string.loopsuperbolusfor), loopPlugin.minutesToEndOfSuspend()) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) } loopPlugin.isDisconnected -> { - overview_apsmode.setImageResource(R.drawable.loop_disconnected) + overview_apsmode?.setImageResource(R.drawable.ic_loop_disconnected) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) -// overview_apsmode_text?.text = String.format(resourceHelper.gs(R.string.loopdisconnectedfor), loopPlugin.minutesToEndOfSuspend()) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonCritical)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextCritical)) } loopPlugin.isEnabled() && loopPlugin.isSuspended -> { - overview_apsmode.setImageResource(R.drawable.loop_paused) + overview_apsmode?.setImageResource(R.drawable.ic_loop_paused) overview_apsmode_text?.text = DateUtil.age(loopPlugin.minutesToEndOfSuspend() * 60000L, true, resourceHelper) -// overview_apsmode_text?.text = String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) } pump.isSuspended -> { - overview_apsmode.setImageResource(R.drawable.loop_paused) + overview_apsmode?.setImageResource(R.drawable.ic_loop_paused) overview_apsmode_text?.text = "" -// overview_apsmode_text?.text = resourceHelper.gs(R.string.pumpsuspended) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) } loopPlugin.isEnabled() && closedLoopEnabled.value() && loopPlugin.isLGS -> { - overview_apsmode.setImageResource(R.drawable.loop_lgs) + overview_apsmode?.setImageResource(R.drawable.ic_loop_lgs) overview_apsmode_text?.text = "" -// overview_apsmode_text?.text = resourceHelper.gs(R.string.closedloop) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) } loopPlugin.isEnabled() && closedLoopEnabled.value() -> { - overview_apsmode.setImageResource(R.drawable.loop_closed) + overview_apsmode?.setImageResource(R.drawable.ic_loop_closed) overview_apsmode_text?.text = "" -// overview_apsmode_text?.text = resourceHelper.gs(R.string.closedloop) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) } loopPlugin.isEnabled() && !closedLoopEnabled.value() -> { - overview_apsmode.setImageResource(R.drawable.loop_open) + overview_apsmode?.setImageResource(R.drawable.ic_loop_open) overview_apsmode_text?.text = "" -// overview_apsmode_text?.text = resourceHelper.gs(R.string.openloop) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) } else -> { - overview_apsmode.setImageResource(R.drawable.loop_disabled) + overview_apsmode?.setImageResource(R.drawable.ic_loop_disabled) overview_apsmode_text?.text = "" -// overview_apsmode_text?.text = resourceHelper.gs(R.string.disabledloop) -// overview_apsmode_text?.setBackgroundColor(resourceHelper.gc(R.color.ribbonCritical)) -// overview_apsmode_text?.setTextColor(resourceHelper.gc(R.color.ribbonTextCritical)) } } } else { + overview_apsmode?.visibility = View.GONE overview_apsmode_text?.visibility = View.GONE } + val lastRun = loopPlugin.lastRun + val predictionsAvailable = if (config.APS) lastRun?.request?.hasPredictions == true else config.NSCLIENT // temp target val tempTarget = treatmentsPlugin.tempTargetFromHistory @@ -648,9 +655,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_temptarget?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) overview_temptarget?.text = Profile.toTargetRangeString(tempTarget.low, tempTarget.high, Constants.MGDL, units) + " " + DateUtil.untilString(tempTarget.end(), resourceHelper) } else { - overview_temptarget?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) - overview_temptarget?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) - overview_temptarget?.text = Profile.toTargetRangeString(profile.targetLowMgdl, profile.targetHighMgdl, Constants.MGDL, units) + // If the target is not the same as set in the profile then oref has overridden it + val targetUsed = lastRun?.constraintsProcessed?.targetBG ?: 0.0 + + if (targetUsed != 0.0 && abs(profile.targetMgdl - targetUsed) > 0.01) { + aapsLogger.debug("Adjusted target. Profile: ${profile.targetMgdl} APS: $targetUsed") + overview_temptarget?.text = Profile.toTargetRangeString(targetUsed, targetUsed, Constants.MGDL, units) + overview_temptarget?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) + overview_temptarget?.setBackgroundColor(resourceHelper.gc(R.color.tempTargetBackground)) + } else { + overview_temptarget?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) + overview_temptarget?.setBackgroundColor(resourceHelper.gc(R.color.ribbonDefault)) + overview_temptarget?.text = Profile.toTargetRangeString(profile.targetLowMgdl, profile.targetHighMgdl, Constants.MGDL, units) + } } // Basal, TBR @@ -658,16 +675,21 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_basebasal?.text = activeTemp?.let { if (resourceHelper.shortTextMode()) "T:" + activeTemp.toStringVeryShort() else activeTemp.toStringFull() } ?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal) overview_basal_llayout?.setOnClickListener { - var fullText = "${resourceHelper.gs(R.string.pump_basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" + var fullText = "${resourceHelper.gs(R.string.basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" if (activeTemp != null) - fullText += "\n" + resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull() + fullText += "\n" + resourceHelper.gs(R.string.tempbasal_label) + ": " + activeTemp.toStringFull() activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.basal), fullText) } } overview_basebasal?.setTextColor(activeTemp?.let { resourceHelper.gc(R.color.basal) } ?: resourceHelper.gc(R.color.defaulttextcolor)) - overview_basebasal_icon.setImageResource(if (activeTemp != null) R.drawable.icon_cp_basal_start else R.drawable.icon_cp_basal_end) + + overview_basebasal_icon?.setImageResource(R.drawable.ic_cp_basal_no_tbr) + val percentRate = activeTemp?.tempBasalConvertedToPercent(System.currentTimeMillis(), profile) + ?: 100 + if (percentRate > 100) overview_basebasal_icon?.setImageResource(R.drawable.ic_cp_basal_tbr_high) + if (percentRate < 100) overview_basebasal_icon?.setImageResource(R.drawable.ic_cp_basal_tbr_low) // Extended bolus val extendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()) @@ -719,7 +741,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } // Status lights - overview_statuslights?.visibility = (sp.getBoolean(R.string.key_show_statuslights, true) || Config.NSCLIENT).toVisibility() + overview_statuslights?.visibility = (sp.getBoolean(R.string.key_show_statuslights, true) || config.NSCLIENT).toVisibility() statusLightHandler.updateStatusLights(careportal_canulaage, careportal_insulinage, careportal_reservoirlevel, careportal_sensorage, careportal_pbage, careportal_batterylevel) // cob @@ -729,10 +751,22 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList cobText = resourceHelper.gs(R.string.format_carbs, cobInfo.displayCob.toInt()) if (cobInfo.futureCarbs > 0) cobText += "(" + DecimalFormatter.to0Decimal(cobInfo.futureCarbs) + ")" } - overview_cob?.text = cobText - val lastRun = loopPlugin.lastRun - val predictionsAvailable = if (Config.APS) lastRun?.request?.hasPredictions == true else Config.NSCLIENT + if (config.APS && lastRun?.constraintsProcessed != null) { + if (lastRun.constraintsProcessed!!.carbsReq > 0) { + //only display carbsreq when carbs have not been entered recently + if (treatmentsPlugin.lastCarbTime < lastRun.lastAPSRun) { + cobText = cobText + " | " + lastRun.constraintsProcessed!!.carbsReq + " " + resourceHelper.gs(R.string.required) + } + overview_cob?.text = cobText + if (carbAnimation?.isRunning == false) + carbAnimation?.start() + } else { + overview_cob?.text = cobText + carbAnimation?.stop() + carbAnimation?.selectDrawable(0) + } + } else overview_cob?.text = cobText // pump status from ns overview_pump?.text = nsDeviceStatus.pumpStatus @@ -747,6 +781,12 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_uploader?.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } } // Sensitivity + if (sp.getBoolean(R.string.key_openapsama_useautosens, false) && constraintChecker.isAutosensModeEnabled().value()) { + overview_sensitivity_icon?.setImageResource(R.drawable.ic_swap_vert_black_48dp_green) + } else { + overview_sensitivity_icon?.setImageResource(R.drawable.ic_x_swap_vert) + } + overview_sensitivity?.text = iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData -> String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100) @@ -755,7 +795,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList // ****** GRAPH ******* GlobalScope.launch(Dispatchers.Main) { overview_bggraph ?: return@launch - val graphData = GraphData(injector, overview_bggraph, iobCobCalculatorPlugin) + val graphData = GraphData(injector, overview_bggraph, iobCobCalculatorPlugin, treatmentsPlugin) val secondaryGraphsData: ArrayList = ArrayList() // do preparation in different thread @@ -771,15 +811,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val toTime: Long val fromTime: Long val endTime: Long - val apsResult = if (Config.APS) lastRun?.constraintsProcessed else NSDeviceStatus.getAPSResult(injector) + val apsResult = if (config.APS) lastRun?.constraintsProcessed else NSDeviceStatus.getAPSResult(injector) if (predictionsAvailable && apsResult != null && overviewMenus.setting[0][OverviewMenus.CharType.PRE.ordinal]) { - var predHours = (ceil(apsResult.latestPredictionsTime - System.currentTimeMillis().toDouble()) / (60 * 60 * 1000)).toInt() - predHours = min(2, predHours) - predHours = max(0, predHours) - hoursToFetch = rangeToDisplay - predHours + var predictionHours = (ceil(apsResult.latestPredictionsTime - System.currentTimeMillis().toDouble()) / (60 * 60 * 1000)).toInt() + predictionHours = min(2, predictionHours) + predictionHours = max(0, predictionHours) + hoursToFetch = rangeToDisplay - predictionHours toTime = calendar.timeInMillis + 100000 // little bit more to avoid wrong rounding - GraphView specific fromTime = toTime - T.hours(hoursToFetch.toLong()).msecs() - endTime = toTime + T.hours(predHours.toLong()).msecs() + endTime = toTime + T.hours(predictionHours.toLong()).msecs() } else { hoursToFetch = rangeToDisplay toTime = calendar.timeInMillis + 100000 // little bit more to avoid wrong rounding - GraphView specific @@ -817,31 +857,31 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList graphData.addNowLine(now) // ------------------ 2nd graph - for (g in 0 until secondaryGraphs.size) { - val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculatorPlugin) + for (g in 0 until min(secondaryGraphs.size, overviewMenus.setting.size + 1)) { + val secondGraphData = GraphData(injector, secondaryGraphs[g], iobCobCalculatorPlugin, treatmentsPlugin) + var useABSForScale = false var useIobForScale = false var useCobForScale = false var useDevForScale = false var useRatioForScale = false var useDSForScale = false var useIAForScale = false - var useABSForScale = false when { + overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] -> useIAForScale = true - overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true } + if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, now, useABSForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(fromTime, now, useIobForScale, 1.0, overviewMenus.setting[g + 1][OverviewMenus.CharType.PRE.ordinal]) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(fromTime, now, useCobForScale, if (useCobForScale) 1.0 else 0.5) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(fromTime, now, useDevForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(fromTime, now, useRatioForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal]) secondGraphData.addActivity(fromTime, endTime, useIAForScale, 0.8) - if (overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(fromTime, now, useABSForScale, 1.0) if (overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(fromTime, now, useDSForScale, 1.0) // set manual x bounds to have nice steps @@ -852,19 +892,19 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } // finally enforce drawing of graphs in UI thread graphData.performUpdate() - for (g in 0 until secondaryGraphs.size) { + for (g in 0 until min(secondaryGraphs.size, overviewMenus.setting.size + 1)) { secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) secondaryGraphs[g].visibility = ( - overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] || + overviewMenus.setting[g + 1][OverviewMenus.CharType.IOB.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.COB.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.DEV.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.SEN.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.ACT.ordinal] || - overviewMenus.setting[g + 1][OverviewMenus.CharType.ABS.ordinal] || overviewMenus.setting[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] ).toVisibility() secondaryGraphsData[g].performUpdate() } } } -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt index a6ad002aa9..f5e3c656dc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewMenus.kt @@ -15,7 +15,6 @@ import androidx.annotation.StringRes import androidx.appcompat.widget.PopupMenu import androidx.fragment.app.FragmentManager import com.google.gson.Gson -import com.google.gson.reflect.TypeToken import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity @@ -34,7 +33,7 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper @@ -42,7 +41,6 @@ import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import java.lang.reflect.Type import javax.inject.Inject import javax.inject.Singleton @@ -59,19 +57,20 @@ class OverviewMenus @Inject constructor( private val profileFunction: ProfileFunction, private val commandQueue: CommandQueueProvider, private val configBuilderPlugin: ConfigBuilderPlugin, - private val loopPlugin: LoopPlugin + private val loopPlugin: LoopPlugin, + private val config: Config ) { - enum class CharType(@StringRes val nameId: Int, @ColorRes val colorId: Int, val primary: Boolean, val secondary: Boolean) { - PRE(R.string.overview_show_predictions, R.color.prediction, primary = true, secondary = false), - BAS(R.string.overview_show_basals, R.color.basal, primary = true, secondary = false), - IOB(R.string.overview_show_iob, R.color.iob, primary = false, secondary = true), - COB(R.string.overview_show_cob, R.color.cob, primary = false, secondary = true), - DEV(R.string.overview_show_deviations, R.color.deviations, primary = false, secondary = true), - SEN(R.string.overview_show_sensitivity, R.color.ratio, primary = false, secondary = true), - ACT(R.string.overview_show_activity, R.color.activity, primary = true, secondary = true), - ABS(R.string.overview_show_absinsulin, R.color.iob, primary = false, secondary = true), - DEVSLOPE(R.string.overview_show_deviationslope, R.color.devslopepos, primary = false, secondary = true) + enum class CharType(@StringRes val nameId: Int, @ColorRes val colorId: Int, val primary: Boolean, val secondary: Boolean, @StringRes val shortnameId: Int) { + PRE(R.string.overview_show_predictions, R.color.prediction, primary = true, secondary = false, shortnameId = R.string.prediction_shortname), + BAS(R.string.overview_show_basals, R.color.basal, primary = true, secondary = false,shortnameId = R.string.basal_shortname), + ABS(R.string.overview_show_absinsulin, R.color.iob, primary = false, secondary = true,shortnameId = R.string.abs_insulin_shortname), + IOB(R.string.overview_show_iob, R.color.iob, primary = false, secondary = true,shortnameId = R.string.iob), + COB(R.string.overview_show_cob, R.color.cob, primary = false, secondary = true,shortnameId = R.string.cob), + DEV(R.string.overview_show_deviations, R.color.deviations, primary = false, secondary = true,shortnameId = R.string.deviation_shortname), + SEN(R.string.overview_show_sensitivity, R.color.ratio, primary = false, secondary = true,shortnameId = R.string.sensitivity_shortname), + ACT(R.string.overview_show_activity, R.color.activity, primary = true, secondary = true,shortnameId = R.string.activity_shortname), + DEVSLOPE(R.string.overview_show_deviationslope, R.color.devslopepos, primary = false, secondary = true,shortnameId = R.string.devslope_shortname) } companion object { @@ -81,7 +80,7 @@ class OverviewMenus @Inject constructor( fun enabledTypes(graph: Int): String { val r = StringBuilder() for (type in CharType.values()) if (setting[graph][type.ordinal]) { - r.append(type.name) + r.append(resourceHelper.gs(type.shortnameId)) r.append(" ") } return r.toString() @@ -117,8 +116,8 @@ class OverviewMenus @Inject constructor( chartButton.setOnClickListener { v: View -> val predictionsAvailable: Boolean = when { - Config.APS -> loopPlugin.lastRun?.request?.hasPredictions ?: false - Config.NSCLIENT -> true + config.APS -> loopPlugin.lastRun?.request?.hasPredictions ?: false + config.NSCLIENT -> true else -> false } val popup = PopupMenu(v.context, v) @@ -207,7 +206,7 @@ class OverviewMenus @Inject constructor( R.id.overview_activeprofile -> { menu.setHeaderTitle(resourceHelper.gs(R.string.profile)) - menu.add(resourceHelper.gs(R.string.danar_viewprofile)) + menu.add(resourceHelper.gs(R.string.viewprofile)) if (activePlugin.activeProfileInterface.profile != null) { menu.add(resourceHelper.gs(R.string.careportal_profileswitch)) } @@ -342,18 +341,18 @@ class OverviewMenus @Inject constructor( return true } - resourceHelper.gs(R.string.disconnectpumpfor3h) -> { + resourceHelper.gs(R.string.disconnectpumpfor3h) -> { aapsLogger.debug("USER ENTRY: DISCONNECT 3h") loopPlugin.disconnectPump(180, profile) rxBus.send(EventRefreshOverview("suspendmenu")) return true } - resourceHelper.gs(R.string.careportal_profileswitch) -> { + resourceHelper.gs(R.string.careportal_profileswitch) -> { ProfileSwitchDialog().show(manager, "Overview") } - resourceHelper.gs(R.string.danar_viewprofile) -> { + resourceHelper.gs(R.string.viewprofile) -> { val args = Bundle() args.putLong("time", DateUtil.now()) args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) @@ -362,7 +361,7 @@ class OverviewMenus @Inject constructor( pvd.show(manager, "ProfileViewDialog") } - resourceHelper.gs(R.string.eatingsoon) -> { + resourceHelper.gs(R.string.eatingsoon) -> { aapsLogger.debug("USER ENTRY: TEMP TARGET EATING SOON") val target = Profile.toMgdl(defaultValueHelper.determineEatingSoonTT(), profileFunction.getUnits()) val tempTarget = TempTarget() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 219b56d025..668e7c7fc2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -1,6 +1,9 @@ package info.nightscout.androidaps.plugins.general.overview +import androidx.preference.PreferenceFragmentCompat +import androidx.preference.SwitchPreference 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.PluginBase @@ -26,7 +29,8 @@ class OverviewPlugin @Inject constructor( private val fabricPrivacy: FabricPrivacy, private val rxBus: RxBusWrapper, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper + resourceHelper: ResourceHelper, + private val config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(OverviewFragment::class.qualifiedName) @@ -64,4 +68,18 @@ class OverviewPlugin @Inject constructor( disposable.clear() super.onStop() } + + override fun preprocessPreferences(preferenceFragment: PreferenceFragmentCompat) { + super.preprocessPreferences(preferenceFragment) + if (config.NSCLIENT) { + (preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_cgm_button)) as SwitchPreference?)?.let { + it.isVisible = false + it.isEnabled = false + } + (preferenceFragment.findPreference(resourceHelper.gs(R.string.key_show_calibration_button)) as SwitchPreference?)?.let { + it.isVisible = false + it.isEnabled = false + } + } + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt index b05e1cb015..8a95e34e1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/StatusLightHandler.kt @@ -20,7 +20,8 @@ class StatusLightHandler @Inject constructor( private val resourceHelper: ResourceHelper, private val sp: SP, private val activePlugin: ActivePluginProvider, - private val warnColors: WarnColors + private val warnColors: WarnColors, + private val config: Config ) { /** @@ -32,9 +33,9 @@ class StatusLightHandler @Inject constructor( handleAge(careportal_insulinage, CareportalEvent.INSULINCHANGE, R.string.key_statuslights_iage_warning, 72.0, R.string.key_statuslights_iage_critical, 144.0) handleAge(careportal_sensorage, CareportalEvent.SENSORCHANGE, R.string.key_statuslights_sage_warning, 216.0, R.string.key_statuslights_sage_critical, 240.0) handleAge(careportal_pbage, CareportalEvent.PUMPBATTERYCHANGE, R.string.key_statuslights_bage_warning, 216.0, R.string.key_statuslights_bage_critical, 240.0) - if (!Config.NSCLIENT) + if (!config.NSCLIENT) handleLevel(careportal_reservoirlevel, R.string.key_statuslights_res_critical, 10.0, R.string.key_statuslights_res_warning, 80.0, pump.reservoirLevel, "U") - if (!Config.NSCLIENT && pump.model() != PumpType.AccuChekCombo) + if (!config.NSCLIENT && pump.model() != PumpType.AccuChekCombo) handleLevel(careportal_batterylevel, R.string.key_statuslights_bat_critical, 26.0, R.string.key_statuslights_bat_warning, 51.0, pump.batteryLevel.toDouble(), "%") } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt index 505ec3e943..6510b7505f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/activities/QuickWizardListActivity.kt @@ -29,6 +29,7 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var quickWizard: QuickWizard + @Inject lateinit var dateUtil: DateUtil private var disposable: CompositeDisposable = CompositeDisposable() @@ -39,8 +40,8 @@ class QuickWizardListActivity : NoSplashAppCompatActivity() { } override fun onBindViewHolder(holder: QuickWizardEntryViewHolder, position: Int) { - holder.from.text = DateUtil.timeString(quickWizard[position].validFromDate()) - holder.to.text = DateUtil.timeString(quickWizard[position].validToDate()) + holder.from.text = dateUtil.timeString(quickWizard[position].validFromDate()) + holder.to.text = dateUtil.timeString(quickWizard[position].validToDate()) holder.buttonText.text = quickWizard[position].buttonText() holder.carbs.text = resourceHelper.gs(R.string.format_carbs, quickWizard[position].carbs()) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt index d2531c77c5..463c7564fa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/dialogs/EditQuickWizardDialog.kt @@ -27,6 +27,7 @@ class EditQuickWizardDialog : DaggerDialogFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var quickWizard: QuickWizard + @Inject lateinit var dateUtil: DateUtil var position = -1 @@ -77,13 +78,13 @@ class EditQuickWizardDialog : DaggerDialogFragment() { var pos = 0 var t = 0 while (t < 24 * 60 * 60) { - timeList.add(DateUtil.timeString(DateUtil.toDate(t))) + timeList.add(dateUtil.timeString(DateUtil.toDate(t))) if (entry.validFrom() == t) posFrom = pos if (entry.validTo() == t) posTo = pos pos++ t += 15 * 60 } - timeList.add(DateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60))) + timeList.add(dateUtil.timeString(DateUtil.toDate(24 * 60 * 60 - 60))) val adapter = context?.let { context -> ArrayAdapter(context, R.layout.spinner_centered, timeList) } overview_editquickwizard_from_spinner.adapter = adapter @@ -103,7 +104,7 @@ class EditQuickWizardDialog : DaggerDialogFragment() { overview_editquickwizard_usetemptarget_spinner.setSelection(entry.useTempTarget()) overview_editquickwizard_usecob_spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { - override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) = processCob() + override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) = processCob() override fun onNothingSelected(parent: AdapterView<*>) {} } processCob() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt index 54d34533f3..f3a779af22 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphData/GraphData.kt @@ -16,12 +16,12 @@ import info.nightscout.androidaps.data.IobTotal import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.LoopInterface import info.nightscout.androidaps.interfaces.TreatmentsInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin.LastRun import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.graphExtensions.* import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin @@ -34,7 +34,13 @@ import kotlin.math.abs import kotlin.math.max import kotlin.math.min -class GraphData(injector: HasAndroidInjector, private val graph: GraphView, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin) { +class GraphData( + injector: HasAndroidInjector, + private val graph: GraphView, + private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val treatmentsPlugin: TreatmentsInterface + +) { // IobCobCalculatorPlugin Cannot be injected: HistoryBrowser @Inject lateinit var aapsLogger: AAPSLogger @@ -42,8 +48,6 @@ class GraphData(injector: HasAndroidInjector, private val graph: GraphView, priv @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var activePlugin: ActivePluginProvider - private val treatmentsPlugin: TreatmentsInterface - var maxY = Double.MIN_VALUE private var minY = Double.MAX_VALUE private var bgReadingsArray: List? = null @@ -53,7 +57,6 @@ class GraphData(injector: HasAndroidInjector, private val graph: GraphView, priv init { injector.androidInjector().inject(this) units = profileFunction.getUnits() - treatmentsPlugin = activePlugin.activeTreatments } @Suppress("UNUSED_PARAMETER") @@ -197,7 +200,7 @@ class GraphData(injector: HasAndroidInjector, private val graph: GraphView, priv basalScale.setMultiplier(maxY * scale / maxBasalValueFound) } - fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LastRun?) { + fun addTargetLine(fromTime: Long, toTimeParam: Long, profile: Profile, lastRun: LoopInterface.LastRun?) { var toTime = toTimeParam val targetsSeriesArray: MutableList = ArrayList() var lastTarget = -1.0 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt index b07e9756e9..f467cc1fce 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationStore.kt @@ -38,7 +38,8 @@ class NotificationStore @Inject constructor( private val rxBus: RxBusWrapper, private val resourceHelper: ResourceHelper, private val context: Context, - private val iconsProvider: IconsProvider + private val iconsProvider: IconsProvider, + private val dateUtil: DateUtil ) { var store: MutableList = ArrayList() @@ -192,7 +193,7 @@ class NotificationStore @Inject constructor( if (notification.buttonText != 0) holder.dismiss.setText(notification.buttonText) else holder.dismiss.setText(R.string.snooze) @Suppress("SetTextI18n") - holder.text.text = DateUtil.timeString(notification.date) + " " + notification.text + 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)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt index 3d198dfc0b..43a2094ef0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationUserMessage.kt @@ -6,6 +6,7 @@ class NotificationUserMessage (text :String): Notification() { var hash = text.hashCode() if (hash < USERMESSAGE) hash += USERMESSAGE id = hash + date = System.currentTimeMillis() this.text = text level = URGENT } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt index 2d8ad45c2b..4e85b03b5c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt @@ -22,8 +22,6 @@ class NotificationWithAction constructor( @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var nsClientPlugin: NSClientPlugin - private var nsAlarm: NSAlarm? = null - init { injector.androidInjector().inject(this) } @@ -36,7 +34,6 @@ class NotificationWithAction constructor( } constructor (injector: HasAndroidInjector, nsAlarm: NSAlarm) : this(injector) { - this.nsAlarm = nsAlarm date = System.currentTimeMillis() when (nsAlarm.level()) { 0 -> { @@ -50,14 +47,14 @@ class NotificationWithAction constructor( id = NSALARM level = NORMAL text = nsAlarm.title() - if (nsAlarm.low() && sp.getBoolean(R.string.key_nsalarm_low, false) || nsAlarm.high() && sp.getBoolean(R.string.key_nsalarm_high, false) || nsAlarm.timeago() && sp.getBoolean(R.string.key_nsalarm_staledata, false)) soundId = R.raw.alarm + soundId = R.raw.alarm } 2 -> { id = NSURGENTALARM level = URGENT text = nsAlarm.title() - if (nsAlarm.low() && sp.getBoolean(R.string.key_nsalarm_low, false) || nsAlarm.high() && sp.getBoolean(R.string.key_nsalarm_high, false) || nsAlarm.timeago() && sp.getBoolean(R.string.key_nsalarm_staledata, false)) soundId = R.raw.urgentalarm + soundId = R.raw.urgentalarm } } buttonText = R.string.snooze diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt index 8d4c605057..5fcf9ee85b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyService.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.persistentNotification +import android.app.Notification import android.app.Service import android.content.Intent import android.os.IBinder @@ -26,13 +27,17 @@ class DummyService : DaggerService() { private val disposable = CompositeDisposable() - override fun onBind(intent: Intent): IBinder? = null + override fun onBind(intent: Intent?): IBinder? = null override fun onCreate() { super.onCreate() // TODO: I guess this was moved here in order to adhere to the 5 seconds rule to call "startForeground" after a Service was called as Foreground service? // As onCreate() is not called every time a service is started, copied to onStartCommand(). - startForeground(notificationHolder.notificationID, notificationHolder.notification) + try { + startForeground(notificationHolder.notificationID, notificationHolder.notification) + } catch (e: Exception) { + startForeground(4711, Notification()) + } disposable.add(rxBus .toObservable(EventAppExit::class.java) .observeOn(Schedulers.io()) @@ -50,9 +55,13 @@ class DummyService : DaggerService() { stopForeground(true) } - override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) - startForeground(notificationHolder.notificationID, notificationHolder.notification) + try { + startForeground(notificationHolder.notificationID, notificationHolder.notification) + } catch (e: Exception) { + startForeground(4711, Notification()) + } return Service.START_STICKY } -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index c1a203a343..ca4b8c1720 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt @@ -15,13 +15,9 @@ import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.events.* -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished @@ -47,7 +43,8 @@ class PersistentNotificationPlugin @Inject constructor( private var rxBus: RxBusWrapper, private var context: Context, private var notificationHolder: NotificationHolder, - private val iconsProvider: IconsProvider + private val iconsProvider: IconsProvider, + private val databaseHelper: DatabaseHelperInterface ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .neverVisible(true) @@ -147,7 +144,7 @@ class PersistentNotificationPlugin @Inject constructor( if (glucoseStatus != null) { line1 += (" Δ" + Profile.toSignedUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units) + " avgΔ" + Profile.toSignedUnitsString(glucoseStatus.avgdelta, glucoseStatus.avgdelta * Constants.MGDL_TO_MMOLL, units)) - line1_aa += " " + lastBG.directionToSymbol() + line1_aa += " " + lastBG.directionToSymbol(databaseHelper) } else { line1 += " " + resourceHelper.gs(R.string.old_data) + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt index 94dd9965f8..49a1778a7e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt @@ -23,6 +23,7 @@ class SmsCommunicatorFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy : FabricPrivacy @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin + @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() @@ -61,15 +62,15 @@ class SmsCommunicatorFragment : DaggerFragment() { val sms = smsCommunicatorPlugin.messages[x] when { sms.ignored -> { - logText += DateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
" + logText += dateUtil.timeString(sms.date) + " <<< " + "░ " + sms.phoneNumber + " " + sms.text + "
" } sms.received -> { - logText += DateUtil.timeString(sms.date) + " <<< " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + "
" + logText += dateUtil.timeString(sms.date) + " <<< " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + "
" } sms.sent -> { - logText += DateUtil.timeString(sms.date) + " >>> " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + "
" + logText += dateUtil.timeString(sms.date) + " >>> " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " " + sms.text + "
" } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt index c8a6bc8601..60bba0fd13 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorPlugin.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification @@ -61,7 +61,9 @@ class SmsCommunicatorPlugin @Inject constructor( private val loopPlugin: LoopPlugin, private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, private val xdripCalibrations: XdripCalibrations, - private var otp: OneTimePassword + private var otp: OneTimePassword, + private val config: Config, + private val dateUtil: DateUtil ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .fragmentClass(SmsCommunicatorFragment::class.java.name) @@ -83,7 +85,7 @@ class SmsCommunicatorPlugin @Inject constructor( "LOOP" to "LOOP STOP/DISABLE/START/ENABLE/RESUME/STATUS\nLOOP SUSPEND 20", "TREATMENTS" to "TREATMENTS REFRESH", "NSCLIENT" to "NSCLIENT RESTART", - "PUMP" to "PUMP", + "PUMP" to "PUMP\nPUMP CONNECT\nPUMP DISCONNECT 30\n", "BASAL" to "BASAL STOP/CANCEL\nBASAL 0.3\nBASAL 0.3 20\nBASAL 30%\nBASAL 30% 20\n", "BOLUS" to "BOLUS 1.2\nBOLUS 1.2 MEAL", "EXTENDED" to "EXTENDED STOP/CANCEL\nEXTENDED 2 120", @@ -226,7 +228,8 @@ class SmsCommunicatorPlugin @Inject constructor( if (splitted.size == 2) processNSCLIENT(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) "PUMP" -> - if (splitted.size == 1) processPUMP(receivedSms) + if (!remoteCommandsAllowed && splitted.size > 1) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) + else if (splitted.size <= 3) processPUMP(splitted, receivedSms) else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) "PROFILE" -> if (!remoteCommandsAllowed) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_remotecommandnotallowed))) @@ -306,13 +309,20 @@ class SmsCommunicatorPlugin @Inject constructor( when (splitted[1].toUpperCase(Locale.getDefault())) { "DISABLE", "STOP" -> { if (loopPlugin.isEnabled(PluginType.LOOP)) { - loopPlugin.setPluginEnabled(PluginType.LOOP, false) - commandQueue.cancelTempBasal(true, object : Callback() { + val passCode = generatePasscode() + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopdisablereplywithcode), passCode) + receivedSms.processed = true + messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { override fun run() { - rxBus.send(EventRefreshOverview("SMS_LOOP_STOP")) - val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + - resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) - sendSMS(Sms(receivedSms.phoneNumber, replyText)) + loopPlugin.setPluginEnabled(PluginType.LOOP, false) + commandQueue.cancelTempBasal(true, object : Callback() { + override fun run() { + rxBus.send(EventRefreshOverview("SMS_LOOP_STOP")) + val replyText = resourceHelper.gs(R.string.smscommunicator_loophasbeendisabled) + " " + + resourceHelper.gs(if (result.success) R.string.smscommunicator_tempbasalcanceled else R.string.smscommunicator_tempbasalcancelfailed) + sendSMS(Sms(receivedSms.phoneNumber, replyText)) + } + }) } }) } else @@ -322,9 +332,16 @@ class SmsCommunicatorPlugin @Inject constructor( "ENABLE", "START" -> { if (!loopPlugin.isEnabled(PluginType.LOOP)) { - loopPlugin.setPluginEnabled(PluginType.LOOP, true) - sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled))) - rxBus.send(EventRefreshOverview("SMS_LOOP_START")) + val passCode = generatePasscode() + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopenablereplywithcode), passCode) + receivedSms.processed = true + messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { + override fun run() { + loopPlugin.setPluginEnabled(PluginType.LOOP, true) + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loophasbeenenabled))) + rxBus.send(EventRefreshOverview("SMS_LOOP_START")) + } + }) } else sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopisenabled))) receivedSms.processed = true @@ -341,9 +358,16 @@ class SmsCommunicatorPlugin @Inject constructor( } "RESUME" -> { - rxBus.send(EventRefreshOverview("SMS_LOOP_RESUME")) - loopPlugin.createOfflineEvent(0) - sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopresumed))) + val passCode = generatePasscode() + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_loopresumereplywithcode), passCode) + receivedSms.processed = true + messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { + override fun run() { + rxBus.send(EventRefreshOverview("SMS_LOOP_RESUME")) + loopPlugin.createOfflineEvent(0) + sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_loopresumed))) + } + }) } "SUSPEND" -> { @@ -418,20 +442,66 @@ class SmsCommunicatorPlugin @Inject constructor( sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) } - private fun processPUMP(receivedSms: Sms) { - commandQueue.readStatus("SMS", object : Callback() { - override fun run() { - val pump = activePlugin.activePump - if (result.success) { - val reply = pump.shortStatus(true) - sendSMS(Sms(receivedSms.phoneNumber, reply)) - } else { - val reply = resourceHelper.gs(R.string.readstatusfailed) - sendSMS(Sms(receivedSms.phoneNumber, reply)) + private fun processPUMP(splitted: Array, receivedSms: Sms) { + if (splitted.size == 1) { + commandQueue.readStatus("SMS", object : Callback() { + override fun run() { + val pump = activePlugin.activePump + if (result.success) { + val reply = pump.shortStatus(true) + sendSMS(Sms(receivedSms.phoneNumber, reply)) + } else { + val reply = resourceHelper.gs(R.string.readstatusfailed) + sendSMS(Sms(receivedSms.phoneNumber, reply)) + } } + }) + receivedSms.processed = true + } else if ((splitted.size == 2) && (splitted[1].equals("CONNECT", ignoreCase = true))) { + val passCode = generatePasscode() + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpconnectwithcode), passCode) + receivedSms.processed = true + messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { + override fun run() { + commandQueue.cancelTempBasal(true, object : Callback() { + override fun run() { + if (!result.success) { + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_pumpconnectfail))) + } else { + loopPlugin.suspendTo(0L) + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_reconnect))) + rxBus.send(EventRefreshOverview("SMS_PUMP_START")) + loopPlugin.createOfflineEvent(0) + } + } + }) + } + }) + } else if ((splitted.size == 3) && (splitted[1].equals("DISCONNECT", ignoreCase = true))) { + var duration = SafeParse.stringToInt(splitted[2]) + duration = Math.max(0, duration) + duration = Math.min(120, duration) + if (duration == 0) { + receivedSms.processed = true + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_wrongduration))) + return + } else { + val passCode = generatePasscode() + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_pumpdisconnectwithcode), duration, passCode) + receivedSms.processed = true + messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction() { + override fun run() { + val profile = profileFunction.getProfile() + loopPlugin.disconnectPump(duration, profile) + rxBus.send(EventRefreshOverview("SMS_PUMP_DISCONNECT")) + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.smscommunicator_pumpdisconnected))) + } + }) } - }) - receivedSms.processed = true + } else { + sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) + return + } } private fun processPROFILE(splitted: Array, receivedSms: Sms) { // load profiles @@ -612,7 +682,7 @@ class SmsCommunicatorPlugin @Inject constructor( override fun run() { if (result.success) { var replyText = String.format(resourceHelper.gs(R.string.smscommunicator_extendedset), aDouble, duration) - if (Config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) + if (config.APS) replyText += "\n" + resourceHelper.gs(R.string.loopsuspended) replyText += "\n" + activePlugin.activePump.shortStatus(true) sendSMSToAllNumbers(Sms(receivedSms.phoneNumber, replyText)) } else { @@ -713,7 +783,7 @@ class SmsCommunicatorPlugin @Inject constructor( if (grams == 0) sendSMS(Sms(receivedSms.phoneNumber, resourceHelper.gs(R.string.wrongformat))) else { val passCode = generatePasscode() - val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, DateUtil.timeString(time), passCode) + val reply = String.format(resourceHelper.gs(R.string.smscommunicator_carbsreplywithcode), grams, dateUtil.timeString(time), passCode) receivedSms.processed = true messageToConfirm = AuthRequest(injector, receivedSms, reply, passCode, object : SmsAction(grams, time) { override fun run() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt index 6c120fc576..faaa1b40d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/TidepoolUploader.kt @@ -38,7 +38,8 @@ class TidepoolUploader @Inject constructor( private val resourceHelper: ResourceHelper, private val sp: SP, private val uploadChunk: UploadChunk, - private val activePlugin: ActivePluginProvider + private val activePlugin: ActivePluginProvider, + private val dateUtil: DateUtil ) { private var wl: PowerManager.WakeLock? = null @@ -233,7 +234,7 @@ class TidepoolUploader @Inject constructor( private fun uploadNext() { if (uploadChunk.getLastEnd() < DateUtil.now() - T.mins(1).msecs()) { SystemClock.sleep(3000) - aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + DateUtil.dateAndTimeString(uploadChunk.getLastEnd())) + aapsLogger.debug(LTag.TIDEPOOL, "Restarting doUpload. Last: " + dateUtil.dateAndTimeString(uploadChunk.getLastEnd())) doUpload() } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt index 9c5bfb9aad..4062f27bd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/comm/UploadChunk.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.tidepool.elements.* import info.nightscout.androidaps.plugins.general.tidepool.events.EventTidepoolStatus import info.nightscout.androidaps.plugins.general.tidepool.utils.GsonInstance @@ -29,7 +29,8 @@ class UploadChunk @Inject constructor( private val aapsLogger: AAPSLogger, private val profileFunction: ProfileFunction, private val treatmentsPlugin: TreatmentsPlugin, - private val activePlugin: ActivePluginProvider + private val activePlugin: ActivePluginProvider, + private val dateUtil: DateUtil ) { private val MAX_UPLOAD_SIZE = T.days(7).msecs() // don't change this @@ -51,9 +52,9 @@ class UploadChunk @Inject constructor( operator fun get(start: Long, end: Long): String { - aapsLogger.debug(LTag.TIDEPOOL, "Syncing data between: " + DateUtil.dateAndTimeString(start) + " -> " + DateUtil.dateAndTimeString(end)) + aapsLogger.debug(LTag.TIDEPOOL, "Syncing data between: " + dateUtil.dateAndTimeString(start) + " -> " + dateUtil.dateAndTimeString(end)) if (end <= start) { - aapsLogger.debug(LTag.TIDEPOOL, "End is <= start: " + DateUtil.dateAndTimeString(start) + " " + DateUtil.dateAndTimeString(end)) + aapsLogger.debug(LTag.TIDEPOOL, "End is <= start: " + dateUtil.dateAndTimeString(start) + " " + dateUtil.dateAndTimeString(end)) return "" } if (end - start > MAX_UPLOAD_SIZE) { @@ -85,11 +86,11 @@ class UploadChunk @Inject constructor( fun setLastEnd(time: Long) { if (time > getLastEnd()) { sp.putLong(R.string.key_tidepool_last_end, time) - val friendlyEnd = DateUtil.dateAndTimeString(time) + val friendlyEnd = dateUtil.dateAndTimeString(time) rxBus.send(EventTidepoolStatus(("Marking uploaded data up to $friendlyEnd"))) - aapsLogger.debug(LTag.TIDEPOOL, "Updating last end to: " + DateUtil.dateAndTimeString(time)) + aapsLogger.debug(LTag.TIDEPOOL, "Updating last end to: " + dateUtil.dateAndTimeString(time)) } else { - aapsLogger.debug(LTag.TIDEPOOL, "Cannot set last end to: " + DateUtil.dateAndTimeString(time) + " vs " + DateUtil.dateAndTimeString(getLastEnd())) + aapsLogger.debug(LTag.TIDEPOOL, "Cannot set last end to: " + dateUtil.dateAndTimeString(time) + " vs " + dateUtil.dateAndTimeString(getLastEnd())) } } @@ -129,7 +130,7 @@ class UploadChunk @Inject constructor( } - internal fun getBgReadings(start: Long, end: Long): List { + private fun getBgReadings(start: Long, end: Long): List { val readings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, end, true) val selection = SensorGlucoseElement.fromBgReadings(readings) if (selection.isNotEmpty()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt index 4297e24420..50e07a4096 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BasalElement.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import java.util.* class BasalElement(tbr: TemporaryBasal, private val profileFunction: ProfileFunction) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt index 3d8dcbe964..f437018994 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/BolusElement.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import java.util.* class BolusElement(treatment: Treatment) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt index d7641862fe..87aba24d1c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/elements/WizardElement.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.general.tidepool.elements import com.google.gson.annotations.Expose -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import java.util.* class WizardElement(treatment: Treatment) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt index f1c58029d1..3aa96ae31d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt @@ -7,6 +7,7 @@ import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.CareportalEvent @@ -20,14 +21,13 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin +import info.nightscout.androidaps.danar.DanaRPlugin +import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin +import info.nightscout.androidaps.danars.DanaRSPlugin +import info.nightscout.androidaps.danaRv2.DanaRv2Plugin import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin import info.nightscout.androidaps.plugins.treatments.CarbsGenerator import info.nightscout.androidaps.queue.Callback @@ -65,9 +65,11 @@ class ActionStringHandler @Inject constructor( private val danaRKoreanPlugin: DanaRKoreanPlugin, private val danaRv2Plugin: DanaRv2Plugin, private val danaRSPlugin: DanaRSPlugin, - private val danaRPump: DanaRPump, + private val danaPump: DanaPump, private val hardLimits: HardLimits, - private val carbsGenerator: CarbsGenerator + private val carbsGenerator: CarbsGenerator, + private val dateUtil: DateUtil, + private val config: Config ) { private val TIMEOUT = 65 * 1000 @@ -84,7 +86,7 @@ class ActionStringHandler @Inject constructor( var rMessage = "" var rAction = "" // do the parsing and check constraints - val act = actionString.split("\\s+").toTypedArray() + val act = actionString.split("\\s+".toRegex()).toTypedArray() if ("fillpreset" == act[0]) { ///////////////////////////////////// PRIME/FILL val amount: Double = if ("1" == act[1]) { sp.getDouble("fill_button1", 0.3) @@ -278,7 +280,7 @@ class ActionStringHandler @Inject constructor( val starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000 val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() rMessage += resourceHelper.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" - rMessage += "\n" + resourceHelper.gs(R.string.time) + ": " + DateUtil.timeString(starttimestamp) + rMessage += "\n" + resourceHelper.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp) rMessage += "\n" + resourceHelper.gs(R.string.duration) + ": " + duration + "h" if (carbsAfterConstraints - carbs != 0) { rMessage += "\n" + resourceHelper.gs(R.string.constraintapllied) @@ -324,7 +326,7 @@ class ActionStringHandler @Inject constructor( message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "\n" } else if (pump is DanaRPlugin) { - val tdd = danaRPump.dailyTotalUnits + val tdd = danaPump.dailyTotalUnits message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" message += "\n" } @@ -409,8 +411,8 @@ class ActionStringHandler @Inject constructor( ret += "APS: " + (aps as PluginBase).name val lastRun = loopPlugin.lastRun if (lastRun != null) { - ret += "\nLast Run: " + DateUtil.timeString(lastRun.lastAPSRun) - if (lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + DateUtil.timeString(lastRun.lastTBREnact) + ret += "\nLast Run: " + dateUtil.timeString(lastRun.lastAPSRun) + if (lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + dateUtil.timeString(lastRun.lastTBREnact) } } else { ret += "LOOP DISABLED\n" @@ -422,7 +424,7 @@ class ActionStringHandler @Inject constructor( private val targetsStatus: String get() { var ret = "" - if (!Config.APS) { + if (!config.APS) { return "Targets only apply in APS mode!" } val profile = profileFunction.getProfile() ?: return "No profile set :(" @@ -430,7 +432,7 @@ class ActionStringHandler @Inject constructor( val tempTarget = activePlugin.activeTreatments.tempTargetFromHistory if (tempTarget != null) { ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.low, tempTarget.low, Constants.MGDL, profileFunction.getUnits()) - ret += "\nuntil: " + DateUtil.timeString(tempTarget.originalEnd()) + ret += "\nuntil: " + dateUtil.timeString(tempTarget.originalEnd()) ret += "\n\n" } ret += "DEFAULT RANGE: " @@ -442,7 +444,7 @@ class ActionStringHandler @Inject constructor( private val oAPSResultStatus: String get() { var ret = "" - if (!Config.APS) + if (!config.APS) return "Only apply in APS mode!" val usedAPS = activePlugin.activeAPS val result = usedAPS.lastAPSResult ?: return "Last result not available!" @@ -468,7 +470,7 @@ class ActionStringHandler @Inject constructor( if (System.currentTimeMillis() - lastSentTimestamp > TIMEOUT) return lastConfirmActionString = null // do the parsing, check constraints and enact! - val act = actionString.split("\\s+").toTypedArray() + val act = actionString.split("\\s+".toRegex()).toTypedArray() if ("fill" == act[0]) { val amount = SafeParse.stringToDouble(act[1]) val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index abff22eae3..02b201f5ab 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -104,7 +104,7 @@ class WearPlugin @Inject constructor( .observeOn(Schedulers.io()) .subscribe({ event: EventDismissBolusProgressIfRunning -> if (event.result == null) return@subscribe - val status: String = if (event.result.success) { + val status: String = if (event.result!!.success) { resourceHelper.gs(R.string.success) } else { resourceHelper.gs(R.string.nosuccess) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java index b60dd1f1fd..88228d1018 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java @@ -42,13 +42,13 @@ import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.general.wear.WearPlugin; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -72,6 +72,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog @Inject public TreatmentsPlugin treatmentsPlugin; @Inject public ActionStringHandler actionStringHandler; @Inject ReceiverStatusStore receiverStatusStore; + @Inject Config config; public static final String ACTION_RESEND = WatchUpdaterService.class.getName().concat(".Resend"); public static final String ACTION_OPEN_SETTINGS = WatchUpdaterService.class.getName().concat(".OpenSettings"); @@ -151,7 +152,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog if (wearIntegration()) { handler.post(() -> { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { if (ACTION_RESEND.equals(action)) { resendData(); } else if (ACTION_OPEN_SETTINGS.equals(action)) { @@ -179,7 +180,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog sendData(); } } else { - googleApiClient.connect(); + if (googleApiClient != null) googleApiClient.connect(); } }); } @@ -297,9 +298,11 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private DataMap dataMapSingleBG(BgReading lastBG, GlucoseStatus glucoseStatus) { String units = profileFunction.getUnits(); - - double lowLine = defaultValueHelper.determineLowLine(); - double highLine = defaultValueHelper.determineHighLine(); + double convert2MGDL = 1.0; + if (units.equals(Constants.MMOL)) + convert2MGDL = Constants.MMOLL_TO_MGDL; + double lowLine = defaultValueHelper.determineLowLine()*convert2MGDL; + double highLine = defaultValueHelper.determineHighLine()*convert2MGDL; long sgvLevel = 0L; if (lastBG.value > highLine) { @@ -530,11 +533,12 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } - final LoopPlugin.LastRun finalLastRun = loopPlugin.lastRun; - if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.request.hasPredictions && finalLastRun.constraintsProcessed != null) { - List predArray = finalLastRun.constraintsProcessed.getPredictions(); + final LoopPlugin.LastRun finalLastRun = loopPlugin.getLastRun(); + if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().hasPredictions && finalLastRun.getConstraintsProcessed() != null) { + List predArray = finalLastRun.getConstraintsProcessed().getPredictions(); if (!predArray.isEmpty()) { + final String units = profileFunction.getUnits(); for (BgReading bg : predArray) { if (bg.value < 40) continue; predictions.add(predictionMap(bg.date, bg.value, bg.getPredectionColor())); @@ -590,7 +594,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private void sendNotification() { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(OPEN_SETTINGS_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); @@ -604,7 +608,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private void sendBolusProgress(int progresspercent, String status) { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(BOLUS_PROGRESS_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); @@ -620,7 +624,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private void sendActionConfirmationRequest(String title, String message, String actionstring) { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CONFIRMATION_REQUEST_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); @@ -640,7 +644,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private void sendChangeConfirmationRequest(String title, String message, String actionstring) { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CHANGECONFIRMATION_REQUEST_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); @@ -660,7 +664,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private void sendCancelNotificationRequest(String actionstring) { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { PutDataMapRequest dataMapRequest = PutDataMapRequest.create(ACTION_CANCELNOTIFICATION_REQUEST_PATH); //unique content dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); @@ -679,7 +683,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog private void sendStatus() { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { Profile profile = profileFunction.getProfile(); String status = resourceHelper.gs(R.string.noprofile); String iobSum, iobDetail, cobString, currentBasal, bgiString; @@ -712,9 +716,9 @@ public class WatchUpdaterService extends WearableListenerService implements Goog long openApsStatus; //OpenAPS status - if (Config.APS) { + if (config.getAPS()) { //we are AndroidAPS - openApsStatus = loopPlugin.lastRun != null && loopPlugin.lastRun.lastTBREnact != 0 ? loopPlugin.lastRun.lastTBREnact : -1; + openApsStatus = loopPlugin.getLastRun() != null && loopPlugin.getLastRun().getLastTBREnact() != 0 ? loopPlugin.getLastRun().getLastTBREnact() : -1; } else { //NSClient or remote openApsStatus = NSDeviceStatus.getOpenApsTimestamp(); @@ -743,7 +747,7 @@ public class WatchUpdaterService extends WearableListenerService implements Goog } private void sendPreferences() { - if (googleApiClient.isConnected()) { + if (googleApiClient != null && googleApiClient.isConnected()) { boolean wearcontrol = sp.getBoolean("wearcontrol", false); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt index 79a8dd486b..067c444eaa 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/xdripStatusline/StatusLinePlugin.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.utils.DecimalFormatter diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.java b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.java index fd8564cf73..cb8dabdde5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/ActivityGraph.java @@ -12,7 +12,7 @@ import java.util.ArrayList; import java.util.List; import info.nightscout.androidaps.data.Iob; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt index e5a92588c3..935fad3ccb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePlugin.kt @@ -9,10 +9,10 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +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.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.utils.resources.ResourceHelper /** diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt index 1ae2869b6e..f1804cbd43 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPlugin.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt index 634ad2df5d..770e7f1f91 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPlugin.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt index e2048d7a65..60f07c3203 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPlugin.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.interfaces.InsulinInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/InMemoryGlucoseValue.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/InMemoryGlucoseValue.kt new file mode 100644 index 0000000000..497117764e --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/InMemoryGlucoseValue.kt @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.iob.iobCobCalculator + +import info.nightscout.androidaps.db.BgReading + +class InMemoryGlucoseValue @JvmOverloads constructor(var timestamp: Long = 0L, var value: Double = 0.0, var interpolated : Boolean = false) { + + constructor(gv: BgReading) : this(gv.date, gv.value) + // var generated : value doesn't correspond to real value with timestamp close to real BG +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index c35e3797dc..50a65dc689 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java @@ -30,18 +30,21 @@ import info.nightscout.androidaps.events.EventNewBG; import info.nightscout.androidaps.events.EventNewBasalProfile; import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryBgData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -55,7 +58,7 @@ import io.reactivex.schedulers.Schedulers; import static info.nightscout.androidaps.utils.DateUtil.now; @Singleton -public class IobCobCalculatorPlugin extends PluginBase { +public class IobCobCalculatorPlugin extends PluginBase implements IobCobCalculatorInterface { private final HasAndroidInjector injector; private final SP sp; private final RxBusWrapper rxBus; @@ -67,6 +70,7 @@ public class IobCobCalculatorPlugin extends PluginBase { private final SensitivityAAPSPlugin sensitivityAAPSPlugin; private final SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; private final FabricPrivacy fabricPrivacy; + private final DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -75,8 +79,13 @@ public class IobCobCalculatorPlugin extends PluginBase { private LongSparseArray autosensDataTable = new LongSparseArray<>(); // oldest at index 0 private LongSparseArray basalDataTable = new LongSparseArray<>(); // oldest at index 0 + // we need to make sure that bucketed_data will always have the same timestamp for correct use of cached values + // once referenceTime != null all bucketed data should be (x * 5min) from referenceTime + Long referenceTime = null; + private Boolean lastUsed5minCalculation = null; // true if used 5min bucketed data + private volatile List bgReadings = null; // newest at index 0 - private volatile List bucketed_data = null; + private volatile List bucketed_data = null; private final Object dataLock = new Object(); @@ -96,7 +105,8 @@ public class IobCobCalculatorPlugin extends PluginBase { SensitivityOref1Plugin sensitivityOref1Plugin, SensitivityAAPSPlugin sensitivityAAPSPlugin, SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.GENERAL) @@ -117,6 +127,7 @@ public class IobCobCalculatorPlugin extends PluginBase { this.sensitivityAAPSPlugin = sensitivityAAPSPlugin; this.sensitivityWeightedAveragePlugin = sensitivityWeightedAveragePlugin; this.fabricPrivacy = fabricPrivacy; + this.dateUtil = dateUtil; } @Override @@ -129,9 +140,8 @@ public class IobCobCalculatorPlugin extends PluginBase { .subscribe(event -> { stopCalculation("onEventConfigBuilderChange"); synchronized (dataLock) { - getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); + getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of configuration change."); + resetData(); } runCalculation("onEventConfigBuilderChange", System.currentTimeMillis(), false, true, event); }, fabricPrivacy::logException) @@ -146,15 +156,13 @@ public class IobCobCalculatorPlugin extends PluginBase { } stopCalculation("onNewProfile"); synchronized (dataLock) { - getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); - basalDataTable = new LongSparseArray<>(); + getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of new profile."); + resetData(); } runCalculation("onNewProfile", System.currentTimeMillis(), false, true, event); }, fabricPrivacy::logException) ); - // EventNewBG + // EventNewBG .... cannot be used for invalidating because only event with last BG is fired disposable.add(rxBus .toObservable(EventNewBG.class) .observeOn(Schedulers.io()) @@ -179,10 +187,8 @@ public class IobCobCalculatorPlugin extends PluginBase { ) { stopCalculation("onEventPreferenceChange"); synchronized (dataLock) { - getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records" + " BasalData: " + basalDataTable.size() + " records"); - iobTable = new LongSparseArray<>(); - autosensDataTable = new LongSparseArray<>(); - basalDataTable = new LongSparseArray<>(); + getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data because of preference change."); + resetData(); } runCalculation("onEventPreferenceChange", System.currentTimeMillis(), false, true, event); } @@ -198,7 +204,13 @@ public class IobCobCalculatorPlugin extends PluginBase { disposable.add(rxBus .toObservable(EventNewHistoryData.class) .observeOn(Schedulers.io()) - .subscribe(this::newHistoryData, fabricPrivacy::logException) + .subscribe(event -> newHistoryData(event, false), fabricPrivacy::logException) + ); + // EventNewHistoryBgData + disposable.add(rxBus + .toObservable(EventNewHistoryBgData.class) + .observeOn(Schedulers.io()) + .subscribe(event -> newHistoryData(new EventNewHistoryData(event.getTimestamp()), true), fabricPrivacy::logException) ); } @@ -220,7 +232,7 @@ public class IobCobCalculatorPlugin extends PluginBase { this.bgReadings = bgReadings; } - public List getBucketedData() { + public List getBucketedData() { return bucketed_data; } @@ -236,6 +248,19 @@ public class IobCobCalculatorPlugin extends PluginBase { return rounded; } + long adjustToReferenceTime(long someTime) { + if (referenceTime == null) { + referenceTime = someTime; + return someTime; + } + long diff = Math.abs(someTime - referenceTime); + diff %= T.mins(5).msecs(); + if (diff > T.mins(2).plus(T.secs(30)).msecs()) + diff = diff - T.mins(5).msecs(); + long newTime = someTime + diff; + return newTime; + } + void loadBgData(long to) { Profile profile = profileFunction.getProfile(to); double dia = Constants.defaultDIA; @@ -245,10 +270,10 @@ public class IobCobCalculatorPlugin extends PluginBase { // if close to now expect there can be some readings with time in close future (caused by wrong time setting) // so read all records bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, false); - getAapsLogger().debug(LTag.AUTOSENS, "BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start)); + getAapsLogger().debug(LTag.AUTOSENS, "BG data loaded. Size: " + bgReadings.size() + " Start date: " + dateUtil.dateAndTimeString(start)); } else { bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime(start, to, false); - getAapsLogger().debug(LTag.AUTOSENS, "BG data loaded. Size: " + bgReadings.size() + " Start date: " + DateUtil.dateAndTimeString(start) + " End date: " + DateUtil.dateAndTimeString(to)); + getAapsLogger().debug(LTag.AUTOSENS, "BG data loaded. Size: " + bgReadings.size() + " Start date: " + dateUtil.dateAndTimeString(start) + " End date: " + dateUtil.dateAndTimeString(to)); } } @@ -279,7 +304,23 @@ public class IobCobCalculatorPlugin extends PluginBase { } } + private void resetData() { + synchronized (dataLock) { + iobTable = new LongSparseArray<>(); + autosensDataTable = new LongSparseArray<>(); + basalDataTable = new LongSparseArray<>(); + absIobTable = new LongSparseArray<>(); + } + } + public void createBucketedData() { + boolean fiveMinData = isAbout5minData(); + if (lastUsed5minCalculation != null && lastUsed5minCalculation != fiveMinData) { + // changing mode => clear cache + getAapsLogger().debug("Invalidating cached data because of changed mode."); + resetData(); + } + lastUsed5minCalculation = fiveMinData; if (isAbout5minData()) createBucketedData5min(); else @@ -320,6 +361,8 @@ public class IobCobCalculatorPlugin extends PluginBase { bucketed_data = new ArrayList<>(); long currentTime = bgReadings.get(0).date - bgReadings.get(0).date % T.mins(5).msecs(); + currentTime = adjustToReferenceTime(currentTime); + getAapsLogger().debug("Adjusted time " + dateUtil.dateAndTimeAndSecondsString(currentTime)); //log.debug("First reading: " + new Date(currentTime).toLocaleString()); while (true) { @@ -330,15 +373,13 @@ public class IobCobCalculatorPlugin extends PluginBase { break; if (older.date == newer.date) { // direct hit - bucketed_data.add(newer); + bucketed_data.add(new InMemoryGlucoseValue(newer)); } else { double bgDelta = newer.value - older.value; long timeDiffToNew = newer.date - currentTime; double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta; - BgReading newBgreading = new BgReading(injector); - newBgreading.date = currentTime; - newBgreading.value = Math.round(currentBg); + InMemoryGlucoseValue newBgreading = new InMemoryGlucoseValue(currentTime, Math.round(currentBg), true); bucketed_data.add(newBgreading); //log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")"); } @@ -355,7 +396,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } bucketed_data = new ArrayList<>(); - bucketed_data.add(bgReadings.get(0)); + bucketed_data.add(new InMemoryGlucoseValue(bgReadings.get(0))); getAapsLogger().debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgReadings.get(0).date) + " lastbgTime: " + "none-first-value" + " " + bgReadings.get(0).toString()); int j = 0; for (int i = 1; i < bgReadings.size(); ++i) { @@ -376,12 +417,10 @@ public class IobCobCalculatorPlugin extends PluginBase { while (elapsed_minutes > 5) { nextbgTime = lastbgTime - 5 * 60 * 1000; j++; - BgReading newBgreading = new BgReading(injector); - newBgreading.date = nextbgTime; double gapDelta = bgReadings.get(i).value - lastbg; //console.error(gapDelta, lastbg, elapsed_minutes); double nextbg = lastbg + (5d / elapsed_minutes * gapDelta); - newBgreading.value = Math.round(nextbg); + InMemoryGlucoseValue newBgreading = new InMemoryGlucoseValue(nextbgTime, Math.round(nextbg), true); //console.error("Interpolated", bucketed_data[j]); bucketed_data.add(newBgreading); getAapsLogger().debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString()); @@ -391,38 +430,37 @@ public class IobCobCalculatorPlugin extends PluginBase { lastbgTime = nextbgTime; } j++; - BgReading newBgreading = new BgReading(injector); - newBgreading.value = bgReadings.get(i).value; - newBgreading.date = bgTime; + InMemoryGlucoseValue newBgreading = new InMemoryGlucoseValue(bgTime, bgReadings.get(i).value); bucketed_data.add(newBgreading); getAapsLogger().debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString()); } else if (Math.abs(elapsed_minutes) > 2) { j++; - BgReading newBgreading = new BgReading(injector); - newBgreading.value = bgReadings.get(i).value; - newBgreading.date = bgTime; + InMemoryGlucoseValue newBgreading = new InMemoryGlucoseValue(bgTime, bgReadings.get(i).value); bucketed_data.add(newBgreading); getAapsLogger().debug(LTag.AUTOSENS, "Adding. bgTime: " + DateUtil.toISOString(bgTime) + " lastbgTime: " + DateUtil.toISOString(lastbgTime) + " " + newBgreading.toString()); } else { - bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2; + bucketed_data.get(j).setValue((bucketed_data.get(j).getValue() + bgReadings.get(i).value) / 2); //log.error("***** Average"); } } // Normalize bucketed data + InMemoryGlucoseValue oldest = bucketed_data.get(bucketed_data.size() - 1); + oldest.setTimestamp(adjustToReferenceTime(oldest.getTimestamp())); + getAapsLogger().debug("Adjusted time " + dateUtil.dateAndTimeAndSecondsString(oldest.getTimestamp())); for (int i = bucketed_data.size() - 2; i >= 0; i--) { - BgReading current = bucketed_data.get(i); - BgReading previous = bucketed_data.get(i + 1); - long msecDiff = current.date - previous.date; + InMemoryGlucoseValue current = bucketed_data.get(i); + InMemoryGlucoseValue previous = bucketed_data.get(i + 1); + long msecDiff = current.getTimestamp() - previous.getTimestamp(); long adjusted = (msecDiff - T.mins(5).msecs()) / 1000; - getAapsLogger().debug(LTag.AUTOSENS, "Adjusting bucketed data time. Current: " + DateUtil.toISOString(current.date) + " to: " + DateUtil.toISOString(previous.date + T.mins(5).msecs()) + " by " + adjusted + " sec"); + getAapsLogger().debug(LTag.AUTOSENS, "Adjusting bucketed data time. Current: " + dateUtil.dateAndTimeAndSecondsString(current.getTimestamp()) + " to: " + dateUtil.dateAndTimeAndSecondsString(previous.getTimestamp() + T.mins(5).msecs()) + " by " + adjusted + " sec"); if (Math.abs(adjusted) > 90) { // too big adjustment, fallback to non 5 min data getAapsLogger().debug(LTag.AUTOSENS, "Fallback to non 5 min data"); createBucketedDataRecalculated(); return; } - current.date = previous.date + T.mins(5).msecs(); + current.setTimestamp(previous.getTimestamp() + T.mins(5).msecs()); } getAapsLogger().debug(LTag.AUTOSENS, "Bucketed data created. Size: " + bucketed_data.size()); @@ -438,7 +476,7 @@ public class IobCobCalculatorPlugin extends PluginBase { if (limitDataToOldestAvailable) { getBGDataFrom = Math.max(oldestDataAvailable, (long) (from - T.hours(1).msecs() * (24 + dia))); if (getBGDataFrom == oldestDataAvailable) - getAapsLogger().debug(LTag.AUTOSENS, "Limiting data to oldest available temps: " + DateUtil.dateAndTimeString(oldestDataAvailable)); + getAapsLogger().debug(LTag.AUTOSENS, "Limiting data to oldest available temps: " + dateUtil.dateAndTimeAndSecondsString(oldestDataAvailable)); } else getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); return getBGDataFrom; @@ -539,8 +577,8 @@ public class IobCobCalculatorPlugin extends PluginBase { if (bucketed_data == null) return null; for (int index = 0; index < bucketed_data.size(); index++) { - if (bucketed_data.get(index).date <= time) - return bucketed_data.get(index).date; + if (bucketed_data.get(index).getTimestamp() <= time) + return bucketed_data.get(index).getTimestamp(); } return null; } @@ -673,7 +711,7 @@ public class IobCobCalculatorPlugin extends PluginBase { return null; } if (data.time < System.currentTimeMillis() - 11 * 60 * 1000) { - getAapsLogger().debug(LTag.AUTOSENS, "AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + DateUtil.dateAndTimeString(data.time)); + getAapsLogger().debug(LTag.AUTOSENS, "AUTOSENSDATA null: data is old (" + reason + ") size()=" + autosensDataTable.size() + " lastdata=" + dateUtil.dateAndTimeAndSecondsString(data.time)); return null; } else { getAapsLogger().debug(LTag.AUTOSENS, "AUTOSENSDATA (" + reason + ") " + data.toString()); @@ -681,9 +719,10 @@ public class IobCobCalculatorPlugin extends PluginBase { } } + @Override public String lastDataTime() { if (autosensDataTable.size() > 0) - return DateUtil.dateAndTimeString(autosensDataTable.valueAt(autosensDataTable.size() - 1).time); + return dateUtil.dateAndTimeAndSecondsString(autosensDataTable.valueAt(autosensDataTable.size() - 1).time); else return "autosensDataTable empty"; } @@ -716,7 +755,6 @@ public class IobCobCalculatorPlugin extends PluginBase { result.boluses += treatment.insulin; } } - if (t > absorptionTime_ago && t <= now) { if (treatment.carbs >= 1) { result.carbs += treatment.carbs; @@ -805,27 +843,27 @@ public class IobCobCalculatorPlugin extends PluginBase { } public void runCalculation(String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { - getAapsLogger().debug(LTag.AUTOSENS, "Starting calculation thread: " + from + " to " + DateUtil.dateAndTimeString(end)); + getAapsLogger().debug(LTag.AUTOSENS, "Starting calculation thread: " + from + " to " + dateUtil.dateAndTimeAndSecondsString(end)); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (sensitivityOref1Plugin.isEnabled()) - thread = new IobCobOref1Thread(injector, from, end, bgDataReload, limitDataToOldestAvailable, cause); + thread = new IobCobOref1Thread(injector, this, treatmentsPlugin, from, end, bgDataReload, limitDataToOldestAvailable, cause); else - thread = new IobCobThread(injector, from, end, bgDataReload, limitDataToOldestAvailable, cause); + thread = new IobCobThread(injector, this, treatmentsPlugin, from, end, bgDataReload, limitDataToOldestAvailable, cause); thread.start(); } } // When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated - private void newHistoryData(EventNewHistoryData ev) { + private void newHistoryData(EventNewHistoryData ev, boolean bgDataReload) { //log.debug("Locking onNewHistoryData"); stopCalculation("onEventNewHistoryData"); synchronized (dataLock) { // clear up 5 min back for proper COB calculation long time = ev.getTime() - 5 * 60 * 1000L; - getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data to: " + DateUtil.dateAndTimeString(time)); + getAapsLogger().debug(LTag.AUTOSENS, "Invalidating cached data to: " + dateUtil.dateAndTimeAndSecondsString(time)); for (int index = iobTable.size() - 1; index >= 0; index--) { if (iobTable.keyAt(index) > time) { - getAapsLogger().debug(LTag.AUTOSENS, "Removing from iobTable: " + DateUtil.dateAndTimeString(iobTable.keyAt(index))); + getAapsLogger().debug(LTag.AUTOSENS, "Removing from iobTable: " + dateUtil.dateAndTimeAndSecondsString(iobTable.keyAt(index))); iobTable.removeAt(index); } else { break; @@ -833,7 +871,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } for (int index = absIobTable.size() - 1; index >= 0; index--) { if (absIobTable.keyAt(index) > time) { - getAapsLogger().debug(LTag.AUTOSENS, "Removing from absIobTable: " + DateUtil.dateAndTimeString(absIobTable.keyAt(index))); + getAapsLogger().debug(LTag.AUTOSENS, "Removing from absIobTable: " + dateUtil.dateAndTimeAndSecondsString(absIobTable.keyAt(index))); absIobTable.removeAt(index); } else { break; @@ -841,7 +879,7 @@ public class IobCobCalculatorPlugin extends PluginBase { } for (int index = autosensDataTable.size() - 1; index >= 0; index--) { if (autosensDataTable.keyAt(index) > time) { - getAapsLogger().debug(LTag.AUTOSENS, "Removing from autosensDataTable: " + DateUtil.dateAndTimeString(autosensDataTable.keyAt(index))); + getAapsLogger().debug(LTag.AUTOSENS, "Removing from autosensDataTable: " + dateUtil.dateAndTimeAndSecondsString(autosensDataTable.keyAt(index))); autosensDataTable.removeAt(index); } else { break; @@ -849,14 +887,14 @@ public class IobCobCalculatorPlugin extends PluginBase { } for (int index = basalDataTable.size() - 1; index >= 0; index--) { if (basalDataTable.keyAt(index) > time) { - getAapsLogger().debug(LTag.AUTOSENS, "Removing from basalDataTable: " + DateUtil.dateAndTimeString(basalDataTable.keyAt(index))); + getAapsLogger().debug(LTag.AUTOSENS, "Removing from basalDataTable: " + dateUtil.dateAndTimeAndSecondsString(basalDataTable.keyAt(index))); basalDataTable.removeAt(index); } else { break; } } } - runCalculation("onEventNewHistoryData", System.currentTimeMillis(), false, true, ev); + runCalculation("onEventNewHistoryData", System.currentTimeMillis(), bgDataReload, true, ev); //log.debug("Releasing onNewHistoryData"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java index 9478b9ed73..431d27f63c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Thread.java @@ -26,14 +26,17 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +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.plugins.iob.iobCobCalculator.data.AutosensData; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -60,15 +63,16 @@ public class IobCobOref1Thread extends Thread { @Inject ResourceHelper resourceHelper; @Inject ProfileFunction profileFunction; @Inject Context context; - @Inject ActivePluginProvider activePluginProvider; - @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @Inject BuildHelper buildHelper; @Inject Profiler profiler; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; 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; @@ -76,10 +80,12 @@ public class IobCobOref1Thread extends Thread { private PowerManager.WakeLock mWakeLock; - IobCobOref1Thread(HasAndroidInjector injector, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + IobCobOref1Thread(HasAndroidInjector injector, IobCobCalculatorPlugin iobCobCalculatorPlugin, TreatmentsPlugin treatmentsPlugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); injector.androidInjector().inject(this); this.injector = injector; + this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; + this.treatmentsPlugin = treatmentsPlugin; this.bgDataReload = bgDataReload; this.limitDataToOldestAvailable = limitDataToOldestAvailable; @@ -111,8 +117,9 @@ public class IobCobOref1Thread extends Thread { if (bgDataReload) { iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); + rxBus.send(new EventAutosensBgLoaded(cause)); } - List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); + List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { @@ -120,8 +127,8 @@ public class IobCobOref1Thread extends Thread { return; } - long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); + long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).getTimestamp()); + aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime)); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { @@ -134,7 +141,7 @@ public class IobCobOref1Thread extends Thread { return; } // check if data already exists - long bgTime = bucketed_data.get(i).date; + long bgTime = bucketed_data.get(i).getTimestamp(); bgTime = IobCobCalculatorPlugin.roundUpTime(bgTime); if (bgTime > IobCobCalculatorPlugin.roundUpTime(now())) continue; @@ -166,14 +173,14 @@ public class IobCobOref1Thread extends Thread { double bg; double avgDelta; double delta; - bg = bucketed_data.get(i).value; - if (bg < 39 || bucketed_data.get(i + 3).value < 39) { + bg = bucketed_data.get(i).getValue(); + if (bg < 39 || bucketed_data.get(i + 3).getValue() < 39) { aapsLogger.error("! value < 39"); continue; } autosensData.bg = bg; - delta = (bg - bucketed_data.get(i + 1).value); - avgDelta = (bg - bucketed_data.get(i + 3).value) / 3; + delta = (bg - bucketed_data.get(i + 1).getValue()); + avgDelta = (bg - bucketed_data.get(i + 3).getValue()) / 3; IobTotal iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTemps(bgTime, profile); @@ -237,10 +244,11 @@ public class IobCobOref1Thread extends Thread { } } - List recentCarbTreatments = activePluginProvider.getActiveTreatments().getCarbTreatments5MinBackFromHistory(bgTime); + List recentCarbTreatments = treatmentsPlugin.getCarbTreatments5MinBackFromHistory(bgTime); for (Treatment recentCarbTreatment : recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.carbs; - autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment)); + boolean isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled(); + autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment, isAAPSOrWeighted)); autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]"; } @@ -277,7 +285,8 @@ public class IobCobOref1Thread extends Thread { autosensData.uam = previous.uam; } - autosensData.removeOldCarbs(bgTime); + boolean isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled(); + autosensData.removeOldCarbs(bgTime, isAAPSOrWeighted); autosensData.cob += autosensData.carbsFromBolus; autosensData.mealCarbs += autosensData.carbsFromBolus; autosensData.deviation = deviation; @@ -358,7 +367,7 @@ public class IobCobOref1Thread extends Thread { // add an extra negative deviation if a high temptarget is running and exercise mode is set // TODO AS-FIX if (false && sp.getBoolean(R.string.key_high_temptarget_raises_sensitivity, SMBDefaults.high_temptarget_raises_sensitivity)) { - TempTarget tempTarget = activePluginProvider.getActiveTreatments().getTempTargetFromHistory(bgTime); + TempTarget tempTarget = treatmentsPlugin.getTempTargetFromHistory(bgTime); if (tempTarget != null && tempTarget.target() >= 100) { autosensData.extraDeviation.add(-(tempTarget.target() - 100) / 20); } @@ -375,7 +384,7 @@ public class IobCobOref1Thread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); + aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java index 48b9c2eb0a..d2d73c1ba9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobThread.java @@ -24,14 +24,17 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +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.plugins.iob.iobCobCalculator.data.AutosensData; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensBgLoaded; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress; import info.nightscout.androidaps.plugins.sensitivity.SensitivityAAPSPlugin; import info.nightscout.androidaps.plugins.sensitivity.SensitivityWeightedAveragePlugin; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -57,15 +60,16 @@ public class IobCobThread extends Thread { @Inject ResourceHelper resourceHelper; @Inject ProfileFunction profileFunction; @Inject Context context; - @Inject ActivePluginProvider activePluginProvider; - @Inject IobCobCalculatorPlugin iobCobCalculatorPlugin; @Inject SensitivityAAPSPlugin sensitivityAAPSPlugin; @Inject SensitivityWeightedAveragePlugin sensitivityWeightedAveragePlugin; @Inject BuildHelper buildHelper; @Inject Profiler profiler; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; 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; @@ -73,10 +77,12 @@ public class IobCobThread extends Thread { private PowerManager.WakeLock mWakeLock; - @Inject IobCobThread(HasAndroidInjector injector, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { + @Inject IobCobThread(HasAndroidInjector injector, IobCobCalculatorPlugin iobCobCalculatorPlugin, TreatmentsPlugin treatmentsPlugin, String from, long end, boolean bgDataReload, boolean limitDataToOldestAvailable, Event cause) { super(); injector.androidInjector().inject(this); this.injector = injector; + this.iobCobCalculatorPlugin = iobCobCalculatorPlugin; + this.treatmentsPlugin = treatmentsPlugin; this.bgDataReload = bgDataReload; this.limitDataToOldestAvailable = limitDataToOldestAvailable; @@ -108,8 +114,9 @@ public class IobCobThread extends Thread { if (bgDataReload) { iobCobCalculatorPlugin.loadBgData(end); iobCobCalculatorPlugin.createBucketedData(); + rxBus.send(new EventAutosensBgLoaded(cause)); } - List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); + List bucketed_data = iobCobCalculatorPlugin.getBucketedData(); LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); if (bucketed_data == null || bucketed_data.size() < 3) { @@ -117,8 +124,8 @@ public class IobCobThread extends Thread { return; } - long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); + long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).getTimestamp()); + aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + dateUtil.dateAndTimeString(prevDataTime)); AutosensData previous = autosensDataTable.get(prevDataTime); // start from oldest to be able sub cob for (int i = bucketed_data.size() - 4; i >= 0; i--) { @@ -131,7 +138,7 @@ public class IobCobThread extends Thread { return; } // check if data already exists - long bgTime = bucketed_data.get(i).date; + long bgTime = bucketed_data.get(i).getTimestamp(); bgTime = IobCobCalculatorPlugin.roundUpTime(bgTime); if (bgTime > IobCobCalculatorPlugin.roundUpTime(now())) continue; @@ -163,14 +170,14 @@ public class IobCobThread extends Thread { double bg; double avgDelta; double delta; - bg = bucketed_data.get(i).value; - if (bg < 39 || bucketed_data.get(i + 3).value < 39) { + bg = bucketed_data.get(i).getValue(); + if (bg < 39 || bucketed_data.get(i + 3).getValue() < 39) { aapsLogger.error("! value < 39"); continue; } autosensData.bg = bg; - delta = (bg - bucketed_data.get(i + 1).value); - avgDelta = (bg - bucketed_data.get(i + 3).value) / 3; + delta = (bg - bucketed_data.get(i + 1).getValue()); + avgDelta = (bg - bucketed_data.get(i + 3).getValue()) / 3; IobTotal iob = iobCobCalculatorPlugin.calculateFromTreatmentsAndTemps(bgTime, profile); @@ -234,10 +241,11 @@ public class IobCobThread extends Thread { } } - List recentCarbTreatments = activePluginProvider.getActiveTreatments().getCarbTreatments5MinBackFromHistory(bgTime); + List recentCarbTreatments = treatmentsPlugin.getCarbTreatments5MinBackFromHistory(bgTime); for (Treatment recentCarbTreatment : recentCarbTreatments) { autosensData.carbsFromBolus += recentCarbTreatment.carbs; - autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment)); + boolean isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled(); + autosensData.activeCarbsList.add(autosensData.new CarbsInPast(recentCarbTreatment, isAAPSOrWeighted)); autosensData.pastSensitivity += "[" + DecimalFormatter.to0Decimal(recentCarbTreatment.carbs) + "g]"; } @@ -268,7 +276,8 @@ public class IobCobThread extends Thread { autosensData.substractAbosorbedCarbs(); autosensData.usedMinCarbsImpact = totalMinCarbsImpact; } - autosensData.removeOldCarbs(bgTime); + boolean isAAPSOrWeighted = sensitivityAAPSPlugin.isEnabled() || sensitivityWeightedAveragePlugin.isEnabled(); + autosensData.removeOldCarbs(bgTime, isAAPSOrWeighted); autosensData.cob += autosensData.carbsFromBolus; autosensData.deviation = deviation; autosensData.bgi = bgi; @@ -299,7 +308,7 @@ public class IobCobThread extends Thread { previous = autosensData; if (bgTime < now()) autosensDataTable.put(bgTime, autosensData); - aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + DateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + DateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); + aapsLogger.debug(LTag.AUTOSENS, "Running detectSensitivity from: " + dateUtil.dateAndTimeString(oldestTimeWithData) + " to: " + dateUtil.dateAndTimeString(bgTime) + " lastDataTime:" + iobCobCalculatorPlugin.lastDataTime()); AutosensResult sensitivity = iobCobCalculatorPlugin.detectSensitivityWithLock(oldestTimeWithData, bgTime); aapsLogger.debug(LTag.AUTOSENS, "Sensitivity result: " + sensitivity.toString()); autosensData.autosensResult = sensitivity; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventAutosensBgLoaded.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventAutosensBgLoaded.kt new file mode 100644 index 0000000000..b02e96b67f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventAutosensBgLoaded.kt @@ -0,0 +1,6 @@ +package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events + +import info.nightscout.androidaps.events.Event +import info.nightscout.androidaps.events.EventLoop + +class EventAutosensBgLoaded(var cause: Event) : EventLoop() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryBgData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryBgData.kt new file mode 100644 index 0000000000..5f546c2d9f --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/events/EventNewHistoryBgData.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.plugins.iob.iobCobCalculator.events + +import info.nightscout.androidaps.events.Event + +class EventNewHistoryBgData(val timestamp: Long) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index f26bacf8ec..b0a1203170 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt @@ -14,6 +14,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.dialogs.ProfileSwitchDialog import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfileChanged @@ -28,12 +29,14 @@ import java.text.DecimalFormat import javax.inject.Inject class LocalProfileFragment : DaggerFragment() { + @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var hardLimits: HardLimits + @Inject lateinit var dateUtil: DateUtil private var disposable: CompositeDisposable = CompositeDisposable() @@ -42,15 +45,15 @@ class LocalProfileFragment : DaggerFragment() { private val save = Runnable { doEdit() - basalView?.updateLabel(resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel()) + basalView?.updateLabel(resourceHelper.gs(R.string.basal_label) + ": " + sumLabel()) } private val textWatch = object : TextWatcher { override fun afterTextChanged(s: Editable) {} override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { - localProfilePlugin.currentProfile().dia = SafeParse.stringToDouble(localprofile_dia.text.toString()) - localProfilePlugin.currentProfile().name = localprofile_name.text.toString() + localProfilePlugin.currentProfile()?.dia = SafeParse.stringToDouble(localprofile_dia.text.toString()) + localProfilePlugin.currentProfile()?.name = localprofile_name.text.toString() doEdit() } } @@ -96,21 +99,23 @@ class LocalProfileFragment : DaggerFragment() { fun build() { val pumpDescription = activePlugin.activePump.pumpDescription - val units = if (localProfilePlugin.currentProfile().mgdl) Constants.MGDL else Constants.MMOL + if (localProfilePlugin.numOfProfiles == 0) localProfilePlugin.addNewProfile() + val currentProfile = localProfilePlugin.currentProfile() ?: return + val units = if (currentProfile.mgdl) Constants.MGDL else Constants.MMOL localprofile_name.removeTextChangedListener(textWatch) - localprofile_name.setText(localProfilePlugin.currentProfile().name) + localprofile_name.setText(currentProfile.name) localprofile_name.addTextChangedListener(textWatch) - localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, hardLimits.MINDIA, hardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) + localprofile_dia.setParams(currentProfile.dia, hardLimits.MINDIA, hardLimits.MAXDIA, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) localprofile_dia.tag = "LP_DIA" - TimeListEdit(context, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label), localProfilePlugin.currentProfile().ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.ic_label), currentProfile.ic, null, hardLimits.MINIC, hardLimits.MAXIC, 0.1, DecimalFormat("0.0"), save) + basalView = TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.basal_label) + ": " + sumLabel(), currentProfile.basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) if (units == Constants.MGDL) { - TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save) - TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), currentProfile.isf, null, hardLimits.MINISF, hardLimits.MAXISF, 1.0, DecimalFormat("0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), 1.0, DecimalFormat("0"), save) } else { - TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label), localProfilePlugin.currentProfile().isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save) - TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label), localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.isf_label), currentProfile.isf, null, Profile.fromMgdlToUnits(hardLimits.MINISF, Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.MAXISF, Constants.MMOL), 0.1, DecimalFormat("0.0"), save) + TimeListEdit(context, aapsLogger, dateUtil, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.target_label), currentProfile.targetLow, currentProfile.targetHigh, Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[0].toDouble(), Constants.MMOL), Profile.fromMgdlToUnits(hardLimits.VERY_HARD_LIMIT_TARGET_BG[1].toDouble(), Constants.MMOL), 0.1, DecimalFormat("0.0"), save) } // Spinner @@ -174,24 +179,17 @@ class LocalProfileFragment : DaggerFragment() { // if (!pumpDescription.isTempBasalCapable) localprofile_basal.visibility = View.GONE @Suppress("SetTextI18n") - localprofile_units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (localProfilePlugin.currentProfile().mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol)) + localprofile_units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (currentProfile.mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol)) localprofile_profileswitch.setOnClickListener { - // TODO: select in dialog localProfilePlugin.currentProfileIndex - ProfileSwitchDialog().show(childFragmentManager, "NewNSTreatmentDialog") + ProfileSwitchDialog() + .also { it.arguments = Bundle().also { bundle -> bundle.putInt("profileIndex", localProfilePlugin.currentProfileIndex) } } + .show(childFragmentManager, "NewNSTreatmentDialog") } localprofile_reset.setOnClickListener { localProfilePlugin.loadSettings() - @Suppress("SetTextI18n") - localprofile_units.text = resourceHelper.gs(R.string.units_colon) + " " + (if (localProfilePlugin.currentProfile().mgdl) resourceHelper.gs(R.string.mgdl) else resourceHelper.gs(R.string.mmol)) - localprofile_dia.setParams(localProfilePlugin.currentProfile().dia, MIN_DIA, 12.0, 0.1, DecimalFormat("0.0"), false, localprofile_save, textWatch) - localprofile_dia.tag = "LP_DIA" - TimeListEdit(context, view, R.id.localprofile_ic, "IC", resourceHelper.gs(R.string.nsprofileview_ic_label) + ":", localProfilePlugin.currentProfile().ic, null, 0.5, 50.0, 0.1, DecimalFormat("0.0"), save) - TimeListEdit(context, view, R.id.localprofile_isf, "ISF", resourceHelper.gs(R.string.nsprofileview_isf_label) + ":", localProfilePlugin.currentProfile().isf, null, 0.5, 500.0, 0.1, DecimalFormat("0.0"), save) - basalView = TimeListEdit(context, view, R.id.localprofile_basal, "BASAL", resourceHelper.gs(R.string.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.currentProfile().basal, null, pumpDescription.basalMinimumRate, 10.0, 0.01, DecimalFormat("0.00"), save) - TimeListEdit(context, view, R.id.localprofile_target, "TARGET", resourceHelper.gs(R.string.nsprofileview_target_label) + ":", localProfilePlugin.currentProfile().targetLow, localProfilePlugin.currentProfile().targetHigh, 3.0, 200.0, 0.1, DecimalFormat("0.0"), save) - updateGUI() + build() } localprofile_save.setOnClickListener { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt index 456c46a5da..8a26b43fbf 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt @@ -5,16 +5,11 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.data.ProfileStore import info.nightscout.androidaps.events.EventProfileStoreChanged -import info.nightscout.androidaps.interfaces.PluginBase -import info.nightscout.androidaps.interfaces.PluginDescription -import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.androidaps.interfaces.ProfileInterface +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter @@ -28,7 +23,6 @@ import java.util.* import javax.inject.Inject import javax.inject.Singleton import kotlin.collections.ArrayList -import kotlin.math.max @Singleton class LocalProfilePlugin @Inject constructor( @@ -37,7 +31,8 @@ class LocalProfilePlugin @Inject constructor( private val rxBus: RxBusWrapper, resourceHelper: ResourceHelper, private val sp: SP, - private val profileFunction: ProfileFunction + private val profileFunction: ProfileFunction, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.PROFILE) .fragmentClass(LocalProfileFragment::class.java.name) @@ -49,15 +44,10 @@ class LocalProfilePlugin @Inject constructor( aapsLogger, resourceHelper, injector ), ProfileInterface { - var rawProfile: ProfileStore? = null + private var rawProfile: ProfileStore? = null private val defaultArray = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]" - companion object { - @JvmStatic - val LOCAL_PROFILE = "LocalProfile" - } - override fun onStart() { super.onStart() loadSettings() @@ -86,22 +76,6 @@ class LocalProfilePlugin @Inject constructor( return sp } - fun copyFrom(rawProfile: ProfileStore?, profile: Profile, newName: String): SingleProfile { - var verifiedName = newName - if (rawProfile?.getSpecificProfile(newName) != null) { - verifiedName += " " + DateUtil.now().toString() - } - val sp = SingleProfile() - sp.name = verifiedName - sp.mgdl = profile.units == Constants.MGDL - sp.dia = profile.dia - sp.ic = JSONArray(profile.data.getJSONArray("carbratio").toString()) - sp.isf = JSONArray(profile.data.getJSONArray("sens").toString()) - sp.basal = JSONArray(profile.data.getJSONArray("basal").toString()) - sp.targetLow = JSONArray(profile.data.getJSONArray("target_low").toString()) - sp.targetHigh = JSONArray(profile.data.getJSONArray("target_high").toString()) - return sp - } } var isEdited: Boolean = false @@ -110,7 +84,7 @@ class LocalProfilePlugin @Inject constructor( var numOfProfiles = 0 internal var currentProfileIndex = 0 - fun currentProfile() = profiles[currentProfileIndex] + fun currentProfile(): SingleProfile? = if (numOfProfiles > 0) profiles[currentProfileIndex] else null @Synchronized fun isValidEditState(): Boolean { @@ -122,18 +96,18 @@ class LocalProfilePlugin @Inject constructor( fun storeSettings(activity: Activity? = null) { for (i in 0 until numOfProfiles) { profiles[i].run { - val LOCAL_PROFILE_NUMBERED = LOCAL_PROFILE + "_" + i + "_" - sp.putString(LOCAL_PROFILE_NUMBERED + "name", name!!) - sp.putBoolean(LOCAL_PROFILE_NUMBERED + "mgdl", mgdl) - sp.putDouble(LOCAL_PROFILE_NUMBERED + "dia", dia) - sp.putString(LOCAL_PROFILE_NUMBERED + "ic", ic.toString()) - sp.putString(LOCAL_PROFILE_NUMBERED + "isf", isf.toString()) - sp.putString(LOCAL_PROFILE_NUMBERED + "basal", basal.toString()) - sp.putString(LOCAL_PROFILE_NUMBERED + "targetlow", targetLow.toString()) - sp.putString(LOCAL_PROFILE_NUMBERED + "targethigh", targetHigh.toString()) + val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_" + sp.putString(localProfileNumbered + "name", name!!) + sp.putBoolean(localProfileNumbered + "mgdl", mgdl) + sp.putDouble(localProfileNumbered + "dia", dia) + sp.putString(localProfileNumbered + "ic", ic.toString()) + sp.putString(localProfileNumbered + "isf", isf.toString()) + sp.putString(localProfileNumbered + "basal", basal.toString()) + sp.putString(localProfileNumbered + "targetlow", targetLow.toString()) + sp.putString(localProfileNumbered + "targethigh", targetHigh.toString()) } } - sp.putInt(LOCAL_PROFILE + "_profiles", numOfProfiles) + sp.putInt(Constants.LOCAL_PROFILE + "_profiles", numOfProfiles) createAndStoreConvertedProfile() isEdited = false @@ -145,7 +119,7 @@ class LocalProfilePlugin @Inject constructor( if (name.contains(".")) namesOK = false } if (namesOK) - rawProfile?.let { NSUpload.uploadProfileStore(it.data) } + rawProfile?.let { nsUpload.uploadProfileStore(it.data) } else activity?.let { OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot)) @@ -154,25 +128,20 @@ class LocalProfilePlugin @Inject constructor( @Synchronized fun loadSettings() { - if (sp.contains(LOCAL_PROFILE + "mgdl")) { - doConversion() - return - } - - numOfProfiles = sp.getInt(LOCAL_PROFILE + "_profiles", 0) + numOfProfiles = sp.getInt(Constants.LOCAL_PROFILE + "_profiles", 0) profiles.clear() - numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists +// numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists for (i in 0 until numOfProfiles) { val p = SingleProfile() - val LOCAL_PROFILE_NUMBERED = LOCAL_PROFILE + "_" + i + "_" + val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_" - p.name = sp.getString(LOCAL_PROFILE_NUMBERED + "name", LOCAL_PROFILE + i) + p.name = sp.getString(localProfileNumbered + "name", Constants.LOCAL_PROFILE + i) if (isExistingName(p.name)) continue - p.mgdl = sp.getBoolean(LOCAL_PROFILE_NUMBERED + "mgdl", false) - p.dia = sp.getDouble(LOCAL_PROFILE_NUMBERED + "dia", Constants.defaultDIA) + p.mgdl = sp.getBoolean(localProfileNumbered + "mgdl", false) + p.dia = sp.getDouble(localProfileNumbered + "dia", Constants.defaultDIA) try { - p.ic = JSONArray(sp.getString(LOCAL_PROFILE_NUMBERED + "ic", defaultArray)) + p.ic = JSONArray(sp.getString(localProfileNumbered + "ic", defaultArray)) } catch (e1: JSONException) { try { p.ic = JSONArray(defaultArray) @@ -182,7 +151,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.isf = JSONArray(sp.getString(LOCAL_PROFILE_NUMBERED + "isf", defaultArray)) + p.isf = JSONArray(sp.getString(localProfileNumbered + "isf", defaultArray)) } catch (e1: JSONException) { try { p.isf = JSONArray(defaultArray) @@ -192,7 +161,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.basal = JSONArray(sp.getString(LOCAL_PROFILE_NUMBERED + "basal", defaultArray)) + p.basal = JSONArray(sp.getString(localProfileNumbered + "basal", defaultArray)) } catch (e1: JSONException) { try { p.basal = JSONArray(defaultArray) @@ -202,7 +171,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.targetLow = JSONArray(sp.getString(LOCAL_PROFILE_NUMBERED + "targetlow", defaultArray)) + p.targetLow = JSONArray(sp.getString(localProfileNumbered + "targetlow", defaultArray)) } catch (e1: JSONException) { try { p.targetLow = JSONArray(defaultArray) @@ -212,7 +181,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.targetHigh = JSONArray(sp.getString(LOCAL_PROFILE_NUMBERED + "targethigh", defaultArray)) + p.targetHigh = JSONArray(sp.getString(localProfileNumbered + "targethigh", defaultArray)) } catch (e1: JSONException) { try { p.targetHigh = JSONArray(defaultArray) @@ -228,6 +197,23 @@ class LocalProfilePlugin @Inject constructor( createAndStoreConvertedProfile() } + fun copyFrom(profile: Profile, newName: String): SingleProfile { + var verifiedName = newName + if (rawProfile?.getSpecificProfile(newName) != null) { + verifiedName += " " + DateUtil.now().toString() + } + val sp = SingleProfile() + sp.name = verifiedName + sp.mgdl = profile.units == Constants.MGDL + sp.dia = profile.dia + sp.ic = JSONArray(profile.data.getJSONArray("carbratio").toString()) + sp.isf = JSONArray(profile.data.getJSONArray("sens").toString()) + sp.basal = JSONArray(profile.data.getJSONArray("basal").toString()) + sp.targetLow = JSONArray(profile.data.getJSONArray("target_low").toString()) + sp.targetHigh = JSONArray(profile.data.getJSONArray("target_high").toString()) + return sp + } + private fun isExistingName(name: String?): Boolean { for (p in profiles) { if (p.name == name) return true @@ -235,78 +221,6 @@ class LocalProfilePlugin @Inject constructor( return false } - @Synchronized - private fun doConversion() { // conversion from 2.3 to 2.4 format - aapsLogger.debug(LTag.PROFILE, "Loading stored settings") - val p = SingleProfile() - - p.mgdl = sp.getBoolean(LOCAL_PROFILE + "mgdl", profileFunction.getUnits() == Constants.MGDL) - p.dia = sp.getDouble(LOCAL_PROFILE + "dia", Constants.defaultDIA) - try { - p.ic = JSONArray(sp.getString(LOCAL_PROFILE + "ic", defaultArray)) - } catch (e1: JSONException) { - try { - p.ic = JSONArray(defaultArray) - } catch (ignored: JSONException) { - } - } - - try { - p.isf = JSONArray(sp.getString(LOCAL_PROFILE + "isf", defaultArray)) - } catch (e1: JSONException) { - try { - p.isf = JSONArray(defaultArray) - } catch (ignored: JSONException) { - } - } - - try { - p.basal = JSONArray(sp.getString(LOCAL_PROFILE + "basal", defaultArray)) - } catch (e1: JSONException) { - try { - p.basal = JSONArray(defaultArray) - } catch (ignored: JSONException) { - } - } - - try { - p.targetLow = JSONArray(sp.getString(LOCAL_PROFILE + "targetlow", defaultArray)) - } catch (e1: JSONException) { - try { - p.targetLow = JSONArray(defaultArray) - } catch (ignored: JSONException) { - } - } - - try { - p.targetHigh = JSONArray(sp.getString(LOCAL_PROFILE + "targethigh", defaultArray)) - } catch (e1: JSONException) { - try { - p.targetHigh = JSONArray(defaultArray) - } catch (ignored: JSONException) { - } - } - p.name = LOCAL_PROFILE - - sp.remove(LOCAL_PROFILE + "mgdl") - sp.remove(LOCAL_PROFILE + "mmol") - sp.remove(LOCAL_PROFILE + "dia") - sp.remove(LOCAL_PROFILE + "ic") - sp.remove(LOCAL_PROFILE + "isf") - sp.remove(LOCAL_PROFILE + "basal") - sp.remove(LOCAL_PROFILE + "targetlow") - sp.remove(LOCAL_PROFILE + "targethigh") - - currentProfileIndex = 0 - numOfProfiles = 1 - profiles.clear() - profiles.add(p) - storeSettings() - - isEdited = false - createAndStoreConvertedProfile() - } - /* { "_id": "576264a12771b7500d7ad184", @@ -352,13 +266,13 @@ class LocalProfilePlugin @Inject constructor( fun addNewProfile() { var free = 0 for (i in 1..10000) { - if (rawProfile?.getSpecificProfile(LOCAL_PROFILE + i) == null) { + if (rawProfile?.getSpecificProfile(Constants.LOCAL_PROFILE + i) == null) { free = i break } } val p = SingleProfile() - p.name = LOCAL_PROFILE + free + p.name = Constants.LOCAL_PROFILE + free p.mgdl = profileFunction.getUnits() == Constants.MGDL p.dia = Constants.defaultDIA p.ic = JSONArray(defaultArray) @@ -422,7 +336,7 @@ class LocalProfilePlugin @Inject constructor( store.put(name, profile) } } - json.put("defaultProfile", currentProfile().name) + if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name) json.put("startDate", DateUtil.toISOAsUTC(DateUtil.now())) json.put("store", store) } catch (e: JSONException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt index 87831d5352..119f2b41a0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfileFragment.kt @@ -9,7 +9,7 @@ import android.widget.ArrayAdapter import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.profile.ns.events.EventNSProfileUpdateGUI import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt index a93cbaad01..31aa4a2df1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/profile/ns/NSProfilePlugin.kt @@ -4,7 +4,7 @@ import android.content.Intent import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.R -import info.nightscout.androidaps.data.ProfileStore +import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.events.EventProfileStoreChanged import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription @@ -27,15 +27,16 @@ class NSProfilePlugin @Inject constructor( aapsLogger: AAPSLogger, private val rxBus: RxBusWrapper, resourceHelper: ResourceHelper, - private val sp: SP + private val sp: SP, + config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.PROFILE) .fragmentClass(NSProfileFragment::class.java.name) .pluginName(R.string.nsprofile) .shortName(R.string.profileviewer_shortname) - .alwaysEnabled(Config.NSCLIENT) - .alwaysVisible(Config.NSCLIENT) - .showInList(!Config.NSCLIENT) + .alwaysEnabled(config.NSCLIENT) + .alwaysVisible(config.NSCLIENT) + .showInList(!config.NSCLIENT) .description(R.string.description_profile_nightscout), aapsLogger, resourceHelper, injector ), ProfileInterface { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index 0ec21a8014..e443ac4657 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -20,7 +20,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -44,7 +43,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.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; @@ -65,7 +64,7 @@ import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpH import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.PumpHistoryRequest; import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Tdd; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.InstanceId; @@ -485,7 +484,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr getAapsLogger().error("deliverTreatment: Invalid input"); return new PumpEnactResult(getInjector()).success(false).enacted(false) .bolusDelivered(0d).carbsDelivered(0d) - .comment(getResourceHelper().gs(R.string.danar_invalidinput)); + .comment(getResourceHelper().gs(R.string.invalidinput)); } else if (detailedBolusInfo.insulin > 0) { // bolus needed, ask pump to deliver it return deliverBolus(detailedBolusInfo); @@ -1259,7 +1258,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { if (!pump.initialized) { return null; } @@ -1281,7 +1280,7 @@ public class ComboPlugin extends PumpPluginBase implements PumpInterface, Constr pumpJson.put("status", statusJson); JSONObject extendedJson = new JSONObject(); - extendedJson.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extendedJson.put("Version", version); extendedJson.put("ActiveProfile", profileFunction.getProfileName()); PumpState ps = pump.state; if (ps.tbrActive) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java deleted file mode 100644 index 48d1df3b9d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.java +++ /dev/null @@ -1,73 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.defs; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; - -/** - * This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes - * management and modified/extended for AAPS. - *

- * Author: Andy {andy.rozman@gmail.com} - */ - -public enum PumpHistoryEntryGroup { - - All(R.string.medtronic_history_group_all), // - Bolus(R.string.danar_history_bolus), // - Basal(R.string.medtronic_history_group_basal), // - Prime(R.string.danar_history_prime), // - Configuration(R.string.medtronic_history_group_configuration), // - Alarm(R.string.danar_history_alarm), // - Glucose(R.string.danar_history_glucose), // - Notification(R.string.medtronic_history_group_notification), // - Statistic(R.string.medtronic_history_group_statistic), - Unknown(R.string.medtronic_history_group_unknown), // - ; - - private int resourceId; - private String translated; - - public static boolean doNotTranslate = false; - - private static List list; - - static { - list = new ArrayList<>(); - - for (PumpHistoryEntryGroup pumpHistoryEntryGroup : values()) { - //if (doNotTranslate) { - pumpHistoryEntryGroup.translated = MainApp.gs(pumpHistoryEntryGroup.resourceId); - //} - list.add(pumpHistoryEntryGroup); - } - } - - - PumpHistoryEntryGroup(int resourceId) { - this.resourceId = resourceId; - // this.translated = MainApp.gs(resourceId); - } - - - public static List getList() { - return list; - } - - - public int getResourceId() { - return resourceId; - } - - - public String getTranslated() { - return translated; - } - - - public String toString() { - return this.translated; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java deleted file mode 100644 index 03b42b730f..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/LocationHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.common.utils; - -import android.app.Activity; -import android.content.Context; -import android.content.Intent; -import android.location.LocationManager; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.utils.alertDialogs.OKDialog; - -/** - * Helper for checking if location services are enabled on the device. - */ -public class LocationHelper { - - /** - * Determine if GPS is currently enabled. - *

- * On Android 6 (Marshmallow), location needs to be enabled for Bluetooth discovery to work. - * - * @param context The current app context. - * @return true if location is enabled, false otherwise. - */ - public static boolean isLocationEnabled(Context context) { - LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); - - return (locationManager != null && // - (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || // - locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))); - - // return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - } - - - /** - * Prompt the user to enable GPS location if it isn't already on. - * - * @param parent The currently visible activity. - */ - public static void requestLocation(final Activity parent) { - if (LocationHelper.isLocationEnabled(parent)) { - return; - } - - // Shamelessly borrowed from http://stackoverflow.com/a/10311877/868533 - OKDialog.showConfirmation(parent, parent.getString(R.string.location_not_found_title), parent.getString(R.string.location_not_found_message), () -> { - parent.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); - }); - } - - - /** - * Prompt the user to enable GPS location on devices that need it for Bluetooth discovery. - *

- * Android 6 (Marshmallow) needs GPS enabled for Bluetooth discovery to work. - * - * @param activity The currently visible activity. - */ - public static void requestLocationForBluetooth(Activity activity) { - // Location needs to be enabled for Bluetooth discovery on Marshmallow. - LocationHelper.requestLocation(activity); - } - - // public static Boolean locationPermission(ActivityWithMenu act) { - // return ActivityCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) == - // PackageManager.PERMISSION_GRANTED; - // } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt deleted file mode 100644 index a81408b381..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageHashTableR.kt +++ /dev/null @@ -1,100 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableR @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - injector: HasAndroidInjector -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue)) - put(MsgInitConnStatusBolus(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic(aapsLogger, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgInitConnStatusOption(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0304 CMD_PUMPINIT_OPTION - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryError(aapsLogger, rxBus)) // 0x3106 CMD_HISTORY_ERROR - put(MsgHistoryCarbo(aapsLogger, rxBus)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgHistoryRefill(aapsLogger, rxBus)) // 0x3108 CMD_HISTORY_REFILL - put(MsgHistorySuspend(aapsLogger, rxBus)) // 0x3109 CMD_HISTORY_SUSPEND - put(MsgHistoryBasalHour(aapsLogger, rxBus)) // 0x310A CMD_HISTORY_BASAL_HOUR - put(MsgHistoryDone(aapsLogger, danaRPump)) // 0x31F1 CMD_HISTORY_DONT_USED - // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)) - // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSettingUserOptions(aapsLogger, danaRPump)) // 0x320B CMD_SETTING_V_USER_OPTIONS - put(MsgSettingActiveProfile(aapsLogger, danaRPump)) // 0x320C CMD_SETTING_V_PROFILE_NUMBER - put(MsgSettingProfileRatiosAll(aapsLogger, danaRPump)) // 0x320D CMD_SETTING_V_CIR_CF_VALUE - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgSetBasalProfile(aapsLogger, rxBus, resourceHelper, 0.toByte(), Array(24) { 0.0 })) // 0x3306 CMD_SETTING_BASAL_PROFILE_S - put(MsgSetUserOptions(aapsLogger, danaRPump)) // 0x330B CMD_SETTING_USER_OPTIONS_S - put(MsgSetActivateBasalProfile(aapsLogger, 0.toByte())) // 0x330C CMD_SETTING_PROFILE_NUMBER_S - put(MsgHistoryAllDone(aapsLogger, danaRPump)) // 0x41F1 CMD_HISTORY_ALL_DONE - put(MsgHistoryAll(aapsLogger, rxBus)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW - // 0xF0F1 CMD_PUMP_CHECK_VALUE - put(MsgCheckValue(aapsLogger, danaRPump, danaRPlugin)) - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.kt deleted file mode 100644 index b83da483fe..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusProgress.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.R -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.EventOverviewBolusProgress -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.resources.ResourceHelper -import kotlin.math.min - -class MsgBolusProgress( - private val aapsLogger: AAPSLogger, - private val resourceHelper: ResourceHelper, - private val rxBus: RxBusWrapper, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x0202) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - val deliveredInsulin = danaRPump.bolusAmountToBeDelivered - intFromBuff(bytes, 0, 2) / 100.0 - danaRPump.bolusProgressLastTimeStamp = System.currentTimeMillis() - danaRPump.bolusingTreatment?.insulin = deliveredInsulin - val bolusingEvent = EventOverviewBolusProgress - bolusingEvent.status = resourceHelper.gs(R.string.bolusdelivering, deliveredInsulin) - bolusingEvent.t = danaRPump.bolusingTreatment - bolusingEvent.percent = min((deliveredInsulin / danaRPump.bolusAmountToBeDelivered * 100).toInt(), 100) - aapsLogger.debug(LTag.PUMPCOMM, "Delivered insulin so far: $deliveredInsulin") - rxBus.send(bolusingEvent) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.kt deleted file mode 100644 index abb6c34d8d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgCheckValue.kt +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgCheckValue( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val danaRPlugin: DanaRPlugin -) : MessageBase() { - - init { - SetCommand(0xF0F1) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.isNewPump = true - aapsLogger.debug(LTag.PUMPCOMM, "New firmware confirmed") - danaRPump.model = intFromBuff(bytes, 0, 1) - danaRPump.protocol = intFromBuff(bytes, 1, 1) - danaRPump.productCode = intFromBuff(bytes, 2, 1) - if (danaRPump.model != DanaRPump.EXPORT_MODEL) { - danaRPlugin.disconnect("Wrong Model") - aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected") - } - aapsLogger.debug(LTag.PUMPCOMM, "Model: " + String.format("%02X ", danaRPump.model)) - aapsLogger.debug(LTag.PUMPCOMM, "Protocol: " + String.format("%02X ", danaRPump.protocol)) - aapsLogger.debug(LTag.PUMPCOMM, "Product Code: " + String.format("%02X ", danaRPump.productCode)) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAlarm.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAlarm.kt deleted file mode 100644 index 142d0fea04..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAlarm.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryAlarm( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3105) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllDone.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllDone.kt deleted file mode 100644 index bd5d634423..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAllDone.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgHistoryAllDone( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x41F1) - danaRPump.historyDoneReceived = false - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.historyDoneReceived = true - aapsLogger.debug(LTag.PUMPCOMM, "History all done received") - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBasalHour.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBasalHour.kt deleted file mode 100644 index 2f235f38d1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBasalHour.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryBasalHour( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x310A) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBolus.kt deleted file mode 100644 index 26e1506eac..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryBolus.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryBolus( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3101) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryCarbo.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryCarbo.kt deleted file mode 100644 index 8650e251a8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryCarbo.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryCarbo( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3107) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDailyInsulin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDailyInsulin.kt deleted file mode 100644 index 60c1fffd14..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDailyInsulin.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryDailyInsulin( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3102) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDone.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDone.kt deleted file mode 100644 index 203b5f71d7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryDone.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgHistoryDone( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x31F1) - danaRPump.historyDoneReceived = false - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.historyDoneReceived = true - aapsLogger.debug(LTag.PUMPCOMM, "History done received") - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryError.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryError.kt deleted file mode 100644 index 50d6cb9051..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryError.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryError( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3106) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryGlucose.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryGlucose.kt deleted file mode 100644 index 07e2354f18..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryGlucose.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryGlucose( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3104) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNew.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNew.kt deleted file mode 100644 index 0bf49cc612..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNew.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryNew( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x42F2) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNewDone.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNewDone.kt deleted file mode 100644 index e6d292d54e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryNewDone.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgHistoryNewDone( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x42F1) - danaRPump.historyDoneReceived = false - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.historyDoneReceived = true - aapsLogger.debug(LTag.PUMPCOMM, "History new done received") - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryRefill.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryRefill.kt deleted file mode 100644 index d77d0fbca7..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryRefill.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistoryRefill( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3108) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistorySuspend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistorySuspend.kt deleted file mode 100644 index d3f947f77d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistorySuspend.kt +++ /dev/null @@ -1,17 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class MsgHistorySuspend( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { - - init { - SetCommand(0x3109) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - // Handle message taken from MsgHistoryAll -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBasic.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBasic.kt deleted file mode 100644 index f91042282e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusBasic.kt +++ /dev/null @@ -1,58 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgInitConnStatusBasic( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x0303) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (bytes.size - 10 < 21) { - return - } - danaRPump.pumpSuspended = intFromBuff(bytes, 0, 1) == 1 - danaRPump.calculatorEnabled = intFromBuff(bytes, 1, 1) == 1 - danaRPump.dailyTotalUnits = intFromBuff(bytes, 2, 3) / 750.0 - danaRPump.maxDailyTotalUnits = intFromBuff(bytes, 5, 2) / 100 - danaRPump.reservoirRemainingUnits = intFromBuff(bytes, 7, 3) / 750.0 - danaRPump.bolusBlocked = intFromBuff(bytes, 10, 1) == 1 - danaRPump.currentBasal = intFromBuff(bytes, 11, 2) / 100.0 - danaRPump.tempBasalPercent = intFromBuff(bytes, 13, 1) - danaRPump.isExtendedInProgress = intFromBuff(bytes, 14, 1) == 1 - danaRPump.isTempBasalInProgress = intFromBuff(bytes, 15, 1) == 1 - val statusBasalUDOption = intFromBuff(bytes, 16, 1) - danaRPump.isDualBolusInProgress = intFromBuff(bytes, 17, 1) == 1 - val extendedBolusRate = intFromBuff(bytes, 18, 2) / 100.0 - danaRPump.batteryRemaining = intFromBuff(bytes, 20, 1) - val bolusConfig = intFromBuff(bytes, 21, 1) - val deliveryPrime = bolusConfig and DanaRPump.DELIVERY_PRIME != 0 - val deliveryStepBolus = bolusConfig and DanaRPump.DELIVERY_STEP_BOLUS != 0 - val deliveryBasal = bolusConfig and DanaRPump.DELIVERY_BASAL != 0 - val deliveryExtBolus = bolusConfig and DanaRPump.DELIVERY_EXT_BOLUS != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Delivery prime: $deliveryPrime") - aapsLogger.debug(LTag.PUMPCOMM, "Delivery step bolus: $deliveryStepBolus") - aapsLogger.debug(LTag.PUMPCOMM, "Delivery basal: $deliveryBasal") - aapsLogger.debug(LTag.PUMPCOMM, "Delivery ext bolus: $deliveryExtBolus") - aapsLogger.debug(LTag.PUMPCOMM, "Pump suspended: " + danaRPump.pumpSuspended) - aapsLogger.debug(LTag.PUMPCOMM, "Calculator enabled: " + danaRPump.calculatorEnabled) - aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Max daily total units: " + danaRPump.maxDailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: " + danaRPump.reservoirRemainingUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Bolus blocked: " + danaRPump.bolusBlocked) - aapsLogger.debug(LTag.PUMPCOMM, "Current basal: " + danaRPump.currentBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal percent: " + danaRPump.tempBasalPercent) - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "statusBasalUDOption: $statusBasalUDOption") - aapsLogger.debug(LTag.PUMPCOMM, "Is dual bolus running: " + danaRPump.isDualBolusInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus rate: $extendedBolusRate") - aapsLogger.debug(LTag.PUMPCOMM, "Battery remaining: " + danaRPump.batteryRemaining) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt deleted file mode 100644 index f2a579fd72..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetUserOptions.kt +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSetUserOptions( - private val aapsLogger: AAPSLogger, - danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x330B) - if (danaRPump.userOptionsFrompump == null) { - // No options set -> Exiting - aapsLogger.debug(LTag.PUMPCOMM, "NO USER OPTIONS LOADED EXITING!") - } else { - danaRPump.userOptionsFrompump!![0] = (if (danaRPump.timeDisplayType == 1) 0 else 1).toByte() - danaRPump.userOptionsFrompump!![1] = danaRPump.buttonScrollOnOff.toByte() - danaRPump.userOptionsFrompump!![2] = danaRPump.beepAndAlarm.toByte() - danaRPump.userOptionsFrompump!![3] = danaRPump.lcdOnTimeSec.toByte() - danaRPump.userOptionsFrompump!![4] = danaRPump.backlightOnTimeSec.toByte() - danaRPump.userOptionsFrompump!![5] = danaRPump.selectedLanguage.toByte() - danaRPump.userOptionsFrompump!![8] = danaRPump.units.toByte() - danaRPump.userOptionsFrompump!![9] = danaRPump.shutdownHour.toByte() - danaRPump.userOptionsFrompump!![27] = danaRPump.lowReservoirRate.toByte() - for (element in danaRPump.userOptionsFrompump!!) { - AddParamByte(element) - } - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - } - - override fun handleMessage(bytes: ByteArray) { - val result = intFromBuff(bytes, 0, 1) - if (result != 1) { - failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result FAILED!!!") - } else { - aapsLogger.debug(LTag.PUMPCOMM, "Setting user options: $result") - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingActiveProfile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingActiveProfile.kt deleted file mode 100644 index 4da6770031..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingActiveProfile.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingActiveProfile( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x320C) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.activeProfile = intFromBuff(bytes, 0, 1) - aapsLogger.debug(LTag.PUMPCOMM, "Active profile number: " + danaRPump.activeProfile) - } - -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingBasal.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingBasal.kt deleted file mode 100644 index 256063ced1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingBasal.kt +++ /dev/null @@ -1,31 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import java.util.* - -class MsgSettingBasal( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val danaRPlugin: DanaRPlugin -) : MessageBase() { - - init { - SetCommand(0x3202) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.pumpProfiles = Array(4) {Array(48) {0.0} } - for (index in 0..23) { - var basal = intFromBuff(bytes, 2 * index, 2) - if (basal < danaRPlugin.pumpDescription.basalMinimumRate) basal = 0 - danaRPump.pumpProfiles!![danaRPump.activeProfile][index] = basal / 100.0 - } - for (index in 0..23) { - aapsLogger.debug(LTag.PUMPCOMM, "Basal " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaRPump.pumpProfiles!![danaRPump.activeProfile][index]) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingGlucose.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingGlucose.kt deleted file mode 100644 index a4cad21293..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingGlucose.kt +++ /dev/null @@ -1,26 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -/** - * Created by mike on 05.07.2016. - */ -class MsgSettingGlucose( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3209) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.units = intFromBuff(bytes, 0, 1) - danaRPump.easyBasalMode = intFromBuff(bytes, 1, 1) - aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Easy basal mode: " + danaRPump.easyBasalMode) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt deleted file mode 100644 index 437af793f8..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingMaxValues.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingMaxValues( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3205) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.maxBolus = intFromBuff(bytes, 0, 2) / 100.0 - danaRPump.maxBasal = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.maxDailyTotalUnits = intFromBuff(bytes, 4, 2) / 100 - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus) - aapsLogger.debug(LTag.PUMPCOMM, "Max basal: " + danaRPump.maxBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Total daily max units: " + danaRPump.maxDailyTotalUnits) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt deleted file mode 100644 index 6c29024677..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatios.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingProfileRatios( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3204) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble() - danaRPump.currentAIDR = intFromBuff(bytes, 8, 1) - } else { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0 - danaRPump.currentAIDR = intFromBuff(bytes, 8, 1) - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt deleted file mode 100644 index 4f626e89df..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingProfileRatiosAll.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingProfileRatiosAll( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x320D) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.morningCIR = intFromBuff(bytes, 0, 2) - danaRPump.morningCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2) - danaRPump.afternoonCF = intFromBuff(bytes, 6, 2).toDouble() - danaRPump.eveningCIR = intFromBuff(bytes, 8, 2) - danaRPump.eveningCF = intFromBuff(bytes, 10, 2).toDouble() - danaRPump.nightCIR = intFromBuff(bytes, 12, 2) - danaRPump.nightCF = intFromBuff(bytes, 14, 2).toDouble() - } else { - danaRPump.morningCIR = intFromBuff(bytes, 0, 2) - danaRPump.morningCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.afternoonCIR = intFromBuff(bytes, 4, 2) - danaRPump.afternoonCF = intFromBuff(bytes, 6, 2) / 100.0 - danaRPump.eveningCIR = intFromBuff(bytes, 8, 2) - danaRPump.eveningCF = intFromBuff(bytes, 10, 2) / 100.0 - danaRPump.nightCIR = intFromBuff(bytes, 12, 2) - danaRPump.nightCF = intFromBuff(bytes, 14, 2) / 100.0 - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units: " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CIR: " + danaRPump.morningCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump morning CF: " + danaRPump.morningCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CIR: " + danaRPump.afternoonCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump afternoon CF: " + danaRPump.afternoonCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CIR: " + danaRPump.eveningCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump evening CF: " + danaRPump.eveningCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CIR: " + danaRPump.nightCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump night CF: " + danaRPump.nightCF) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingPumpTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingPumpTime.kt deleted file mode 100644 index df356ca744..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingPumpTime.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class MsgSettingPumpTime( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x320A) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - val time = Date( - 100 + intFromBuff(bytes, 5, 1), - intFromBuff(bytes, 4, 1) - 1, - intFromBuff(bytes, 3, 1), - intFromBuff(bytes, 2, 1), - intFromBuff(bytes, 1, 1), - intFromBuff(bytes, 0, 1) - ).time - aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + DateUtil.dateAndTimeString(time) + " Phone time: " + Date()) - danaRPump.pumpTime = time - } - - override fun handleMessageNotReceived() { - danaRPump.pumpTime = 0 - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingShippingInfo.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingShippingInfo.kt deleted file mode 100644 index 7d442e00d6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingShippingInfo.kt +++ /dev/null @@ -1,25 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgSettingShippingInfo( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x3207) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.serialNumber = stringFromBuff(bytes, 0, 10) - danaRPump.shippingDate = dateFromBuff(bytes, 10) - danaRPump.shippingCountry = asciiStringFromBuff(bytes, 13, 3) - aapsLogger.debug(LTag.PUMPCOMM, "Serial number: " + danaRPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping date: " + danaRPump.shippingDate) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaRPump.shippingCountry) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt deleted file mode 100644 index 3678424499..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSettingUserOptions.kt +++ /dev/null @@ -1,59 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import java.util.* - -class MsgSettingUserOptions( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - - init { - SetCommand(0x320B) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(packet: ByteArray) { - val bytes = getDataBytes(packet, packet.size - 10) - danaRPump.userOptionsFrompump = Arrays.copyOf(bytes, bytes!!.size) // saving pumpDataBytes to use it in MsgSetUserOptions - for (pos in bytes.indices) { - aapsLogger.debug(LTag.PUMPCOMM, "[" + pos + "]" + bytes[pos]) - } - danaRPump.timeDisplayType = if (bytes[0] == 1.toByte()) 0 else 1 // 1 -> 24h 0 -> 12h - danaRPump.buttonScrollOnOff = if (bytes[1] == 1.toByte()) 1 else 0 // 1 -> ON, 0-> OFF - danaRPump.beepAndAlarm = bytes[2].toInt() // 1 -> Sound on alarm 2-> Vibrate on alarm 3-> Both on alarm 5-> Sound + beep 6-> vibrate + beep 7-> both + beep Beep adds 4 - danaRPump.lcdOnTimeSec = bytes[3].toInt() and 255 - danaRPump.backlightOnTimeSec = bytes[4].toInt() and 255 - danaRPump.selectedLanguage = bytes[5].toInt() // on DanaRv2 is that needed ? - danaRPump.units = bytes[8].toInt() - danaRPump.shutdownHour = bytes[9].toInt() - danaRPump.lowReservoirRate = bytes[32].toInt() and 255 - /* int selectableLanguage1 = bytes[10]; - int selectableLanguage2 = bytes[11]; - int selectableLanguage3 = bytes[12]; - int selectableLanguage4 = bytes[13]; - int selectableLanguage5 = bytes[14]; - */ - aapsLogger.debug(LTag.PUMPCOMM, "timeDisplayType: " + danaRPump.timeDisplayType) - aapsLogger.debug(LTag.PUMPCOMM, "Button scroll: " + danaRPump.buttonScrollOnOff) - aapsLogger.debug(LTag.PUMPCOMM, "BeepAndAlarm: " + danaRPump.beepAndAlarm) - aapsLogger.debug(LTag.PUMPCOMM, "screen timeout: " + danaRPump.lcdOnTimeSec) - aapsLogger.debug(LTag.PUMPCOMM, "BackLight: " + danaRPump.backlightOnTimeSec) - aapsLogger.debug(LTag.PUMPCOMM, "Selected language: " + danaRPump.selectedLanguage) - aapsLogger.debug(LTag.PUMPCOMM, "Units: " + danaRPump.getUnits()) - aapsLogger.debug(LTag.PUMPCOMM, "Shutdown: " + danaRPump.shutdownHour) - aapsLogger.debug(LTag.PUMPCOMM, "Low reservoir: " + danaRPump.lowReservoirRate) - } - - private fun getDataBytes(bytes: ByteArray?, len: Int): ByteArray? { - if (bytes == null) { - return null - } - val ret = ByteArray(len) - System.arraycopy(bytes, 6, ret, 0, len) - return ret - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt deleted file mode 100644 index e37ad1ebb6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatus.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgStatus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump - -) : MessageBase() { - - init { - SetCommand(0x020B) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750.0 - danaRPump.isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1 - danaRPump.extendedBolusMinutes = intFromBuff(bytes, 4, 2) - danaRPump.extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100.0 - val lastBolusAmount = intFromBuff(bytes, 13, 2) / 100.0 - if (lastBolusAmount != 0.0) { - danaRPump.lastBolusTime = dateTimeFromBuff(bytes, 8) - danaRPump.lastBolusAmount = lastBolusAmount - } - danaRPump.iob = intFromBuff(bytes, 15, 2) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus min: " + danaRPump.extendedBolusMinutes) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus amount: " + danaRPump.extendedBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + danaRPump.lastBolusTime) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "IOB: " + danaRPump.iob) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt deleted file mode 100644 index e8bd43012b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusProfile.kt +++ /dev/null @@ -1,36 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class MsgStatusProfile( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x0204) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - if (danaRPump.units == DanaRPump.UNITS_MGDL) { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2).toDouble() - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2).toDouble() - } else { - danaRPump.currentCIR = intFromBuff(bytes, 0, 2) - danaRPump.currentCF = intFromBuff(bytes, 2, 2) / 100.0 - danaRPump.currentAI = intFromBuff(bytes, 4, 2) / 100.0 - danaRPump.currentTarget = intFromBuff(bytes, 6, 2) / 100.0 - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump units (saved): " + if (danaRPump.units == DanaRPump.UNITS_MGDL) "MGDL" else "MMOL") - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CIR: " + danaRPump.currentCIR) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump CF: " + danaRPump.currentCF) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AI: " + danaRPump.currentAI) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump target: " + danaRPump.currentTarget) - aapsLogger.debug(LTag.PUMPCOMM, "Current pump AIDR: " + danaRPump.currentAIDR) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java deleted file mode 100644 index 6d2cba9741..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractSerialIOThread.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaR.services; - -import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; - -/** - * Created by mike on 28.01.2018. - */ - -public abstract class AbstractSerialIOThread extends Thread { - - public abstract void sendMessage(MessageBase message); - public abstract void disconnect(String reason); -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt deleted file mode 100644 index 7c8f5ca33b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MessageHashTableRKorean.kt +++ /dev/null @@ -1,83 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRKorean.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.* -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableRKorean @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - injector: HasAndroidInjector -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic_k(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus_k(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - put(MsgInitConnStatusTime_k(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue)) // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusBolus_k(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic_k(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryCarbo(aapsLogger, rxBus)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgSettingBasal_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll_k(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgHistoryAll(aapsLogger, rxBus)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW - put(MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0xF0F1 CMD_PUMP_CHECK_VALUE - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgCheckValue_k.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgCheckValue_k.kt deleted file mode 100644 index 16ae6967a2..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgCheckValue_k.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRKorean.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin - -class MsgCheckValue_k( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val danaRKoreanPlugin: DanaRKoreanPlugin - -) : MessageBase() { - - init { - SetCommand(0xF0F1) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.isNewPump = true - aapsLogger.debug(LTag.PUMPCOMM, "New firmware confirmed") - danaRPump.model = intFromBuff(bytes, 0, 1) - danaRPump.protocol = intFromBuff(bytes, 1, 1) - danaRPump.productCode = intFromBuff(bytes, 2, 1) - if (danaRPump.model != DanaRPump.DOMESTIC_MODEL) { - danaRKoreanPlugin.disconnect("Wrong Model") - aapsLogger.debug(LTag.PUMPCOMM, "Wrong model selected") - } - aapsLogger.debug(LTag.PUMPCOMM, "Model: " + String.format("%02X ", danaRPump.model)) - aapsLogger.debug(LTag.PUMPCOMM, "Protocol: " + String.format("%02X ", danaRPump.protocol)) - aapsLogger.debug(LTag.PUMPCOMM, "Product Code: " + String.format("%02X ", danaRPump.productCode)) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt deleted file mode 100644 index 13b29aba9c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgSettingBasal_k.kt +++ /dev/null @@ -1,31 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRKorean.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import java.util.* - -class MsgSettingBasal_k( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump, - private val danaRKoreanPlugin: DanaRKoreanPlugin -) : MessageBase() { - - init { - SetCommand(0x3202) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.pumpProfiles = Array(4) {Array(48) {0.0} } - for (index in 0..23) { - var basal = intFromBuff(bytes, 2 * index, 2) - if (basal < danaRKoreanPlugin.pumpDescription.basalMinimumRate) basal = 0 - danaRPump.pumpProfiles!![danaRPump.activeProfile][index] = basal / 100.0 - } - for (index in 0..23) - aapsLogger.debug(LTag.PUMPCOMM, "Basal " + String.format(Locale.ENGLISH, "%02d", index) + "h: " + danaRPump.pumpProfiles!![danaRPump.activeProfile][index]) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgStatus_k.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgStatus_k.kt deleted file mode 100644 index bef2e8a926..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgStatus_k.kt +++ /dev/null @@ -1,37 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRKorean.comm - -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase - -class MsgStatus_k( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : MessageBase() { - - init { - SetCommand(0x020B) - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(bytes: ByteArray) { - danaRPump.dailyTotalUnits = intFromBuff(bytes, 0, 3) / 750.0 - danaRPump.isExtendedInProgress = intFromBuff(bytes, 3, 1) == 1 - danaRPump.extendedBolusMinutes = intFromBuff(bytes, 4, 2) - danaRPump.extendedBolusAmount = intFromBuff(bytes, 6, 2) / 100.0 - //val lastBolusAmount = intFromBuff(bytes, 13, 2) / 100.0 - //if (lastBolusAmount != 0d) { - // pump.lastBolusTime = dateTimeFromBuff(bytes, 8); - // pump.lastBolusAmount = lastBolusAmount; - //} - danaRPump.iob = intFromBuff(bytes, 15, 2) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus min: " + danaRPump.extendedBolusMinutes) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus amount: " + danaRPump.extendedBolusAmount) - //aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + pump.lastBolusTime); - //aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + pump.lastBolusAmount); - aapsLogger.debug(LTag.PUMPCOMM, "IOB: " + danaRPump.iob) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java deleted file mode 100644 index 2227c905a9..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/DanaRSPlugin.java +++ /dev/null @@ -1,833 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS; - -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.ServiceConnection; -import android.os.IBinder; - -import androidx.annotation.NonNull; -import androidx.preference.Preference; - -import org.jetbrains.annotations.NotNull; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.List; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.DetailedBolusInfo; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.db.ExtendedBolus; -import info.nightscout.androidaps.db.TemporaryBasal; -import info.nightscout.androidaps.events.EventAppExit; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; -import info.nightscout.androidaps.interfaces.Constraint; -import info.nightscout.androidaps.interfaces.ConstraintsInterface; -import info.nightscout.androidaps.interfaces.DanaRInterface; -import info.nightscout.androidaps.interfaces.PluginDescription; -import info.nightscout.androidaps.interfaces.PluginType; -import info.nightscout.androidaps.interfaces.PumpDescription; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.interfaces.PumpPluginBase; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; -import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; -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.pump.common.bolusInfo.DetailedBolusInfoStorage; -import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRFragment; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange; -import info.nightscout.androidaps.plugins.pump.danaRS.services.DanaRSService; -import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.Round; -import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.TimeChangeType; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -@Singleton -public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaRInterface, ConstraintsInterface { - private CompositeDisposable disposable = new CompositeDisposable(); - - private final Context context; - private final ResourceHelper resourceHelper; - private final ConstraintChecker constraintChecker; - private final ProfileFunction profileFunction; - private final TreatmentsPlugin treatmentsPlugin; - private final SP sp; - private final RxBusWrapper rxBus; - private final CommandQueueProvider commandQueue; - private final DanaRPump danaRPump; - private final DetailedBolusInfoStorage detailedBolusInfoStorage; - - private static DanaRSService danaRSService; - - private static String mDeviceAddress = ""; - public static String mDeviceName = ""; - - public static PumpDescription pumpDescription = new PumpDescription(); - - // Bolus & history handling - public int bolusStartErrorCode; // from start message - public Treatment bolusingTreatment; // actually delivered treatment - public double bolusAmountToBeDelivered = 0.0; // amount to be delivered - public boolean bolusStopped = false; // bolus finished - public boolean bolusStopForced = false; // bolus forced to stop by user - public boolean bolusDone = false; // success end - public long bolusProgressLastTimeStamp = 0; // timestamp of last bolus progress message - public boolean apsHistoryDone = false; // true when last history message is received - public long lastEventTimeLoaded = 0; // timestamp of last received event - - @Inject - public DanaRSPlugin( - HasAndroidInjector injector, - AAPSLogger aapsLogger, - RxBusWrapper rxBus, - Context context, - ResourceHelper resourceHelper, - ConstraintChecker constraintChecker, - ProfileFunction profileFunction, - TreatmentsPlugin treatmentsPlugin, - SP sp, - CommandQueueProvider commandQueue, - DanaRPump danaRPump, - DetailedBolusInfoStorage detailedBolusInfoStorage - ) { - super(new PluginDescription() - .mainType(PluginType.PUMP) - .fragmentClass(DanaRFragment.class.getName()) - .pluginName(R.string.danarspump) - .shortName(R.string.danarspump_shortname) - .preferencesId(R.xml.pref_danars) - .description(R.string.description_pump_dana_rs), - injector, aapsLogger, resourceHelper, commandQueue - ); - this.context = context; - this.rxBus = rxBus; - this.resourceHelper = resourceHelper; - this.constraintChecker = constraintChecker; - this.profileFunction = profileFunction; - this.treatmentsPlugin = treatmentsPlugin; - this.sp = sp; - this.commandQueue = commandQueue; - this.danaRPump = danaRPump; - this.detailedBolusInfoStorage = detailedBolusInfoStorage; - - pumpDescription.setPumpDescription(PumpType.DanaRS); - } - - @Override - public void updatePreferenceSummary(@NotNull Preference pref) { - super.updatePreferenceSummary(pref); - - if (pref.getKey().equals(resourceHelper.gs(R.string.key_danars_name))) - pref.setSummary(sp.getString(R.string.key_danars_name, "")); - } - - @Override - protected void onStart() { - Intent intent = new Intent(context, DanaRSService.class); - context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE); - - disposable.add(rxBus - .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) - .subscribe(event -> context.unbindService(mConnection), exception -> FabricPrivacy.getInstance().logException(exception)) - ); - disposable.add(rxBus - .toObservable(EventDanaRSDeviceChange.class) - .observeOn(Schedulers.io()) - .subscribe(event -> loadAddress(), exception -> FabricPrivacy.getInstance().logException(exception)) - ); - loadAddress(); // load device name - super.onStart(); - } - - @Override - protected void onStop() { - context.unbindService(mConnection); - - disposable.clear(); - super.onStop(); - } - - private ServiceConnection mConnection = new ServiceConnection() { - - public void onServiceDisconnected(ComponentName name) { - getAapsLogger().debug(LTag.PUMP, "Service is disconnected"); - danaRSService = null; - } - - public void onServiceConnected(ComponentName name, IBinder service) { - getAapsLogger().debug(LTag.PUMP, "Service is connected"); - DanaRSService.LocalBinder mLocalBinder = (DanaRSService.LocalBinder) service; - danaRSService = mLocalBinder.getServiceInstance(); - } - }; - - private void loadAddress() { - mDeviceAddress = sp.getString(R.string.key_danars_address, ""); - mDeviceName = sp.getString(R.string.key_danars_name, ""); - } - - @Override - public void connect(String from) { - getAapsLogger().debug(LTag.PUMP, "RS connect from: " + from); - if (danaRSService != null && !mDeviceAddress.equals("") && !mDeviceName.equals("")) { - final Object o = new Object(); - - danaRSService.connect(from, mDeviceAddress, o); - } - } - - @Override - public boolean isConnected() { - return danaRSService != null && danaRSService.isConnected(); - } - - @Override - public boolean isConnecting() { - return danaRSService != null && danaRSService.isConnecting(); - } - - @Override - public boolean isHandshakeInProgress() { - return false; - } - - @Override - public void finishHandshaking() { - } - - @Override - public void disconnect(String from) { - getAapsLogger().debug(LTag.PUMP, "RS disconnect from: " + from); - if (danaRSService != null) danaRSService.disconnect(from); - } - - @Override - public void stopConnecting() { - if (danaRSService != null) danaRSService.stopConnecting(); - } - - @Override - public void getPumpStatus() { - if (danaRSService != null) { - danaRSService.getPumpStatus(); - pumpDescription.basalStep = danaRPump.getBasalStep(); - pumpDescription.bolusStep = danaRPump.getBolusStep(); - } - } - - // DanaR interface - - @Override - public PumpEnactResult loadHistory(byte type) { - return danaRSService.loadHistory(type); - } - - @Override - public PumpEnactResult loadEvents() { - return danaRSService.loadEvents(); - } - - @Override - public PumpEnactResult setUserOptions() { - return danaRSService.setUserSettings(); - } - - // Constraints interface - - @NonNull - @Override - public Constraint applyBasalConstraints(Constraint absoluteRate, @NonNull Profile profile) { - absoluteRate.setIfSmaller(getAapsLogger(), danaRPump.getMaxBasal(), resourceHelper.gs(R.string.limitingbasalratio, danaRPump.getMaxBasal(), resourceHelper.gs(R.string.pumplimit)), this); - return absoluteRate; - } - - @NonNull - @Override - public Constraint applyBasalPercentConstraints(Constraint percentRate, @NonNull Profile profile) { - percentRate.setIfGreater(getAapsLogger(), 0, resourceHelper.gs(R.string.limitingpercentrate, 0, resourceHelper.gs(R.string.itmustbepositivevalue)), this); - percentRate.setIfSmaller(getAapsLogger(), getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.limitingpercentrate, getPumpDescription().maxTempPercent, resourceHelper.gs(R.string.pumplimit)), this); - - return percentRate; - } - - - @NonNull - @Override - public Constraint applyBolusConstraints(Constraint insulin) { - insulin.setIfSmaller(getAapsLogger(), danaRPump.getMaxBolus(), resourceHelper.gs(R.string.limitingbolus, danaRPump.getMaxBolus(), resourceHelper.gs(R.string.pumplimit)), this); - return insulin; - } - - @NonNull - @Override - public Constraint applyExtendedBolusConstraints(@NonNull Constraint insulin) { - return applyBolusConstraints(insulin); - } - - // Pump interface - - @Override - public boolean isInitialized() { - return danaRPump.getLastConnection() > 0 && danaRPump.getMaxBasal() > 0; - } - - @Override - public boolean isSuspended() { - return danaRPump.getPumpSuspended(); - } - - @Override - public boolean isBusy() { - if (danaRSService == null) return false; - return danaRSService.isConnected() || danaRSService.isConnecting(); - } - - @NonNull @Override - public PumpEnactResult setNewBasalProfile(Profile profile) { - PumpEnactResult result = new PumpEnactResult(getInjector()); - - if (danaRSService == null) { - getAapsLogger().error("setNewBasalProfile sExecutionService is null"); - result.comment = "setNewBasalProfile sExecutionService is null"; - return result; - } - if (!isInitialized()) { - getAapsLogger().error("setNewBasalProfile not initialized"); - Notification notification = new Notification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED, resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet), Notification.URGENT); - rxBus.send(new EventNewNotification(notification)); - result.comment = resourceHelper.gs(R.string.pumpNotInitializedProfileNotSet); - return result; - } else { - rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); - } - if (!danaRSService.updateBasalsInPump(profile)) { - Notification notification = new Notification(Notification.FAILED_UDPATE_PROFILE, resourceHelper.gs(R.string.failedupdatebasalprofile), Notification.URGENT); - rxBus.send(new EventNewNotification(notification)); - result.comment = resourceHelper.gs(R.string.failedupdatebasalprofile); - return result; - } else { - rxBus.send(new EventDismissNotification(Notification.PROFILE_NOT_SET_NOT_INITIALIZED)); - rxBus.send(new EventDismissNotification(Notification.FAILED_UDPATE_PROFILE)); - Notification notification = new Notification(Notification.PROFILE_SET_OK, resourceHelper.gs(R.string.profile_set_ok), Notification.INFO, 60); - rxBus.send(new EventNewNotification(notification)); - result.success = true; - result.enacted = true; - result.comment = "OK"; - return result; - } - } - - @Override - public boolean isThisProfileSet(Profile profile) { - if (!isInitialized()) - return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS - if (danaRPump.getPumpProfiles() == null) - return true; // TODO: not sure what's better. so far TRUE to prevent too many SMS - int basalValues = danaRPump.getBasal48Enable() ? 48 : 24; - int basalIncrement = danaRPump.getBasal48Enable() ? 30 * 60 : 60 * 60; - for (int h = 0; h < basalValues; h++) { - Double pumpValue = danaRPump.getPumpProfiles()[danaRPump.getActiveProfile()][h]; - Double profileValue = profile.getBasalTimeFromMidnight(h * basalIncrement); - if (Math.abs(pumpValue - profileValue) > getPumpDescription().basalStep) { - getAapsLogger().debug(LTag.PUMP, "Diff found. Hour: " + h + " Pump: " + pumpValue + " Profile: " + profileValue); - return false; - } - } - return true; - } - - @Override - public long lastDataTime() { - return danaRPump.getLastConnection(); - } - - @Override - public double getBaseBasalRate() { - return danaRPump.getCurrentBasal(); - } - - @Override - public double getReservoirLevel() { - return danaRPump.getReservoirRemainingUnits(); - } - - @Override - public int getBatteryLevel() { - return danaRPump.getBatteryRemaining(); - } - - @NonNull @Override - public synchronized PumpEnactResult deliverTreatment(DetailedBolusInfo detailedBolusInfo) { - detailedBolusInfo.insulin = constraintChecker.applyBolusConstraints(new Constraint<>(detailedBolusInfo.insulin)).value(); - if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { - int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0); - int speed = 12; - switch (preferencesSpeed) { - case 0: - speed = 12; - break; - case 1: - speed = 30; - break; - case 2: - speed = 60; - break; - } - // RS stores end time for bolus, we need to adjust time - // default delivery speed is 12 sec/U - detailedBolusInfo.date = DateUtil.now() + (long) (speed * detailedBolusInfo.insulin * 1000); - // clean carbs to prevent counting them as twice because they will picked up as another record - // I don't think it's necessary to copy DetailedBolusInfo right now for carbs records - double carbs = detailedBolusInfo.carbs; - detailedBolusInfo.carbs = 0; - int carbTime = detailedBolusInfo.carbTime; - if (carbTime == 0) carbTime--; // better set 1 min back to prevents clash with insulin - detailedBolusInfo.carbTime = 0; - - detailedBolusInfoStorage.add(detailedBolusInfo); // will be picked up on reading history - - Treatment t = new Treatment(); - t.isSMB = detailedBolusInfo.isSMB; - boolean connectionOK = false; - if (detailedBolusInfo.insulin > 0 || carbs > 0) - connectionOK = danaRSService.bolus(detailedBolusInfo.insulin, (int) carbs, DateUtil.now() + T.mins(carbTime).msecs(), t); - PumpEnactResult result = new PumpEnactResult(getInjector()); - result.success = connectionOK && Math.abs(detailedBolusInfo.insulin - t.insulin) < pumpDescription.bolusStep; - result.bolusDelivered = t.insulin; - result.carbsDelivered = detailedBolusInfo.carbs; - if (!result.success) { - String error = "" + bolusStartErrorCode; - switch (bolusStartErrorCode) { - // 4 reported as max bolus violation. Check later - case 0x10: - error = resourceHelper.gs(R.string.maxbolusviolation); - break; - case 0x20: - error = resourceHelper.gs(R.string.commanderror); - break; - case 0x40: - error = resourceHelper.gs(R.string.speederror); - break; - case 0x80: - error = resourceHelper.gs(R.string.insulinlimitviolation); - break; - } - result.comment = String.format(resourceHelper.gs(R.string.boluserrorcode), detailedBolusInfo.insulin, t.insulin, error); - } else - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "deliverTreatment: OK. Asked: " + detailedBolusInfo.insulin + " Delivered: " + result.bolusDelivered); - return result; - } else { - PumpEnactResult result = new PumpEnactResult(getInjector()); - result.success = false; - result.bolusDelivered = 0d; - result.carbsDelivered = 0d; - result.comment = resourceHelper.gs(R.string.danar_invalidinput); - getAapsLogger().error("deliverTreatment: Invalid input"); - return result; - } - } - - @Override - public void stopBolusDelivering() { - if (danaRSService == null) { - getAapsLogger().error("stopBolusDelivering sExecutionService is null"); - return; - } - danaRSService.bolusStop(); - } - - // This is called from APS - @NonNull @Override - public synchronized PumpEnactResult setTempBasalAbsolute(Double absoluteRate, Integer durationInMinutes, Profile profile, boolean enforceNew) { - // Recheck pump status if older than 30 min - - //This should not be needed while using queue because connection should be done before calling this - //if (pump.lastConnection.getTime() + 30 * 60 * 1000L < System.currentTimeMillis()) { - // connect("setTempBasalAbsolute old data"); - //} - - PumpEnactResult result = new PumpEnactResult(getInjector()); - - absoluteRate = constraintChecker.applyBasalConstraints(new Constraint<>(absoluteRate), profile).value(); - - final boolean doTempOff = getBaseBasalRate() - absoluteRate == 0d; - final boolean doLowTemp = absoluteRate < getBaseBasalRate(); - final boolean doHighTemp = absoluteRate > getBaseBasalRate(); - - if (doTempOff) { - // If temp in progress - if (treatmentsPlugin.isTempBasalInProgress()) { - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Stopping temp basal (doTempOff)"); - return cancelTempBasal(false); - } - result.success = true; - result.enacted = false; - result.percent = 100; - result.isPercent = true; - result.isTempCancel = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: doTempOff OK"); - return result; - } - - if (doLowTemp || doHighTemp) { - Integer percentRate = Double.valueOf(absoluteRate / getBaseBasalRate() * 100).intValue(); - if (percentRate < 100) percentRate = Round.ceilTo((double) percentRate, 10d).intValue(); - else percentRate = Round.floorTo((double) percentRate, 10d).intValue(); - if (percentRate > 500) // Special high temp 500/15min - percentRate = 500; - // Check if some temp is already in progress - TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: currently running: " + activeTemp.toString()); - // Correct basal already set ? - if (activeTemp.percentRate == percentRate && activeTemp.getPlannedRemainingMinutes() > 4) { - if (!enforceNew) { - result.success = true; - result.percent = percentRate; - result.enacted = false; - result.duration = activeTemp.getPlannedRemainingMinutes(); - result.isPercent = true; - result.isTempCancel = false; - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Correct temp basal already set (doLowTemp || doHighTemp)"); - return result; - } - } - } - // Convert duration from minutes to hours - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: Setting temp basal " + percentRate + "% for " + durationInMinutes + " mins (doLowTemp || doHighTemp)"); - if (percentRate == 0 && durationInMinutes > 30) { - result = setTempBasalPercent(percentRate, durationInMinutes, profile, enforceNew); - } else { - // use special APS temp basal call ... 100+/15min .... 100-/30min - result = setHighTempBasalPercent(percentRate); - } - if (!result.success) { - getAapsLogger().error("setTempBasalAbsolute: Failed to set hightemp basal"); - return result; - } - getAapsLogger().debug(LTag.PUMP, "setTempBasalAbsolute: hightemp basal set ok"); - return result; - } - // We should never end here - getAapsLogger().error("setTempBasalAbsolute: Internal error"); - result.success = false; - result.comment = "Internal error"; - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult setTempBasalPercent(Integer percent, Integer durationInMinutes, Profile profile, boolean enforceNew) { - DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(getInjector()); - percent = constraintChecker.applyBasalPercentConstraints(new Constraint<>(percent), profile).value(); - if (percent < 0) { - result.isTempCancel = false; - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_invalidinput); - getAapsLogger().error("setTempBasalPercent: Invalid input"); - return result; - } - if (percent > getPumpDescription().maxTempPercent) - percent = getPumpDescription().maxTempPercent; - long now = System.currentTimeMillis(); - TemporaryBasal activeTemp = treatmentsPlugin.getTempBasalFromHistory(now); - if (activeTemp != null && activeTemp.percentRate == percent && activeTemp.getPlannedRemainingMinutes() > 4 && !enforceNew) { - result.enacted = false; - result.success = true; - result.isTempCancel = false; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: Correct value already set"); - return result; - } - boolean connectionOK; - if (durationInMinutes == 15 || durationInMinutes == 30) { - connectionOK = danaRSService.tempBasalShortDuration(percent, durationInMinutes); - } else { - int durationInHours = Math.max(durationInMinutes / 60, 1); - connectionOK = danaRSService.tempBasal(percent, durationInHours); - } - if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setTempBasalPercent: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.tempbasaldeliveryerror); - getAapsLogger().error("setTempBasalPercent: Failed to set temp basal"); - return result; - } - - private synchronized PumpEnactResult setHighTempBasalPercent(Integer percent) { - DanaRPump pump = danaRPump; - PumpEnactResult result = new PumpEnactResult(getInjector()); - boolean connectionOK = danaRSService.highTempBasal(percent); - if (connectionOK && pump.isTempBasalInProgress() && pump.getTempBasalPercent() == percent) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getTempBasalRemainingMin(); - result.percent = pump.getTempBasalPercent(); - result.isPercent = true; - getAapsLogger().debug(LTag.PUMP, "setHighTempBasalPercent: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("setHighTempBasalPercent: Failed to set temp basal"); - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { - DanaRPump pump = danaRPump; - insulin = constraintChecker.applyExtendedBolusConstraints(new Constraint<>(insulin)).value(); - // needs to be rounded - int durationInHalfHours = Math.max(durationInMinutes / 30, 1); - insulin = Round.roundTo(insulin, getPumpDescription().extendedBolusStep); - PumpEnactResult result = new PumpEnactResult(getInjector()); - ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (runningEB != null && Math.abs(runningEB.insulin - insulin) < getPumpDescription().extendedBolusStep) { - result.enacted = false; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.duration = pump.getExtendedBolusRemainingMinutes(); - result.absolute = pump.getExtendedBolusAbsoluteRate(); - result.isPercent = false; - result.isTempCancel = false; - getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: Correct extended bolus already set. Current: " + pump.getExtendedBolusAmount() + " Asked: " + insulin); - return result; - } - boolean connectionOK = danaRSService.extendedBolus(insulin, durationInHalfHours); - if (connectionOK && pump.isExtendedInProgress() && Math.abs(pump.getExtendedBolusAbsoluteRate() - insulin) < getPumpDescription().extendedBolusStep) { - result.enacted = true; - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - result.isTempCancel = false; - result.duration = pump.getExtendedBolusRemainingMinutes(); - result.absolute = pump.getExtendedBolusAbsoluteRate(); - result.bolusDelivered = pump.getExtendedBolusAmount(); - result.isPercent = false; - getAapsLogger().debug(LTag.PUMP, "setExtendedBolus: OK"); - return result; - } - result.enacted = false; - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("setExtendedBolus: Failed to extended bolus"); - return result; - } - - @NonNull @Override - public synchronized PumpEnactResult cancelTempBasal(boolean force) { - PumpEnactResult result = new PumpEnactResult(getInjector()); - TemporaryBasal runningTB = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()); - if (runningTB != null) { - danaRSService.tempBasalStop(); - result.enacted = true; - result.isTempCancel = true; - } - if (!danaRPump.isTempBasalInProgress()) { - result.success = true; - result.isTempCancel = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "cancelRealTempBasal: OK"); - return result; - } else { - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - result.isTempCancel = true; - getAapsLogger().error("cancelRealTempBasal: Failed to cancel temp basal"); - return result; - } - } - - @NonNull @Override - public synchronized PumpEnactResult cancelExtendedBolus() { - PumpEnactResult result = new PumpEnactResult(getInjector()); - ExtendedBolus runningEB = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (runningEB != null) { - danaRSService.extendedBolusStop(); - result.enacted = true; - result.isTempCancel = true; - } - if (!danaRPump.isExtendedInProgress()) { - result.success = true; - result.comment = resourceHelper.gs(R.string.virtualpump_resultok); - getAapsLogger().debug(LTag.PUMP, "cancelExtendedBolus: OK"); - return result; - } else { - result.success = false; - result.comment = resourceHelper.gs(R.string.danar_valuenotsetproperly); - getAapsLogger().error("cancelExtendedBolus: Failed to cancel extended bolus"); - return result; - } - } - - @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { - DanaRPump pump = danaRPump; - long now = System.currentTimeMillis(); - if (pump.getLastConnection() + 5 * 60 * 1000L < System.currentTimeMillis()) { - return new JSONObject(); - } - JSONObject pumpjson = new JSONObject(); - JSONObject battery = new JSONObject(); - JSONObject status = new JSONObject(); - JSONObject extended = new JSONObject(); - try { - battery.put("percent", pump.getBatteryRemaining()); - status.put("status", pump.getPumpSuspended() ? "suspended" : "normal"); - status.put("timestamp", DateUtil.toISOString(pump.getLastConnection())); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); - if (pump.getLastBolusTime() != 0) { - extended.put("LastBolus", DateUtil.dateAndTimeString(pump.getLastBolusTime())); - extended.put("LastBolusAmount", pump.getLastBolusAmount()); - } - TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now); - if (tb != null) { - extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)); - extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); - extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); - } - ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now); - if (eb != null) { - extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()); - extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date)); - extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes()); - } - extended.put("BaseBasalRate", getBaseBasalRate()); - try { - extended.put("ActiveProfile", profileFunction.getProfileName()); - } catch (Exception e) { - getAapsLogger().error("Unhandled exception", e); - } - - pumpjson.put("battery", battery); - pumpjson.put("status", status); - pumpjson.put("extended", extended); - pumpjson.put("reservoir", (int) pump.getReservoirRemainingUnits()); - pumpjson.put("clock", DateUtil.toISOString(now)); - } catch (JSONException e) { - getAapsLogger().error("Unhandled exception", e); - } - return pumpjson; - } - - @NonNull @Override - public ManufacturerType manufacturer() { - return ManufacturerType.Sooil; - } - - @NonNull @Override - public PumpType model() { - return PumpType.DanaRS; - } - - @NonNull @Override - public String serialNumber() { - return danaRPump.getSerialNumber(); - } - - @NonNull @Override - public PumpDescription getPumpDescription() { - return pumpDescription; - } - - @NonNull @Override - public String shortStatus(boolean veryShort) { - DanaRPump pump = danaRPump; - String ret = ""; - if (pump.getLastConnection() != 0) { - long agoMsec = System.currentTimeMillis() - pump.getLastConnection(); - int agoMin = (int) (agoMsec / 60d / 1000d); - ret += "LastConn: " + agoMin + " minago\n"; - } - if (pump.getLastBolusTime() != 0) { - ret += "LastBolus: " + DecimalFormatter.to2Decimal(pump.getLastBolusAmount()) + "U @" + android.text.format.DateFormat.format("HH:mm", pump.getLastBolusTime()) + "\n"; - } - TemporaryBasal activeTemp = treatmentsPlugin.getRealTempBasalFromHistory(System.currentTimeMillis()); - if (activeTemp != null) { - ret += "Temp: " + activeTemp.toStringFull() + "\n"; - } - ExtendedBolus activeExtendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()); - if (activeExtendedBolus != null) { - ret += "Extended: " + activeExtendedBolus.toString() + "\n"; - } - if (!veryShort) { - ret += "TDD: " + DecimalFormatter.to0Decimal(pump.getDailyTotalUnits()) + " / " + pump.getMaxDailyTotalUnits() + " U\n"; - } - ret += "Reserv: " + DecimalFormatter.to0Decimal(pump.getReservoirRemainingUnits()) + "U\n"; - ret += "Batt: " + pump.getBatteryRemaining() + "\n"; - return ret; - } - - @Override - public boolean isFakingTempsByExtendedBoluses() { - return false; - } - - @NonNull @Override - public PumpEnactResult loadTDDs() { - return loadHistory(RecordTypes.RECORD_TYPE_DAILY); - } - - @Override - public List getCustomActions() { - return null; - } - - @Override - public void executeCustomAction(CustomActionType customActionType) { - - } - - @Override - public boolean canHandleDST() { - return false; - } - - @Override - public void timezoneOrDSTChanged(TimeChangeType changeType) { - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java deleted file mode 100644 index 89f794259e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/BLEScanActivity.java +++ /dev/null @@ -1,217 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.activities; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.le.BluetoothLeScanner; -import android.bluetooth.le.ScanCallback; -import android.bluetooth.le.ScanResult; -import android.content.pm.ActivityInfo; -import android.os.Bundle; -import android.os.Handler; -import android.view.View; -import android.view.ViewGroup; -import android.widget.BaseAdapter; -import android.widget.ListView; -import android.widget.TextView; - -import java.util.ArrayList; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.NoSplashAppCompatActivity; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSDeviceChange; -import info.nightscout.androidaps.utils.SP; - -public class BLEScanActivity extends NoSplashAppCompatActivity { - private ListAdapter mListAdapter = null; - private ArrayList mDevices = new ArrayList<>(); - - private BluetoothLeScanner mBluetoothLeScanner = null; - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.danars_blescanner_activity); - setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); - - mListAdapter = new ListAdapter(); - - ListView listView = findViewById(R.id.danars_blescanner_listview); - listView.setEmptyView(findViewById(R.id.danars_blescanner_nodevice)); - listView.setAdapter(mListAdapter); - - mListAdapter.notifyDataSetChanged(); - } - - @Override - protected void onResume() { - super.onResume(); - - BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); - if (mBluetoothAdapter != null) { - if (!mBluetoothAdapter.isEnabled()) mBluetoothAdapter.enable(); - mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); - - if (mBluetoothLeScanner == null) { - mBluetoothAdapter.enable(); - mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); - } - startScan(); - } - } - - @Override - protected void onPause() { - super.onPause(); - - stopScan(); - } - - private void startScan() { - if (mBluetoothLeScanner != null) - mBluetoothLeScanner.startScan(mBleScanCallback); - } - - private void stopScan() { - if (mBluetoothLeScanner != null) - mBluetoothLeScanner.stopScan(mBleScanCallback); - } - - private void addBleDevice(BluetoothDevice device) { - if (device == null || device.getName() == null || device.getName().equals("")) { - return; - } - BluetoothDeviceItem item = new BluetoothDeviceItem(device); - if (!isSNCheck(device.getName()) || mDevices.contains(item)) { - return; - } - - mDevices.add(item); - new Handler().post(() -> mListAdapter.notifyDataSetChanged()); - } - - private ScanCallback mBleScanCallback = new ScanCallback() { - @Override - public void onScanResult(int callbackType, ScanResult result) { - addBleDevice(result.getDevice()); - } - }; - - class ListAdapter extends BaseAdapter { - - @Override - public int getCount() { - return mDevices.size(); - } - - @Override - public BluetoothDeviceItem getItem(int i) { - return mDevices.get(i); - } - - @Override - public long getItemId(int i) { - return 0; - } - - @Override - public View getView(int i, View convertView, ViewGroup parent) { - View v = convertView; - ViewHolder holder; - - if (v == null) { - v = View.inflate(getApplicationContext(), R.layout.danars_blescanner_item, null); - holder = new ViewHolder(v); - v.setTag(holder); - } else { - holder = (ViewHolder) v.getTag(); - } - - BluetoothDeviceItem item = getItem(i); - holder.setData(item); - return v; - } - - private class ViewHolder implements View.OnClickListener { - private BluetoothDeviceItem item = null; - - private TextView mName; - private TextView mAddress; - - ViewHolder(View v) { - mName = v.findViewById(R.id.ble_name); - mAddress = v.findViewById(R.id.ble_address); - - v.setOnClickListener(ViewHolder.this); - } - - @Override - public void onClick(View v) { - SP.putString(R.string.key_danars_address, item.device.getAddress()); - SP.putString(R.string.key_danars_name, mName.getText().toString()); - item.device.createBond(); - RxBus.Companion.getINSTANCE().send(new EventDanaRSDeviceChange()); - finish(); - } - - public void setData(BluetoothDeviceItem data) { - if (data != null) { - try { - String tTitle = data.device.getName(); - if (tTitle == null || tTitle.equals("")) { - tTitle = "(unknown)"; - } else if (tTitle.length() > 10) { - tTitle = tTitle.substring(0, 10); - } - mName.setText(tTitle); - - mAddress.setText(data.device.getAddress()); - - item = data; - } catch (Exception ignored) { - } - } - } - } - } - - // - private class BluetoothDeviceItem { - private BluetoothDevice device; - - BluetoothDeviceItem(BluetoothDevice device) { - super(); - this.device = device; - } - - @Override - public boolean equals(Object o) { - if (device == null || !(o instanceof BluetoothDeviceItem)) { - return false; - } - BluetoothDeviceItem checkItem = (BluetoothDeviceItem) o; - if (checkItem.device == null) { - return false; - } - return stringEquals(device.getAddress(), checkItem.device.getAddress()); - } - - boolean stringEquals(String arg1, String arg2) { - try { - return arg1.equals(arg2); - } catch (Exception e) { - return false; - } - } - } - - public static boolean isSNCheck(String sn) { - String regex = "^([a-zA-Z]{3})([0-9]{5})([a-zA-Z]{2})$"; - Pattern p = Pattern.compile(regex); - Matcher m = p.matcher(sn); - - return m.matches(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt deleted file mode 100644 index ba73e1b368..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/activities/PairingHelperActivity.kt +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.activities - -import android.content.pm.ActivityInfo -import android.os.Bundle -import info.nightscout.androidaps.activities.NoSplashAppCompatActivity -import info.nightscout.androidaps.plugins.pump.danaRS.dialogs.PairingProgressDialog - -class PairingHelperActivity : NoSplashAppCompatActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - PairingProgressDialog() - .setHelperActivity(this) - .show(supportFragmentManager, "PairingProgress") - requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt deleted file mode 100644 index 2edf5254b3..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRSMessageHashTable.kt +++ /dev/null @@ -1,107 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class DanaRSMessageHashTable @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - danaRPump: DanaRPump, - danaRSPlugin: DanaRSPlugin, - activePlugin: ActivePluginProvider, - constraintChecker: ConstraintChecker, - detailedBolusInfoStorage: DetailedBolusInfoStorage, - injector: HasAndroidInjector -) { - - var messages: HashMap = HashMap() - - fun put(message: DanaRS_Packet) { - messages[message.command] = message - } - - fun findMessage(command: Int): DanaRS_Packet { - return messages[command] ?: DanaRS_Packet() - } - - init { - put(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)) - put(DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)) - put(DanaRS_Packet_Basal_Get_Profile_Basal_Rate(aapsLogger, danaRPump)) - put(DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump)) - put(DanaRS_Packet_Basal_Set_Basal_Rate(aapsLogger, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, arrayOf())) - put(DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Suspend_Off(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Suspend_On(aapsLogger)) - put(DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger)) - put(DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Initial_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Carbohydrate_Calculation_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Dual_Bolus(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Extended_Menu_Option_State(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Bolus_Set_Bolus_Option(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Initial_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_CIR_CF_Array(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Dual_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker)) - put(DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Etc_Keep_Connection(aapsLogger)) - put(DanaRS_Packet_Etc_Set_History_Save(aapsLogger)) - put(DanaRS_Packet_General_Delivery_Status(aapsLogger)) - put(DanaRS_Packet_General_Get_Password(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_Notify_Alarm(aapsLogger, resourceHelper)) - put(DanaRS_Packet_Notify_Delivery_Complete(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Notify_Delivery_Rate_Display(aapsLogger, rxBus, resourceHelper, danaRSPlugin)) - put(DanaRS_Packet_Notify_Missed_Bolus_Alarm(aapsLogger)) - put(DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump)) - put(DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)) - put(DanaRS_Packet_Option_Set_Pump_Time(aapsLogger)) - put(DanaRS_Packet_Option_Set_User_Option(aapsLogger, danaRPump)) - //put(new DanaRS_Packet_History_()); - put(DanaRS_Packet_History_Alarm(aapsLogger, rxBus)) - put(DanaRS_Packet_History_All_History(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Basal(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Bolus(aapsLogger, rxBus)) - put(DanaRS_Packet_Review_Bolus_Avg(aapsLogger)) - put(DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Daily(aapsLogger, rxBus)) - put(DanaRS_Packet_General_Get_More_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper)) - put(DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Get_Today_Delivery_Total(aapsLogger, danaRPump)) - put(DanaRS_Packet_General_Get_User_Time_Change_Flag(aapsLogger)) - put(DanaRS_Packet_History_Prime(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Refill(aapsLogger, rxBus)) - put(DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger)) - put(DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear(aapsLogger)) - put(DanaRS_Packet_History_Suspend(aapsLogger, rxBus)) - put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus)) - // APS - put(DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, 0)) - put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector,0)) - put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, 0, 0, 0, 0)) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt deleted file mode 100644 index 4681e68e92..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_History_Events.kt +++ /dev/null @@ -1,203 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.R -import info.nightscout.androidaps.data.DetailedBolusInfo -import info.nightscout.androidaps.db.ExtendedBolus -import info.nightscout.androidaps.db.Source -import info.nightscout.androidaps.db.TemporaryBasal -import info.nightscout.androidaps.events.EventPumpStatusChanged -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin -import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* - -open class DanaRS_Packet_APS_History_Events( - private val aapsLogger: AAPSLogger, - private val rxBus: RxBusWrapper, - private val resourceHelper: ResourceHelper, - private val activePlugin: ActivePluginProvider, - private val danaRSPlugin: DanaRSPlugin, - private val detailedBolusInfoStorage: DetailedBolusInfoStorage, - private val injector: HasAndroidInjector, - private var from: Long -) : DanaRS_Packet() { - - private var year = 0 - private var month = 0 - private var day = 0 - private var hour = 0 - private var min = 0 - private var sec = 0 - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE__APS_HISTORY_EVENTS - val cal = GregorianCalendar() - if (from > DateUtil.now()) { - aapsLogger.debug(LTag.PUMPCOMM, "Asked to load from the future") - from = 0 - } - if (from != 0L) cal.timeInMillis = from else cal[2000, 0, 1, 0, 0] = 0 - year = cal[Calendar.YEAR] - 1900 - 100 - month = cal[Calendar.MONTH] + 1 - day = cal[Calendar.DAY_OF_MONTH] - hour = cal[Calendar.HOUR_OF_DAY] - min = cal[Calendar.MINUTE] - sec = cal[Calendar.SECOND] - aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + DateUtil.dateAndTimeString(cal.timeInMillis)) - danaRSPlugin.apsHistoryDone = false - } - - override fun getRequestParams(): ByteArray { - val request = ByteArray(6) - request[0] = (year and 0xff).toByte() - request[1] = (month and 0xff).toByte() - request[2] = (day and 0xff).toByte() - request[3] = (hour and 0xff).toByte() - request[4] = (min and 0xff).toByte() - request[5] = (sec and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - val recordCode = intFromBuff(data, 0, 1).toByte() - // Last record - if (recordCode == 0xFF.toByte()) { - danaRSPlugin.apsHistoryDone = true - aapsLogger.debug(LTag.PUMPCOMM, "Last record received") - return - } - val datetime = dateTimeSecFromBuff(data, 1) // 6 bytes - val param1 = (intFromBuff(data, 7, 1) shl 8 and 0xFF00) + (intFromBuff(data, 8, 1) and 0xFF) - val param2 = (intFromBuff(data, 9, 1) shl 8 and 0xFF00) + (intFromBuff(data, 10, 1) and 0xFF) - val temporaryBasal = TemporaryBasal(injector).date(datetime).source(Source.PUMP).pumpId(datetime) - val extendedBolus = ExtendedBolus(injector).date(datetime).source(Source.PUMP).pumpId(datetime) - val status: String - when (recordCode.toInt()) { - DanaRPump.TEMPSTART -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT TEMPSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") - temporaryBasal.percentRate = param1 - temporaryBasal.durationInMinutes = param2 - activePlugin.activeTreatments.addToHistoryTempBasal(temporaryBasal) - status = "TEMPSTART " + DateUtil.timeString(datetime) - } - - DanaRPump.TEMPSTOP -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime)) - activePlugin.activeTreatments.addToHistoryTempBasal(temporaryBasal) - status = "TEMPSTOP " + DateUtil.timeString(datetime) - } - - DanaRPump.EXTENDEDSTART -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT EXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") - extendedBolus.insulin = param1 / 100.0 - extendedBolus.durationInMinutes = param2 - activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus) - status = "EXTENDEDSTART " + DateUtil.timeString(datetime) - } - - DanaRPump.EXTENDEDSTOP -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT EXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") - activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus) - status = "EXTENDEDSTOP " + DateUtil.timeString(datetime) - } - - DanaRPump.BOLUS -> { - val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0) - ?: DetailedBolusInfo() - detailedBolusInfo.date = datetime - detailedBolusInfo.source = Source.PUMP - detailedBolusInfo.pumpId = datetime - detailedBolusInfo.insulin = param1 / 100.0 - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) - aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") - status = "BOLUS " + DateUtil.timeString(datetime) - } - - DanaRPump.DUALBOLUS -> { - val detailedBolusInfo = detailedBolusInfoStorage.findDetailedBolusInfo(datetime, param1 / 100.0) - ?: DetailedBolusInfo() - detailedBolusInfo.date = datetime - detailedBolusInfo.source = Source.PUMP - detailedBolusInfo.pumpId = datetime - detailedBolusInfo.insulin = param1 / 100.0 - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(detailedBolusInfo, false) - aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") - status = "DUALBOLUS " + DateUtil.timeString(datetime) - } - - DanaRPump.DUALEXTENDEDSTART -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") - extendedBolus.insulin = param1 / 100.0 - extendedBolus.durationInMinutes = param2 - activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus) - status = "DUALEXTENDEDSTART " + DateUtil.timeString(datetime) - } - - DanaRPump.DUALEXTENDEDSTOP -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") - activePlugin.activeTreatments.addToHistoryExtendedBolus(extendedBolus) - status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime) - } - - DanaRPump.SUSPENDON -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT SUSPENDON (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") - status = "SUSPENDON " + DateUtil.timeString(datetime) - } - - DanaRPump.SUSPENDOFF -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT SUSPENDOFF (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") - status = "SUSPENDOFF " + DateUtil.timeString(datetime) - } - - DanaRPump.REFILL -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT REFILL (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") - status = "REFILL " + DateUtil.timeString(datetime) - } - - DanaRPump.PRIME -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT PRIME (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") - status = "PRIME " + DateUtil.timeString(datetime) - } - - DanaRPump.PROFILECHANGE -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT PROFILECHANGE (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h") - status = "PROFILECHANGE " + DateUtil.timeString(datetime) - } - - DanaRPump.CARBS -> { - val emptyCarbsInfo = DetailedBolusInfo() - emptyCarbsInfo.carbs = param1.toDouble() - emptyCarbsInfo.date = datetime - emptyCarbsInfo.source = Source.PUMP - emptyCarbsInfo.pumpId = datetime - val newRecord = activePlugin.activeTreatments.addToHistoryTreatment(emptyCarbsInfo, false) - aapsLogger.debug(LTag.PUMPCOMM, (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") - status = "CARBS " + DateUtil.timeString(datetime) - } - - DanaRPump.PRIMECANNULA -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT PRIMECANNULA(" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") - status = "PRIMECANNULA " + DateUtil.timeString(datetime) - } - - else -> { - aapsLogger.debug(LTag.PUMPCOMM, "Event: " + recordCode + " " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2) - status = "UNKNOWN " + DateUtil.timeString(datetime) - } - } - if (datetime > danaRSPlugin.lastEventTimeLoaded) danaRSPlugin.lastEventTimeLoaded = datetime - rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.processinghistory) + ": " + status)) - } - - override fun getFriendlyName(): String { - return "APS_HISTORY_EVENTS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_History.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_History.kt deleted file mode 100644 index 266554d3be..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_APS_Set_Event_History.kt +++ /dev/null @@ -1,62 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_APS_Set_Event_History( - private val aapsLogger: AAPSLogger, - private var packetType: Int, - private var time: Long, - private var param1: Int, - private var param2: Int -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE__APS_SET_EVENT_HISTORY - if ((packetType == DanaRPump.CARBS || packetType == DanaRPump.BOLUS) && param1 <= 0) this.param1 = 0 - aapsLogger.debug(LTag.PUMPCOMM, "Set history entry: " + DateUtil.dateAndTimeString(time) + " type: " + packetType + " param1: " + param1 + " param2: " + param2) - } - - override fun getRequestParams(): ByteArray { - val cal = GregorianCalendar() - cal.timeInMillis = time - val year = cal[Calendar.YEAR] - 1900 - 100 - val month = cal[Calendar.MONTH] + 1 - val day = cal[Calendar.DAY_OF_MONTH] - val hour = cal[Calendar.HOUR_OF_DAY] - val min = cal[Calendar.MINUTE] - val sec = cal[Calendar.SECOND] - val request = ByteArray(11) - request[0] = (packetType and 0xff).toByte() - request[1] = (year and 0xff).toByte() - request[2] = (month and 0xff).toByte() - request[3] = (day and 0xff).toByte() - request[4] = (hour and 0xff).toByte() - request[5] = (min and 0xff).toByte() - request[6] = (sec and 0xff).toByte() - request[7] = (param1 ushr 8 and 0xff).toByte() - request[8] = (param1 and 0xff).toByte() - request[9] = (param2 ushr 8 and 0xff).toByte() - request[10] = (param2 and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - val result = intFromBuff(data, 0, 1) - if (result != 0) { - failed = true - aapsLogger.error(LTag.PUMPCOMM, "Set history entry result: $result FAILED!!!") - } else { - failed = false - aapsLogger.debug(LTag.PUMPCOMM, "Set history entry result: $result") - } - } - - override fun getFriendlyName(): String { - return "APS_SET_EVENT_HISTORY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt deleted file mode 100644 index c37242b740..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Profile_Number.kt +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Basal_Get_Profile_Number( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BASAL__GET_PROFILE_NUMBER - aapsLogger.debug(LTag.PUMPCOMM, "Requesting active profile") - } - - override fun handleMessage(data: ByteArray) { - danaRPump.activeProfile = byteArrayToInt(getBytes(data, DATA_START, 1)) - aapsLogger.debug(LTag.PUMPCOMM, "Active profile: " + danaRPump.activeProfile) - } - - override fun getFriendlyName(): String { - return "BASAL__GET_PROFILE_NUMBER" - } - -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt deleted file mode 100644 index 2fbe624322..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Dual_Bolus.kt +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Dual_Bolus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_DUAL_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - val error = byteArrayToInt(getBytes(data, DATA_START, 1)) - danaRPump.bolusStep = byteArrayToInt(getBytes(data, DATA_START + 1, 2)) / 100.0 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, DATA_START + 3, 2)) / 100.0 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, DATA_START + 5, 2)) / 100.0 - val bolusIncrement = byteArrayToInt(getBytes(data, DATA_START + 7, 1)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: ${danaRPump.bolusStep} U") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: ${danaRPump.extendedBolusAbsoluteRate} U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "bolusIncrement: $bolusIncrement U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_DUAL_BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt deleted file mode 100644 index 3cd50febdb..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus.kt +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Extended_Bolus( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt deleted file mode 100644 index c48b08150b..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Extended_Bolus_State.kt +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Bolus_Get_Extended_Bolus_State( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_EXTENDED_BOLUS_STATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - dataIndex += dataSize - dataSize = 1 - danaRPump.extendedBolusMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) * 30 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusSoFarInMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusDeliveredSoFar = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "Is extended bolus running: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus running: " + danaRPump.extendedBolusAbsoluteRate + " U/h") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus duration: " + danaRPump.extendedBolusMinutes + " min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far: " + danaRPump.extendedBolusSoFarInMinutes + " min") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus delivered so far: " + danaRPump.extendedBolusDeliveredSoFar + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_EXTENDED_BOLUS_STATE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt deleted file mode 100644 index e6c8121506..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Bolus_Get_Step_Bolus_Information.kt +++ /dev/null @@ -1,60 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_BOLUS__GET_STEP_BOLUS_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val error = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val bolusType = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.initialBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - val lbt = Date() // it doesn't provide day only hour+min, workaround: expecting today - dataIndex += dataSize - dataSize = 1 - lbt.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - lbt.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - danaRPump.lastBolusTime = lbt.time - dataIndex += dataSize - dataSize = 2 - danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxBolus = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.bolusStep = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - failed = error != 0 - aapsLogger.debug(LTag.PUMPCOMM, "Result: $error") - aapsLogger.debug(LTag.PUMPCOMM, "BolusType: $bolusType") - aapsLogger.debug(LTag.PUMPCOMM, "Initial bolus amount: " + danaRPump.initialBolusAmount + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + DateUtil.dateAndTimeString(danaRPump.lastBolusTime)) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - aapsLogger.debug(LTag.PUMPCOMM, "Max bolus: " + danaRPump.maxBolus + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Bolus step: " + danaRPump.bolusStep + " U") - } - - override fun getFriendlyName(): String { - return "BOLUS__GET_STEP_BOLUS_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt deleted file mode 100644 index b8e7e6bb53..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_More_Information.kt +++ /dev/null @@ -1,62 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_General_Get_More_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_MORE_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 15) { - failed = true - return - } - var dataIndex = DATA_START - var dataSize = 2 - danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.isExtendedInProgress = byteArrayToInt(getBytes(data, dataIndex, dataSize)) == 0x01 - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusRemainingMinutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - //val remainRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - val lastBolusTime = Date() // it doesn't provide day only hour+min, workaround: expecting today - dataIndex += dataSize - dataSize = 1 - lastBolusTime.hours = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - lastBolusTime.minutes = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.lastBolusAmount = byteArrayToInt(getBytes(data, dataIndex, dataSize)).toDouble() - // On DanaRS DailyUnits can't be more than 160 - if (danaRPump.dailyTotalUnits > 160) failed = true - aapsLogger.debug(LTag.PUMPCOMM, "Daily total units: " + danaRPump.dailyTotalUnits.toString() + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Is extended in progress: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: " + danaRPump.extendedBolusRemainingMinutes) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus time: " + DateUtil.dateAndTimeAndSecondsString(lastBolusTime.time)) - aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_MORE_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt deleted file mode 100644 index 00ebd4118a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Shipping_Information.kt +++ /dev/null @@ -1,41 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil - -class DanaRS_Packet_General_Get_Shipping_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_SHIPPING_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 18) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 10 - danaRPump.serialNumber = stringFromBuff(data, dataIndex, dataSize) - dataIndex += dataSize - dataSize = 3 - danaRPump.shippingDate = dateFromBuff(data, dataIndex) - dataIndex += dataSize - dataSize = 3 - danaRPump.shippingCountry = asciiStringFromBuff(data, dataIndex, dataSize) - aapsLogger.debug(LTag.PUMPCOMM, "Serial number: " + danaRPump.serialNumber) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping date: " + DateUtil.dateAndTimeString(danaRPump.shippingDate)) - aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaRPump.shippingCountry) - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_SHIPPING_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt deleted file mode 100644 index 31310e3d08..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Get_Today_Delivery_Total.kt +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_General_Get_Today_Delivery_Total( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__GET_TODAY_DELIVERY_TOTAL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 8) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalBasalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalBolusUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Daily total: " + danaRPump.dailyTotalUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total bolus: " + danaRPump.dailyTotalBolusUnits + " U") - aapsLogger.debug(LTag.PUMPCOMM, "Daily total basal: " + danaRPump.dailyTotalBasalUnits + " U") - } - - override fun getFriendlyName(): String { - return "REVIEW__GET_TODAY_DELIVERY_TOTAL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt deleted file mode 100644 index fab00aca3d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Initial_Screen_Information.kt +++ /dev/null @@ -1,71 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_General_Initial_Screen_Information( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - type = BleCommandUtil.DANAR_PACKET__TYPE_RESPONSE - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__INITIAL_SCREEN_INFORMATION - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun handleMessage(data: ByteArray) { - if (data.size < 17) { - failed = true - return - } else failed = false - var dataIndex = DATA_START - var dataSize = 1 - val status = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - danaRPump.pumpSuspended = status and 0x01 == 0x01 - danaRPump.isTempBasalInProgress = status and 0x10 == 0x10 - danaRPump.isExtendedInProgress = status and 0x04 == 0x04 - danaRPump.isDualBolusInProgress = status and 0x08 == 0x08 - dataIndex += dataSize - dataSize = 2 - danaRPump.dailyTotalUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.maxDailyTotalUnits = (byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0).toInt() - dataIndex += dataSize - dataSize = 2 - danaRPump.reservoirRemainingUnits = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.currentBasal = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 1 - danaRPump.tempBasalPercent = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - danaRPump.batteryRemaining = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 2 - danaRPump.extendedBolusAbsoluteRate = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - dataIndex += dataSize - dataSize = 2 - danaRPump.iob = byteArrayToInt(getBytes(data, dataIndex, dataSize)) / 100.0 - aapsLogger.debug(LTag.PUMPCOMM, "Pump suspended: " + danaRPump.pumpSuspended) - aapsLogger.debug(LTag.PUMPCOMM, "Temp basal in progress: " + danaRPump.isTempBasalInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Extended in progress: " + danaRPump.isExtendedInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Dual in progress: " + danaRPump.isDualBolusInProgress) - aapsLogger.debug(LTag.PUMPCOMM, "Daily units: " + danaRPump.dailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Max daily units: " + danaRPump.maxDailyTotalUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Reservoir remaining units: " + danaRPump.reservoirRemainingUnits) - aapsLogger.debug(LTag.PUMPCOMM, "Battery: " + danaRPump.batteryRemaining) - aapsLogger.debug(LTag.PUMPCOMM, "Current basal: " + danaRPump.currentBasal) - aapsLogger.debug(LTag.PUMPCOMM, "Temp basal percent: " + danaRPump.tempBasalPercent) - aapsLogger.debug(LTag.PUMPCOMM, "Extended absolute rate: " + danaRPump.extendedBolusAbsoluteRate) - } - - override fun getFriendlyName(): String { - return "REVIEW__INITIAL_SCREEN_INFORMATION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt deleted file mode 100644 index 9b0c7ef4c6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Alarm.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Alarm @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__ALARM" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt deleted file mode 100644 index a8010b2127..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_All_History.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_All_History( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__ALL_HISTORY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt deleted file mode 100644 index 0ac22574d5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Basal.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Basal @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BASAL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt deleted file mode 100644 index 6ebbeaed53..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Blood_Glucose.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Blood_Glucose @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BLOOD_GLUCOSE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt deleted file mode 100644 index 47996fc8c6..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Bolus.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Bolus @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__BOLUS" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt deleted file mode 100644 index 1084434962..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Carbohydrate.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Carbohydrate @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__CARBOHYDRATE" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt deleted file mode 100644 index 93e974728d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Daily.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Daily @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__DAILY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt deleted file mode 100644 index 0306e6f129..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Prime.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Prime @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__PRIME" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt deleted file mode 100644 index 672c5e2cc4..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Refill.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Refill @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__REFILL" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt deleted file mode 100644 index 9868cd10a4..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Suspend.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Suspend @JvmOverloads constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__SUSPEND" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt deleted file mode 100644 index b185748495..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_Temporary.kt +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.bus.RxBusWrapper - -class DanaRS_Packet_History_Temporary( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY - aapsLogger.debug(LTag.PUMPCOMM, "New message") - } - - override fun getFriendlyName(): String { - return "REVIEW__TEMPORARY" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.kt deleted file mode 100644 index 2b18603d11..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Get_Pump_Time.kt +++ /dev/null @@ -1,52 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_Option_Get_Pump_Time( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__GET_PUMP_TIME - aapsLogger.debug(LTag.PUMPCOMM, "Requesting pump time") - } - - override fun handleMessage(data: ByteArray) { - var dataIndex = DATA_START - var dataSize = 1 - val year = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val month = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val day = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val hour = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val min = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - dataIndex += dataSize - dataSize = 1 - val sec = byteArrayToInt(getBytes(data, dataIndex, dataSize)) - val time = Date(100 + year, month - 1, day, hour, min, sec) - danaRPump.pumpTime = time.time - failed = year == month && month == day && day == hour && hour == min && min == sec && sec == 1 - aapsLogger.debug(LTag.PUMPCOMM, "Pump time " + DateUtil.dateAndTimeString(time)) - } - - override fun handleMessageNotReceived() { - danaRPump.pumpTime = 0 - } - - override fun getFriendlyName(): String { - return "OPTION__GET_PUMP_TIME" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.kt deleted file mode 100644 index ec1a44c789..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_Pump_Time.kt +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.utils.DateUtil -import java.util.* - -class DanaRS_Packet_Option_Set_Pump_Time( - private val aapsLogger: AAPSLogger, - private var time: Long = 0 -) : DanaRS_Packet() { - - var error = 0 - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME - aapsLogger.debug(LTag.PUMPCOMM, "Setting pump time " + DateUtil.dateAndTimeString(time)) - } - - override fun getRequestParams(): ByteArray { - val date = Date(time) - val request = ByteArray(6) - request[0] = (date.year - 100 and 0xff).toByte() - request[1] = (date.month + 1 and 0xff).toByte() - request[2] = (date.date and 0xff).toByte() - request[3] = (date.hours and 0xff).toByte() - request[4] = (date.minutes and 0xff).toByte() - request[5] = (date.seconds and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - val result = intFromBuff(data, 0, 1) - if (result == 0) { - aapsLogger.debug(LTag.PUMPCOMM, "Result OK") - failed = false - } else { - aapsLogger.error("Result Error: $result") - failed = true - } - } - - override fun getFriendlyName(): String { - return "OPTION__SET_PUMP_TIME" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt deleted file mode 100644 index 2ca965fc60..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Option_Set_User_Option.kt +++ /dev/null @@ -1,60 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.comm - -import com.cozmo.danar.util.BleCommandUtil -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump - -class DanaRS_Packet_Option_Set_User_Option( - private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump -) : DanaRS_Packet() { - - - init { - opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_USER_OPTION - aapsLogger.debug(LTag.PUMPCOMM, "Setting user settings") - } - - override fun getRequestParams(): ByteArray { - aapsLogger.debug(LTag.PUMPCOMM, - "UserOptions:" + (System.currentTimeMillis() - danaRPump.lastConnection) / 1000 + " s ago" - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nbuttonScroll:" + danaRPump.buttonScrollOnOff - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nlcdOnTimeSec:" + danaRPump.lcdOnTimeSec - + "\nbacklight:" + danaRPump.backlightOnTimeSec - + "\ndanaRPumpUnits:" + danaRPump.units - + "\nlowReservoir:" + danaRPump.lowReservoirRate) - val request = ByteArray(13) - request[0] = (danaRPump.timeDisplayType and 0xff).toByte() - request[1] = (danaRPump.buttonScrollOnOff and 0xff).toByte() - request[2] = (danaRPump.beepAndAlarm and 0xff).toByte() - request[3] = (danaRPump.lcdOnTimeSec and 0xff).toByte() - request[4] = (danaRPump.backlightOnTimeSec and 0xff).toByte() - request[5] = (danaRPump.selectedLanguage and 0xff).toByte() - request[6] = (danaRPump.units and 0xff).toByte() - request[7] = (danaRPump.shutdownHour and 0xff).toByte() - request[8] = (danaRPump.lowReservoirRate and 0xff).toByte() - request[9] = (danaRPump.cannulaVolume and 0xff).toByte() - request[10] = (danaRPump.cannulaVolume ushr 8 and 0xff).toByte() - request[11] = (danaRPump.refillAmount and 0xff).toByte() - request[12] = (danaRPump.refillAmount ushr 8 and 0xff).toByte() - return request - } - - override fun handleMessage(data: ByteArray) { - val result = intFromBuff(data, 0, 1) - if (result == 0) { - aapsLogger.debug(LTag.PUMPCOMM, "Result OK") - failed = false - } else { - aapsLogger.error("Result Error: $result") - failed = true - } - } - - override fun getFriendlyName(): String { - return "OPTION__SET_USER_OPTION" - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java deleted file mode 100644 index 35097dcef5..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/BLEComm.java +++ /dev/null @@ -1,682 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.services; - -import android.bluetooth.BluetoothAdapter; -import android.bluetooth.BluetoothDevice; -import android.bluetooth.BluetoothGatt; -import android.bluetooth.BluetoothGattCallback; -import android.bluetooth.BluetoothGattCharacteristic; -import android.bluetooth.BluetoothGattService; -import android.bluetooth.BluetoothManager; -import android.bluetooth.BluetoothProfile; -import android.content.Context; -import android.content.Intent; -import android.os.SystemClock; - -import com.cozmo.danar.util.BleCommandUtil; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.concurrent.ScheduledFuture; - -import info.nightscout.androidaps.MainApp; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.events.EventPumpStatusChanged; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; -import info.nightscout.androidaps.plugins.bus.RxBus; -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.Notification; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; -import info.nightscout.androidaps.plugins.pump.danaRS.activities.PairingHelperActivity; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; -import info.nightscout.androidaps.plugins.pump.danaRS.events.EventDanaRSPairingSuccess; -import info.nightscout.androidaps.utils.SP; - -/** - * Created by mike on 23.09.2017. - */ - -public class BLEComm { - private Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPBTCOMM); - - private final long WRITE_DELAY_MILLIS = 50; - - private String UART_READ_UUID = "0000fff1-0000-1000-8000-00805f9b34fb"; - private String UART_WRITE_UUID = "0000fff2-0000-1000-8000-00805f9b34fb"; - - private final byte PACKET_START_BYTE = (byte) 0xA5; - private final byte PACKET_END_BYTE = (byte) 0x5A; - private Context context; - private DanaRPump danaRPump; - private DanaRSMessageHashTable danaRSMessageHashTable; - - public BLEComm(Context context, DanaRSMessageHashTable danaRSMessageHashTable, DanaRPump danaRPump) { - this.context = context; - this.danaRPump = danaRPump; - this.danaRSMessageHashTable = danaRSMessageHashTable; - initialize(); - } - - private ScheduledFuture scheduledDisconnection = null; - - private DanaRS_Packet processsedMessage = null; - private final ArrayList mSendQueue = new ArrayList<>(); - - private BluetoothManager mBluetoothManager = null; - private BluetoothAdapter mBluetoothAdapter = null; - private String mBluetoothDeviceName = null; - private BluetoothGatt mBluetoothGatt = null; - - protected boolean isConnected = false; - protected boolean isConnecting = false; - - private BluetoothGattCharacteristic UART_Read; - private BluetoothGattCharacteristic UART_Write; - - private boolean initialize() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Initializing BLEComm."); - - if (mBluetoothManager == null) { - mBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)); - if (mBluetoothManager == null) { - log.error("Unable to initialize BluetoothManager."); - return false; - } - } - - mBluetoothAdapter = mBluetoothManager.getAdapter(); - if (mBluetoothAdapter == null) { - log.error("Unable to obtain a BluetoothAdapter."); - return false; - } - - return true; - } - - public boolean isConnected() { - return isConnected; - } - - public boolean isConnecting() { - return isConnecting; - } - - public boolean connect(String from, String address, Object confirmConnect) { - BluetoothManager tBluetoothManager = ((BluetoothManager) MainApp.instance().getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)); - if (tBluetoothManager == null) { - return false; - } - - BluetoothAdapter tBluetoothAdapter = tBluetoothManager.getAdapter(); - if (tBluetoothAdapter == null) { - return false; - } - - if (mBluetoothAdapter == null) { - if (!initialize()) { - return false; - } - } - - if (address == null) { - log.error("unspecified address."); - return false; - } - - isConnecting = true; - - BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); - if (device == null) { - log.error("Device not found. Unable to connect from: " + from); - return false; - } - - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Trying to create a new connection from: " + from); - mBluetoothDeviceName = device.getName(); - mBluetoothGatt = device.connectGatt(context, false, mGattCallback); - setCharacteristicNotification(getUARTReadBTGattChar(), true); - return true; - } - - public void stopConnecting() { - isConnecting = false; - } - - public synchronized void disconnect(String from) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("disconnect from: " + from); - - // cancel previous scheduled disconnection to prevent closing upcomming connection - if (scheduledDisconnection != null) - scheduledDisconnection.cancel(false); - scheduledDisconnection = null; - - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("disconnect not possible: (mBluetoothAdapter == null) " + (mBluetoothAdapter == null)); - log.error("disconnect not possible: (mBluetoothGatt == null) " + (mBluetoothGatt == null)); - return; - } - setCharacteristicNotification(getUARTReadBTGattChar(), false); - mBluetoothGatt.disconnect(); - isConnected = false; - SystemClock.sleep(2000); - } - - public synchronized void close() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("BluetoothAdapter close"); - if (mBluetoothGatt == null) { - return; - } - - mBluetoothGatt.close(); - mBluetoothGatt = null; - } - - - private String getConnectDeviceName() { - return mBluetoothDeviceName; - } - - private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { - public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { - onConnectionStateChangeSynchronized(gatt, status, newState); // call it synchronized - } - - public void onServicesDiscovered(BluetoothGatt gatt, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onServicesDiscovered"); - if (status == BluetoothGatt.GATT_SUCCESS) { - findCharacteristic(); - } - SendPumpCheck(); - // 1st message sent to pump after connect - } - - public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicRead" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - addToReadBuffer(characteristic.getValue()); - readDataParsing(); - } - - public void onCharacteristicChanged(BluetoothGatt gatt, final BluetoothGattCharacteristic characteristic) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicChanged" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - addToReadBuffer(characteristic.getValue()); - new Thread(() -> readDataParsing()).start(); - } - - public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); - new Thread(() -> { - synchronized (mSendQueue) { - // after message sent, check if there is the rest of the message waiting and send it - if (mSendQueue.size() > 0) { - byte[] bytes = mSendQueue.get(0); - mSendQueue.remove(0); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - } - }).start(); - } - }; - - private synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("setCharacteristicNotification"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - mBluetoothGatt.setCharacteristicNotification(characteristic, enabled); - } - - public synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("readCharacteristic"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - mBluetoothGatt.readCharacteristic(characteristic); - } - - private synchronized void writeCharacteristic_NO_RESPONSE(final BluetoothGattCharacteristic characteristic, final byte[] data) { - new Thread(() -> { - SystemClock.sleep(WRITE_DELAY_MILLIS); - - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return; - } - - characteristic.setValue(data); - characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data)); - mBluetoothGatt.writeCharacteristic(characteristic); - }).start(); - } - - private BluetoothGattCharacteristic getUARTReadBTGattChar() { - if (UART_Read == null) { - UART_Read = new BluetoothGattCharacteristic(UUID.fromString(UART_READ_UUID), BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY, 0); - } - return UART_Read; - } - - private BluetoothGattCharacteristic getUARTWriteBTGattChar() { - if (UART_Write == null) { - UART_Write = new BluetoothGattCharacteristic(UUID.fromString(UART_WRITE_UUID), BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, 0); - } - return UART_Write; - } - - private List getSupportedGattServices() { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("getSupportedGattServices"); - if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { - log.error("BluetoothAdapter not initialized_ERROR"); - isConnecting = false; - isConnected = false; - return null; - } - - return mBluetoothGatt.getServices(); - } - - private void findCharacteristic() { - List gattServices = getSupportedGattServices(); - - if (gattServices == null) { - return; - } - String uuid; - - for (BluetoothGattService gattService : gattServices) { - List gattCharacteristics = gattService.getCharacteristics(); - for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) { - uuid = gattCharacteristic.getUuid().toString(); - if (UART_READ_UUID.equals(uuid)) { - UART_Read = gattCharacteristic; - setCharacteristicNotification(UART_Read, true); - } - if (UART_WRITE_UUID.equals(uuid)) { - UART_Write = gattCharacteristic; - } - } - } - } - - private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("onConnectionStateChange"); - - if (newState == BluetoothProfile.STATE_CONNECTED) { - mBluetoothGatt.discoverServices(); - } else if (newState == BluetoothProfile.STATE_DISCONNECTED) { - close(); - isConnected = false; - isConnecting = false; - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected - } - } - - private final byte[] readBuffer = new byte[1024]; - private int bufferLength = 0; - - private void addToReadBuffer(byte[] buffer) { - //log.debug("addToReadBuffer " + DanaRS_Packet.toHexString(buffer)); - if (buffer == null || buffer.length == 0) { - return; - } - synchronized (readBuffer) { - // Append incomming data to input buffer - System.arraycopy(buffer, 0, readBuffer, bufferLength, buffer.length); - bufferLength += buffer.length; - } - } - - private void readDataParsing() { - boolean startSignatureFound = false, packetIsValid = false; - boolean isProcessing; - - isProcessing = true; - - while (isProcessing) { - int length = 0; - byte[] inputBuffer = null; - synchronized (readBuffer) { - // Find packet start [A5 A5] - if (bufferLength >= 6) { - for (int idxStartByte = 0; idxStartByte < bufferLength - 2; idxStartByte++) { - if ((readBuffer[idxStartByte] == PACKET_START_BYTE) && (readBuffer[idxStartByte + 1] == PACKET_START_BYTE)) { - if (idxStartByte > 0) { - // if buffer doesn't start with signature remove the leading trash - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Shifting the input buffer by " + idxStartByte + " bytes"); - System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte); - bufferLength -= idxStartByte; - } - startSignatureFound = true; - break; - } - } - } - // A5 A5 LEN TYPE CODE PARAMS CHECKSUM1 CHECKSUM2 5A 5A - // ^---- LEN -----^ - // total packet length 2 + 1 + readBuffer[2] + 2 + 2 - if (startSignatureFound) { - length = readBuffer[2]; - // test if there is enough data loaded - if (length + 7 > bufferLength) - return; - // Verify packed end [5A 5A] - if ((readBuffer[length + 5] == PACKET_END_BYTE) && (readBuffer[length + 6] == PACKET_END_BYTE)) { - packetIsValid = true; - } - } - if (packetIsValid) { - inputBuffer = new byte[length + 7]; - // copy packet to input buffer - System.arraycopy(readBuffer, 0, inputBuffer, 0, length + 7); - // Cut off the message from readBuffer - try { - System.arraycopy(readBuffer, length + 7, readBuffer, 0, bufferLength - (length + 7)); - } catch (Exception e) { - log.error("length: " + length + "bufferLength: " + bufferLength); - throw e; - } - bufferLength -= (length + 7); - // now we have encrypted packet in inputBuffer - } - } - if (packetIsValid) { - try { - // decrypt the packet - inputBuffer = BleCommandUtil.getInstance().getDecryptedPacket(inputBuffer); - - if (inputBuffer == null) { - log.error("Null decryptedInputBuffer"); - return; - } - - switch (inputBuffer[0]) { - // initial handshake packet - case (byte) BleCommandUtil.DANAR_PACKET__TYPE_ENCRYPTION_RESPONSE: - switch (inputBuffer[1]) { - // 1st packet - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK: - if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (OK)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - // Grab pairing key from preferences if exists - String pairingKey = SP.getString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Using stored pairing key: " + pairingKey); - if (pairingKey != null) { - byte[] encodedPairingKey = DanaRS_Packet.hexToBytes(pairingKey); - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY, encodedPairingKey, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } else { - // Stored pairing key does not exists, request pairing - SendPairingRequest(); - } - - } else if (inputBuffer.length == 6 && inputBuffer[2] == 'P' && inputBuffer[3] == 'U' && inputBuffer[4] == 'M' && inputBuffer[5] == 'P') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (PUMP)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumperror))); - NSUpload.uploadError(MainApp.gs(R.string.pumperror)); - Notification n = new Notification(Notification.PUMPERROR, MainApp.gs(R.string.pumperror), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - } else if (inputBuffer.length == 6 && inputBuffer[2] == 'B' && inputBuffer[3] == 'U' && inputBuffer[4] == 'S' && inputBuffer[5] == 'Y') { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (BUSY)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.pumpbusy))); - } else { - // ERROR in response, wrong serial number - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PUMP_CHECK (ERROR)" + " " + DanaRS_Packet.toHexString(inputBuffer)); - mSendQueue.clear(); - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED, MainApp.gs(R.string.connectionerror))); - SP.remove(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName); - Notification n = new Notification(Notification.WRONGSERIALNUMBER, MainApp.gs(R.string.wrongpassword), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - } - break; - // 2nd packet, pairing key - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(inputBuffer)); - if (inputBuffer[2] == (byte) 0x00) { - // Paring is not requested, sending time info - SendTimeInfo(); - } else { - // Pairing on pump is requested - SendPairingRequest(); - } - break; - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer)); - if (inputBuffer[2] != (byte) 0x00) { - disconnect("passkey request failed"); - } - break; - // Paring response, OK button on pump pressed - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__PASSKEY_RETURN " + DanaRS_Packet.toHexString(inputBuffer)); - // Paring is successfull, sending time info - RxBus.Companion.getINSTANCE().send(new EventDanaRSPairingSuccess()); - SendTimeInfo(); - byte[] pairingKey = {inputBuffer[2], inputBuffer[3]}; - // store pairing key to preferences - SP.putString(MainApp.gs(R.string.key_danars_pairingkey) + DanaRSPlugin.mDeviceName, DanaRS_Packet.bytesToHex(pairingKey)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Got pairing key: " + DanaRS_Packet.bytesToHex(pairingKey)); - break; - // time and user password information. last packet in handshake - case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION: - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + "ENCRYPTION__TIME_INFORMATION " + /*message.getMessageName() + " " + */ DanaRS_Packet.toHexString(inputBuffer)); - int size = inputBuffer.length; - int pass = ((inputBuffer[size - 1] & 0x000000FF) << 8) + ((inputBuffer[size - 2] & 0x000000FF)); - pass = pass ^ 3463; - danaRPump.setRsPassword(Integer.toHexString(pass)); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("Pump user password: " + Integer.toHexString(pass)); - - RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.CONNECTED)); - isConnected = true; - isConnecting = false; - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("RS connected and status read"); - break; - } - break; - // common data packet - default: - DanaRS_Packet message; - // Retrieve message code from received buffer and last message sent - int originalCommand = processsedMessage != null ? processsedMessage.getCommand() : 0xFFFF; - int receivedCommand = DanaRS_Packet.getCommand(inputBuffer); - if (originalCommand == receivedCommand) { - // it's response to last message - message = processsedMessage; - } else { - // it's not response to last message, create new instance - message = danaRSMessageHashTable.findMessage(receivedCommand); - } - if (message != null) { - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer)); - // process received data - message.handleMessage(inputBuffer); - message.setReceived(); - synchronized (message) { - // notify to sendMessage - message.notify(); - } - } else { - log.error("Unknown message received " + DanaRS_Packet.toHexString(inputBuffer)); - } - break; - } - } catch (Exception e) { - log.error("Unhandled exception", e); - } - startSignatureFound = false; - packetIsValid = false; - if (bufferLength < 6) { - // stop the loop - isProcessing = false; - } - } else { - // stop the loop - isProcessing = false; - } - } - } - - public void sendMessage(DanaRS_Packet message) { - processsedMessage = message; - if (message == null) - return; - - byte[] command = {(byte) message.getType(), (byte) message.getOpCode()}; - byte[] params = message.getRequestParams(); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(command) + " " + DanaRS_Packet.toHexString(params)); - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(message.getOpCode(), params, null); - // If there is another message not completely sent, add to queue only - if (mSendQueue.size() > 0) { - // Split to parts per 20 bytes max - for (; ; ) { - if (bytes.length > 20) { - byte[] addBytes = new byte[20]; - System.arraycopy(bytes, 0, addBytes, 0, addBytes.length); - byte[] reBytes = new byte[bytes.length - addBytes.length]; - System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - synchronized (mSendQueue) { - mSendQueue.add(addBytes); - } - } else { - synchronized (mSendQueue) { - mSendQueue.add(bytes); - } - break; - } - } - - } else { - if (bytes.length > 20) { - // Cut first 20 bytes - byte[] sendBytes = new byte[20]; - System.arraycopy(bytes, 0, sendBytes, 0, sendBytes.length); - byte[] reBytes = new byte[bytes.length - sendBytes.length]; - System.arraycopy(bytes, sendBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - // and send - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), sendBytes); - // The rest split to parts per 20 bytes max - for (; ; ) { - if (bytes.length > 20) { - byte[] addBytes = new byte[20]; - System.arraycopy(bytes, 0, addBytes, 0, addBytes.length); - reBytes = new byte[bytes.length - addBytes.length]; - System.arraycopy(bytes, addBytes.length, reBytes, 0, reBytes.length); - bytes = reBytes; - synchronized (mSendQueue) { - mSendQueue.add(addBytes); - } - } else { - synchronized (mSendQueue) { - mSendQueue.add(bytes); - } - break; - } - } - } else { - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - } - // The rest from queue is send from onCharasteristicWrite (after sending 1st part) - synchronized (message) { - try { - message.wait(5000); - } catch (InterruptedException e) { - log.error("sendMessage InterruptedException", e); - log.error("Unhandled exception", e); - } - } - - //SystemClock.sleep(200); - if (!message.isReceived()) { - log.warn("Reply not received " + message.getFriendlyName()); - message.handleMessageNotReceived(); - } - } - - private void SendPairingRequest() { - // Start activity which is waiting 20sec - // On pump pairing request is displayed and is waiting for conformation - Intent i = new Intent(); - i.setClass(MainApp.instance(), PairingHelperActivity.class); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); - - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - - private void SendPumpCheck() { - // 1st message sent to pump after connect - String devicename = getConnectDeviceName(); - if (devicename == null || devicename.equals("")) { - Notification n = new Notification(Notification.DEVICENOTPAIRED, MainApp.gs(R.string.pairfirst), Notification.URGENT); - RxBus.Companion.getINSTANCE().send(new EventNewNotification(n)); - return; - } - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, devicename); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__PUMP_CHECK (0x00)" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - - private void SendTimeInfo() { - byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__TIME_INFORMATION, null, null); - if (L.isEnabled(LTag.PUMPBTCOMM)) - log.debug(">>>>> " + "ENCRYPTION__TIME_INFORMATION" + " " + DanaRS_Packet.toHexString(bytes)); - writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); - } - -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java deleted file mode 100644 index 3d7eb03e0a..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ /dev/null @@ -1,565 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRS.services; - -import android.content.Context; -import android.content.Intent; -import android.os.Binder; -import android.os.IBinder; -import android.os.SystemClock; - -import javax.inject.Inject; - -import dagger.android.DaggerService; -import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.activities.ErrorHelperActivity; -import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.events.EventAppExit; -import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventProfileNeedsUpdate; -import info.nightscout.androidaps.events.EventPumpStatusChanged; -import info.nightscout.androidaps.interfaces.ActivePluginProvider; -import info.nightscout.androidaps.interfaces.CommandQueueProvider; -import info.nightscout.androidaps.interfaces.PumpInterface; -import info.nightscout.androidaps.logging.AAPSLogger; -import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; -import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; -import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; -import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage; -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; -import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRNewStatus; -import info.nightscout.androidaps.plugins.pump.danaRS.DanaRSPlugin; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRSMessageHashTable; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Basal_Set_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_History_Events; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_APS_Set_Event_History; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Basal_Rate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Profile_Number; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Get_Temporary_Basal_State; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Basal_Rate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Profile_Number; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Basal_Set_Temporary_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Bolus_Option; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_CIR_CF_Array; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Calculation_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Extended_Bolus_State; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Get_Step_Bolus_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Start; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Bolus_Set_Step_Bolus_Stop; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Pump_Check; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Get_Shipping_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Initial_Screen_Information; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_General_Set_History_Upload_Mode; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Alarm; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Basal; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Blood_Glucose; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Bolus; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Carbohydrate; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Daily; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Prime; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Refill; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History_Suspend; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_Pump_Time; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Get_User_Option; -import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_Option_Set_Pump_Time; -import info.nightscout.androidaps.plugins.treatments.Treatment; -import info.nightscout.androidaps.queue.Callback; -import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.androidaps.utils.DateUtil; -import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; - -public class DanaRSService extends DaggerService { - @Inject HasAndroidInjector injector; - @Inject AAPSLogger aapsLogger; - @Inject RxBusWrapper rxBus; - @Inject SP sp; - @Inject ResourceHelper resourceHelper; - @Inject ProfileFunction profileFunction; - @Inject CommandQueueProvider commandQueue; - @Inject Context context; - @Inject DanaRSPlugin danaRSPlugin; - @Inject DanaRPump danaRPump; - @Inject DanaRSMessageHashTable danaRSMessageHashTable; - @Inject ActivePluginProvider activePlugin; - @Inject ConstraintChecker constraintChecker; - @Inject DetailedBolusInfoStorage detailedBolusInfoStorage; - - private CompositeDisposable disposable = new CompositeDisposable(); - - private BLEComm bleComm; - - private IBinder mBinder = new LocalBinder(); - - private Treatment bolusingTreatment = null; - - private long lastHistoryFetched = 0; - private long lastApproachingDailyLimit = 0; - - @Override - public void onCreate() { - super.onCreate(); - bleComm = new BLEComm(this, danaRSMessageHashTable, danaRPump); - disposable.add(rxBus - .toObservable(EventAppExit.class) - .observeOn(Schedulers.io()) - .subscribe(event -> { - aapsLogger.debug(LTag.PUMPCOMM, "EventAppExit received"); - stopSelf(); - }, exception -> FabricPrivacy.getInstance().logException(exception)) - ); - } - - @Override - public void onDestroy() { - disposable.clear(); - super.onDestroy(); - } - - public boolean isConnected() { - return bleComm.isConnected; - } - - public boolean isConnecting() { - return bleComm.isConnecting; - } - - public boolean connect(String from, String address, Object confirmConnect) { - return bleComm.connect(from, address, confirmConnect); - } - - public void stopConnecting() { - bleComm.stopConnecting(); - } - - public void disconnect(String from) { - bleComm.disconnect(from); - } - - @SuppressWarnings("unused") - public void sendMessage(DanaRS_Packet message) { - bleComm.sendMessage(message); - } - - public void getPumpStatus() { - try { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); - - bleComm.sendMessage(new DanaRS_Packet_General_Initial_Screen_Information(aapsLogger, danaRPump)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump)); // last bolus, bolusStep, maxBolus - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)); - - danaRPump.setLastConnection(System.currentTimeMillis()); - - Profile profile = profileFunction.getProfile(); - PumpInterface pump = activePlugin.getActivePump(); - if (profile != null && Math.abs(danaRPump.getCurrentBasal() - profile.getBasal()) >= pump.getPumpDescription().basalStep) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal - if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { - rxBus.send(new EventProfileNeedsUpdate()); - } - } - - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump)); - - long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - if (danaRPump.getPumpTime() == 0) { - // initial handshake was not successfull - // deinitialize pump - danaRPump.setLastConnection(0); - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - return; - } - long now = System.currentTimeMillis(); - if (danaRPump.getLastSettingsRead() + 60 * 60 * 1000L < now || !pump.isInitialized()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))); - bleComm.sendMessage(new DanaRS_Packet_General_Get_Shipping_Information(aapsLogger, danaRPump)); // serial no - bleComm.sendMessage(new DanaRS_Packet_General_Get_Pump_Check(aapsLogger, danaRPump, rxBus, resourceHelper)); // firmware - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Profile_Number(aapsLogger, danaRPump)); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Bolus_Option(aapsLogger, rxBus, resourceHelper, danaRPump)); // isExtendedEnabled - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Basal_Rate(aapsLogger, rxBus, resourceHelper, danaRPump)); // basal profile, basalStep, maxBasal - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Calculation_Information(aapsLogger, danaRPump)); // target - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_CIR_CF_Array(aapsLogger, danaRPump)); - bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); // Getting user options - danaRPump.setLastSettingsRead(now); - } - - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds"); - if (Math.abs(timeDiff) > 3) { - if (Math.abs(timeDiff) > 60 * 60 * 1.5) { - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds - large difference"); - //If time-diff is very large, warn user until we can synchronize history readings properly - Intent i = new Intent(context, ErrorHelperActivity.class); - i.putExtra("soundid", R.raw.error); - i.putExtra("status", resourceHelper.gs(R.string.largetimediff)); - i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle)); - i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(i); - - //deinitialize pump - danaRPump.setLastConnection(0); - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - return; - } else { - if (danaRPump.getProtocol() >= 6) { - bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, DateUtil.now())); - } else { - waitForWholeMinute(); // Dana can set only whole minute - // add 10sec to be sure we are over minute (will be cutted off anyway) - bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, DateUtil.now() + T.secs(10).msecs())); - } - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump)); - timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; - aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds"); - } - } - - loadEvents(); - - rxBus.send(new EventDanaRNewStatus()); - rxBus.send(new EventInitializationChanged()); - //NSUpload.uploadDeviceStatus(); - if (danaRPump.getDailyTotalUnits() > danaRPump.getMaxDailyTotalUnits() * Constants.dailyLimitWarning) { - aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits()); - if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { - Notification reportFail = new Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT); - rxBus.send(new EventNewNotification(reportFail)); - NSUpload.uploadError(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaRPump.getDailyTotalUnits() + "/" + danaRPump.getMaxDailyTotalUnits() + "U"); - lastApproachingDailyLimit = System.currentTimeMillis(); - } - } - } catch (Exception e) { - aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e); - } - aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded"); - } - - public PumpEnactResult loadEvents() { - - if (!danaRSPlugin.isInitialized()) { - PumpEnactResult result = new PumpEnactResult(injector).success(false); - result.comment = "pump not initialized"; - return result; - } - - SystemClock.sleep(1000); - - DanaRS_Packet_APS_History_Events msg; - if (lastHistoryFetched == 0) { - msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, 0); - aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history"); - } else { - msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, lastHistoryFetched); - aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched)); - } - bleComm.sendMessage(msg); - while (!danaRSPlugin.apsHistoryDone && bleComm.isConnected()) { - SystemClock.sleep(100); - } - if (danaRSPlugin.lastEventTimeLoaded != 0) - lastHistoryFetched = danaRSPlugin.lastEventTimeLoaded - T.mins(1).msecs(); - else - lastHistoryFetched = 0; - aapsLogger.debug(LTag.PUMPCOMM, "Events loaded"); - danaRPump.setLastConnection(System.currentTimeMillis()); - return new PumpEnactResult(injector).success(true); - } - - - public PumpEnactResult setUserSettings() { - bleComm.sendMessage(new DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)); - return new PumpEnactResult(injector).success(true); - } - - - public boolean bolus(final double insulin, int carbs, long carbtime, Treatment t) { - if (!isConnected()) return false; - if (BolusProgressDialog.stopPressed) return false; - - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))); - bolusingTreatment = t; - final int preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0); - danaRSPlugin.bolusingTreatment = t; - danaRSPlugin.bolusAmountToBeDelivered = insulin; - danaRSPlugin.bolusStopped = false; - danaRSPlugin.bolusStopForced = false; - danaRSPlugin.bolusProgressLastTimeStamp = DateUtil.now(); - - DanaRS_Packet_Bolus_Set_Step_Bolus_Start start = new DanaRS_Packet_Bolus_Set_Step_Bolus_Start(aapsLogger, danaRSPlugin, constraintChecker, insulin, preferencesSpeed); - if (carbs > 0) { -// MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbtime, carbs); #### -// bleComm.sendMessage(msg); - DanaRS_Packet_APS_Set_Event_History msgSetHistoryEntry_v2 = new DanaRS_Packet_APS_Set_Event_History(aapsLogger, DanaRPump.CARBS, carbtime, carbs, 0); - bleComm.sendMessage(msgSetHistoryEntry_v2); - lastHistoryFetched = Math.min(lastHistoryFetched, carbtime - T.mins(1).msecs()); - } - - final long bolusStart = System.currentTimeMillis(); - if (insulin > 0) { - if (!danaRSPlugin.bolusStopped) { - bleComm.sendMessage(start); - } else { - t.insulin = 0d; - return false; - } - - while (!danaRSPlugin.bolusStopped && !start.failed && !danaRSPlugin.bolusDone) { - SystemClock.sleep(100); - if ((System.currentTimeMillis() - danaRSPlugin.bolusProgressLastTimeStamp) > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm - danaRSPlugin.bolusStopped = true; - danaRSPlugin.bolusStopForced = true; - aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped"); - } - } - } - - final EventOverviewBolusProgress bolusingEvent = EventOverviewBolusProgress.INSTANCE; - bolusingEvent.setT(t); - bolusingEvent.setPercent(99); - - bolusingTreatment = null; - int speed = 12; - switch (preferencesSpeed) { - case 0: - speed = 12; - break; - case 1: - speed = 30; - break; - case 2: - speed = 60; - break; - } - long bolusDurationInMSec = (long) (insulin * speed * 1000); - long expectedEnd = bolusStart + bolusDurationInMSec + 2000; - while (System.currentTimeMillis() < expectedEnd) { - long waitTime = expectedEnd - System.currentTimeMillis(); - bolusingEvent.setStatus(String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000)); - rxBus.send(bolusingEvent); - SystemClock.sleep(1000); - } - // do not call loadEvents() directly, reconnection may be needed - commandQueue.loadEvents(new Callback() { - @Override - public void run() { - // reread bolus status - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump)); // last bolus - bolusingEvent.setPercent(100); - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))); - } - }); - return !start.failed; - } - - public void bolusStop() { - aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + (bolusingTreatment == null ? "" : bolusingTreatment.insulin)); - DanaRS_Packet_Bolus_Set_Step_Bolus_Stop stop = new DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(aapsLogger, rxBus, resourceHelper, danaRSPlugin); - danaRSPlugin.bolusStopForced = true; - if (isConnected()) { - bleComm.sendMessage(stop); - while (!danaRSPlugin.bolusStopped) { - bleComm.sendMessage(stop); - SystemClock.sleep(200); - } - } else { - danaRSPlugin.bolusStopped = true; - } - } - - public boolean tempBasal(Integer percent, int durationInHours) { - if (!isConnected()) return false; - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Temporary_Basal(aapsLogger, percent, durationInHours)); - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean highTempBasal(Integer percent) { - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean tempBasalShortDuration(Integer percent, int durationInMinutes) { - if (durationInMinutes != 15 && durationInMinutes != 30) { - aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param"); - return false; - } - - if (danaRPump.isTempBasalInProgress()) { - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - SystemClock.sleep(500); - } - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_APS_Basal_Set_Temporary_Basal(aapsLogger, percent)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean tempBasalStop() { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); - bleComm.sendMessage(new DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(aapsLogger)); - bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean extendedBolus(Double insulin, int durationInHalfHours) { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus(aapsLogger, insulin, durationInHalfHours)); - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean extendedBolusStop() { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(aapsLogger)); - bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Extended_Bolus_State(aapsLogger, danaRPump)); - loadEvents(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public boolean updateBasalsInPump(Profile profile) { - if (!isConnected()) return false; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))); - Double[] basal = danaRPump.buildDanaRProfileRecord(profile); - DanaRS_Packet_Basal_Set_Profile_Basal_Rate msgSet = new DanaRS_Packet_Basal_Set_Profile_Basal_Rate(aapsLogger, 0, basal); - bleComm.sendMessage(msgSet); - DanaRS_Packet_Basal_Set_Profile_Number msgActivate = new DanaRS_Packet_Basal_Set_Profile_Number(aapsLogger, 0); - bleComm.sendMessage(msgActivate); - danaRPump.setLastSettingsRead(0); // force read full settings - getPumpStatus(); - rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); - return true; - } - - public PumpEnactResult loadHistory(byte type) { - PumpEnactResult result = new PumpEnactResult(injector); - if (!isConnected()) return result; - DanaRS_Packet_History_ msg = null; - switch (type) { - case RecordTypes.RECORD_TYPE_ALARM: - msg = new DanaRS_Packet_History_Alarm(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_PRIME: - msg = new DanaRS_Packet_History_Prime(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_BASALHOUR: - msg = new DanaRS_Packet_History_Basal(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_BOLUS: - msg = new DanaRS_Packet_History_Bolus(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_CARBO: - msg = new DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_DAILY: - msg = new DanaRS_Packet_History_Daily(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_GLUCOSE: - msg = new DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_REFILL: - msg = new DanaRS_Packet_History_Refill(aapsLogger, rxBus); - break; - case RecordTypes.RECORD_TYPE_SUSPEND: - msg = new DanaRS_Packet_History_Suspend(aapsLogger, rxBus); - break; - } - if (msg != null) { - bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 1)); - SystemClock.sleep(200); - bleComm.sendMessage(msg); - while (!msg.getDone() && isConnected()) { - SystemClock.sleep(100); - } - SystemClock.sleep(200); - bleComm.sendMessage(new DanaRS_Packet_General_Set_History_Upload_Mode(aapsLogger, 0)); - } - result.success = true; - result.comment = "OK"; - return result; - } - - - public class LocalBinder extends Binder { - public DanaRSService getServiceInstance() { - return DanaRSService.this; - } - - } - - @Override - public IBinder onBind(Intent intent) { - return mBinder; - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - return START_STICKY; - } - - void waitForWholeMinute() { - while (true) { - long time = DateUtil.now(); - long timeToWholeMinute = (60000 - time % 60000); - if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) - break; - rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (int) (timeToWholeMinute / 1000)))); - SystemClock.sleep(Math.min(timeToWholeMinute, 100)); - } - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt deleted file mode 100644 index 7fbb2f3258..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MessageHashTableRv2.kt +++ /dev/null @@ -1,107 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.danaRv2.comm - -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump -import info.nightscout.androidaps.plugins.pump.danaR.comm.* -import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.plugins.pump.danaRv2.DanaRv2Plugin -import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper -import java.util.* -import javax.inject.Inject -import javax.inject.Singleton - -@Singleton -class MessageHashTableRv2 @Inject constructor( - aapsLogger: AAPSLogger, - rxBus: RxBusWrapper, - resourceHelper: ResourceHelper, - constraintChecker: ConstraintChecker, - danaRPump: DanaRPump, - danaRPlugin: DanaRPlugin, - danaRKoreanPlugin: DanaRKoreanPlugin, - danaRv2Plugin: DanaRv2Plugin, - configBuilderPlugin: ConfigBuilderPlugin, - commandQueue: CommandQueueProvider, - activePlugin: ActivePluginProvider, - detailedBolusInfoStorage: DetailedBolusInfoStorage, - treatmentsPlugin: TreatmentsPlugin, - injector: HasAndroidInjector -) : MessageHashTableBase { - - var messages: HashMap = HashMap() - - init { - put(MsgBolusStop(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0101 CMD_MEALINS_STOP - put(MsgBolusStart(aapsLogger, constraintChecker, danaRPump, 0.0)) // 0x0102 CMD_MEALINS_START_DATA - put(MsgBolusStartWithSpeed(aapsLogger, constraintChecker, danaRPump, 0.0, 0)) // 0x0104 CMD_MEALINS_START_DATA_SPEED - put(MsgBolusProgress(aapsLogger, resourceHelper, rxBus, danaRPump)) // 0x0202 CMD_PUMP_THIS_REMAINDER_MEAL_INS - put(MsgStatusProfile(aapsLogger, danaRPump)) // 0x0204 CMD_PUMP_CALCULATION_SETTING - put(MsgStatusTempBasal_v2(aapsLogger, danaRPump)) // 0x0205 CMD_PUMP_EXERCISE_MODE - put(MsgStatusBolusExtended_v2(aapsLogger, danaRPump)) // 0x0207 CMD_PUMP_EXPANS_INS_I - put(MsgStatusBasic(aapsLogger, danaRPump)) // 0x020A CMD_PUMP_INITVIEW_I - put(MsgStatus(aapsLogger, danaRPump)) // 0x020B CMD_PUMP_STATUS - put(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue)) // 0x0301 CMD_PUMPINIT_TIME_INFO - put(MsgInitConnStatusBolus(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0302 CMD_PUMPINIT_BOLUS_INFO - put(MsgInitConnStatusBasic(aapsLogger, danaRPump)) // 0x0303 CMD_PUMPINIT_INIT_INFO - put(MsgInitConnStatusOption(aapsLogger, rxBus, resourceHelper, danaRPump, activePlugin)) // 0x0304 CMD_PUMPINIT_OPTION - put(MsgSetTempBasalStart(aapsLogger, 0, 0)) // 0x0401 CMD_PUMPSET_EXERCISE_S - put(MsgSetCarbsEntry(aapsLogger, 0, 0)) // 0x0402 CMD_PUMPSET_HIS_S - put(MsgSetTempBasalStop(aapsLogger)) // 0x0403 CMD_PUMPSET_EXERCISE_STOP - put(MsgSetExtendedBolusStop(aapsLogger)) // 0x0406 CMD_PUMPSET_EXPANS_INS_STOP - put(MsgSetExtendedBolusStart(aapsLogger, constraintChecker, 0.0, 0)) // 0x0407 CMD_PUMPSET_EXPANS_INS_S - put(MsgError(aapsLogger, rxBus, resourceHelper, danaRPump)) // 0x0601 CMD_PUMPOWAY_SYSTEM_STATUS - put(MsgPCCommStart(aapsLogger)) // 0x3001 CMD_CONNECT - put(MsgPCCommStop(aapsLogger)) // 0x3002 CMD_DISCONNECT - put(MsgHistoryBolus(aapsLogger, rxBus)) // 0x3101 CMD_HISTORY_MEAL_INS - put(MsgHistoryDailyInsulin(aapsLogger, rxBus)) // 0x3102 CMD_HISTORY_DAY_INS - put(MsgHistoryGlucose(aapsLogger, rxBus)) // 0x3104 CMD_HISTORY_GLUCOSE - put(MsgHistoryAlarm(aapsLogger, rxBus)) // 0x3105 CMD_HISTORY_ALARM - put(MsgHistoryError(aapsLogger, rxBus)) // 0x3106 CMD_HISTORY_ERROR - put(MsgHistoryCarbo(aapsLogger, rxBus)) // 0x3107 CMD_HISTORY_CARBOHY - put(MsgHistoryRefill(aapsLogger, rxBus)) // 0x3108 CMD_HISTORY_REFILL - put(MsgHistorySuspend(aapsLogger, rxBus)) // 0x3109 CMD_HISTORY_SUSPEND - put(MsgHistoryBasalHour(aapsLogger, rxBus)) // 0x310A CMD_HISTORY_BASAL_HOUR - put(MsgHistoryDone(aapsLogger, danaRPump)) // 0x31F1 CMD_HISTORY_DONT_USED - put(MsgSettingBasal(aapsLogger, danaRPump, danaRPlugin)) // 0x3202 CMD_SETTING_V_BASAL_INS_I - put(MsgSettingMeal(aapsLogger, rxBus, resourceHelper, danaRPump, danaRKoreanPlugin)) // 0x3203 CMD_SETTING_V_MEAL_SETTING_I - put(MsgSettingProfileRatios(aapsLogger, danaRPump)) // 0x3204 CMD_SETTING_V_CCC_I - put(MsgSettingMaxValues(aapsLogger, danaRPump)) // 0x3205 CMD_SETTING_V_MAX_VALUE_I - put(MsgSettingBasalProfileAll(aapsLogger, danaRPump)) // 0x3206 CMD_SETTING_V_BASAL_PROFILE_ALL - put(MsgSettingShippingInfo(aapsLogger, danaRPump)) // 0x3207 CMD_SETTING_V_SHIPPING_I - put(MsgSettingGlucose(aapsLogger, danaRPump)) // 0x3209 CMD_SETTING_V_GLUCOSEandEASY - put(MsgSettingPumpTime(aapsLogger, danaRPump)) // 0x320A CMD_SETTING_V_TIME_I - put(MsgSettingUserOptions(aapsLogger, danaRPump)) // 0x320B CMD_SETTING_V_USER_OPTIONS - put(MsgSettingActiveProfile(aapsLogger, danaRPump)) // 0x320C CMD_SETTING_V_PROFILE_NUMBER - put(MsgSettingProfileRatiosAll(aapsLogger, danaRPump)) // 0x320D CMD_SETTING_V_CIR_CF_VALUE - put(MsgSetSingleBasalProfile(aapsLogger, rxBus, resourceHelper, Array(24) { 0.0 })) // 0x3302 CMD_SETTING_BASAL_INS_S - put(MsgSetBasalProfile(aapsLogger, rxBus, resourceHelper, 0.toByte(), Array(24) { 0.0 })) // 0x3306 CMD_SETTING_BASAL_PROFILE_S - put(MsgSetUserOptions(aapsLogger, danaRPump)) // 0x330B CMD_SETTING_USER_OPTIONS_S - put(MsgSetActivateBasalProfile(aapsLogger, 0.toByte())) // 0x330C CMD_SETTING_PROFILE_NUMBER_S - put(MsgHistoryAllDone(aapsLogger, danaRPump)) // 0x41F1 CMD_HISTORY_ALL_DONE - put(MsgHistoryAll(aapsLogger, rxBus)) // 0x41F2 CMD_HISTORY_ALL - put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW - put(MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue)) // 0xF0F1 CMD_PUMP_CHECK_VALUE - put(MsgStatusAPS_v2(aapsLogger, danaRPump)) // 0xE001 CMD_PUMPSTATUS_APS - put(MsgSetAPSTempBasalStart_v2(aapsLogger, 0, false, false)) // 0xE002 CMD_PUMPSET_APSTEMP - put(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector)) // 0xE003 CMD_GET_HISTORY - put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY - } - - override fun put(message: MessageBase) { - messages[message.command] = message - } - - override fun findMessage(command: Int): MessageBase { - return messages[command] ?: MessageBase() - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java index 0812bb7614..50722c627c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java @@ -8,7 +8,6 @@ import android.content.ServiceConnection; import android.os.Binder; import android.os.IBinder; import android.os.Vibrator; -import android.text.Html; import androidx.annotation.Nullable; import androidx.core.app.NotificationCompat; @@ -34,6 +33,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.InsightExcepti import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.AppLayerErrorException; import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtils; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; +import info.nightscout.androidaps.utils.HtmlHelper; import info.nightscout.androidaps.utils.resources.ResourceHelper; public class InsightAlertService extends DaggerService implements InsightConnectionService.StateCallback { @@ -299,7 +299,7 @@ public class InsightAlertService extends DaggerService implements InsightConnect notificationBuilder.setContentTitle(alertUtils.getAlertCode(alert.getAlertType()) + " – " + alertUtils.getAlertTitle(alert.getAlertType())); String description = alertUtils.getAlertDescription(alert); if (description != null) - notificationBuilder.setContentText(Html.fromHtml(description).toString()); + notificationBuilder.setContentText(HtmlHelper.INSTANCE.fromHtml(description).toString()); Intent fullScreenIntent = new Intent(this, InsightAlertActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index 603e8aabb9..cc4cdd9516 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -44,6 +44,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick @Inject RxBusWrapper rxBus; @Inject ResourceHelper resourceHelper; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -237,7 +238,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick long lastConnection = localInsightPlugin.getConnectionService().getLastConnected(); if (lastConnection == 0) return; int min = (int) ((System.currentTimeMillis() - lastConnection) / 60000); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.last_connected), DateUtil.timeString(lastConnection))); + statusItems.add(getStatusItem(resourceHelper.gs(R.string.last_connected), dateUtil.timeString(lastConnection))); } } @@ -268,7 +269,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick private void getBatteryStatusItem(List statusItems) { if (localInsightPlugin.getBatteryStatus() == null) return; - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_battery_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.battery_label), localInsightPlugin.getBatteryStatus().getBatteryAmount() + "%")); } @@ -279,7 +280,7 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick if (cartridgeStatus.isInserted()) status = DecimalFormatter.to2Decimal(localInsightPlugin.getCartridgeStatus().getRemainingAmount()) + "U"; else status = resourceHelper.gs(R.string.not_inserted); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_reservoir_label), status)); + statusItems.add(getStatusItem(resourceHelper.gs(R.string.reservoir_label), status)); } private void getTDDItems(List statusItems) { @@ -293,14 +294,14 @@ public class LocalInsightFragment extends DaggerFragment implements View.OnClick private void getBaseBasalRateItem(List statusItems) { if (localInsightPlugin.getActiveBasalRate() == null) return; ActiveBasalRate activeBasalRate = localInsightPlugin.getActiveBasalRate(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_basebasalrate_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.basebasalrate_label), DecimalFormatter.to2Decimal(activeBasalRate.getActiveBasalRate()) + " U/h (" + activeBasalRate.getActiveBasalProfileName() + ")")); } private void getTBRItem(List statusItems) { if (localInsightPlugin.getActiveTBR() == null) return; ActiveTBR activeTBR = localInsightPlugin.getActiveTBR(); - statusItems.add(getStatusItem(resourceHelper.gs(R.string.pump_tempbasal_label), + statusItems.add(getStatusItem(resourceHelper.gs(R.string.tempbasal_label), resourceHelper.gs(R.string.tbr_formatter, activeTBR.getPercentage(), activeTBR.getInitialDuration() - activeTBR.getRemainingDuration(), activeTBR.getInitialDuration()))); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index b91823a24a..0da2b70209 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -27,7 +27,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.BuildConfig; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; @@ -39,6 +38,7 @@ import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TDD; import info.nightscout.androidaps.db.TemporaryBasal; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.EventInitializationChanged; import info.nightscout.androidaps.events.EventRefreshOverview; import info.nightscout.androidaps.interfaces.CommandQueueProvider; @@ -46,6 +46,7 @@ import info.nightscout.androidaps.interfaces.Constraint; import info.nightscout.androidaps.interfaces.ConstraintsInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.interfaces.PumpDescription; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.interfaces.PumpPluginBase; @@ -53,7 +54,6 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.common.ManufacturerType; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; @@ -132,7 +132,6 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_errors.NoActiveTBRToCanceLException; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; -import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.TimeChangeType; @@ -149,7 +148,10 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, private final SP sp; private final CommandQueueProvider commandQueue; private final ProfileFunction profileFunction; + private final NSUpload nsUpload; private final Context context; + private final UploadQueue uploadQueue; + private final DateUtil dateUtil; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -208,7 +210,11 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, SP sp, CommandQueueProvider commandQueue, ProfileFunction profileFunction, - Context context + NSUpload nsUpload, + Context context, + UploadQueue uploadQueue, + Config config, + DateUtil dateUtil ) { super(new PluginDescription() .pluginName(R.string.insight_local) @@ -216,7 +222,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, .mainType(PluginType.PUMP) .description(R.string.description_pump_insight_local) .fragmentClass(LocalInsightFragment.class.getName()) - .preferencesId(Config.APS ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), + .preferencesId(config.getAPS() ? R.xml.pref_insight_local_full : R.xml.pref_insight_local_pumpcontrol), injector, aapsLogger, resourceHelper, commandQueue ); @@ -227,7 +233,10 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, this.sp = sp; this.commandQueue = commandQueue; this.profileFunction = profileFunction; + this.nsUpload = nsUpload; this.context = context; + this.uploadQueue = uploadQueue; + this.dateUtil = dateUtil; pumpDescription = new PumpDescription(); pumpDescription.setPumpDescription(PumpType.AccuChekInsightBluetooth); @@ -588,6 +597,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, bolusMessage.setDuration(0); bolusMessage.setExtendedAmount(0); bolusMessage.setImmediateAmount(insulin); + bolusMessage.setVibration(sp.getBoolean(detailedBolusInfo.isSMB ? R.string.key_disable_vibration_auto : R.string.key_disable_vibration ,false)); bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); bolusCancelled = false; } @@ -711,7 +721,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, PumpEnactResult cancelTBRResult = cancelTempBasalOnly(); if (cancelTBRResult.success) { PumpEnactResult ebResult = setExtendedBolusOnly((absoluteRate - getBaseBasalRate()) / 60D - * ((double) durationInMinutes), durationInMinutes); + * ((double) durationInMinutes), durationInMinutes, + sp.getBoolean(R.string.key_disable_vibration_auto,false)); if (ebResult.success) { result.success = true; result.enacted = true; @@ -789,7 +800,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, @NonNull @Override public PumpEnactResult setExtendedBolus(Double insulin, Integer durationInMinutes) { PumpEnactResult result = cancelExtendedBolusOnly(); - if (result.success) result = setExtendedBolusOnly(insulin, durationInMinutes); + if (result.success) result = setExtendedBolusOnly(insulin, durationInMinutes, sp.getBoolean(R.string.key_disable_vibration,false)); try { fetchStatus(); readHistory(); @@ -803,7 +814,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, return result; } - public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes) { + public PumpEnactResult setExtendedBolusOnly(Double insulin, Integer durationInMinutes, boolean disableVibration) { PumpEnactResult result = new PumpEnactResult(getInjector()); try { DeliverBolusMessage bolusMessage = new DeliverBolusMessage(); @@ -811,6 +822,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, bolusMessage.setDuration(durationInMinutes); bolusMessage.setExtendedAmount(insulin); bolusMessage.setImmediateAmount(0); + bolusMessage.setVibration(disableVibration); int bolusID = connectionService.requestMessage(bolusMessage).await().getBolusId(); InsightBolusID insightBolusID = new InsightBolusID(); insightBolusID.bolusID = bolusID; @@ -925,8 +937,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, if (extendedBolus.durationInMinutes <= 0) { final String _id = extendedBolus._id; if (NSUpload.isIdValid(_id)) - NSUpload.removeCareportalEntryFromNS(_id); - else UploadQueue.removeID("dbAdd", _id); + nsUpload.removeCareportalEntryFromNS(_id); + else uploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } else treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus); @@ -974,7 +986,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { long now = System.currentTimeMillis(); if (connectionService == null) return null; if (System.currentTimeMillis() - connectionService.getLastConnected() > (60 * 60 * 1000)) { @@ -987,7 +999,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, final JSONObject extended = new JSONObject(); try { status.put("timestamp", DateUtil.toISOString(connectionService.getLastConnected())); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extended.put("Version", version); try { extended.put("ActiveProfile", profileFunction.getProfileName()); } catch (Exception e) { @@ -995,13 +1007,13 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, TemporaryBasal tb = treatmentsPlugin.getTempBasalFromHistory(now); if (tb != null) { extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)); - extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); + extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)); extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); } ExtendedBolus eb = treatmentsPlugin.getExtendedBolusFromHistory(now); if (eb != null) { extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()); - extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date)); + extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date)); extended.put("ExtendedBolusRemaining", eb.getPlannedRemainingMinutes()); } extended.put("BaseBasalRate", getBaseBasalRate()); @@ -1379,7 +1391,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, temporaryBasal.durationInMinutes = 0; temporaryBasal.source = Source.PUMP; temporaryBasal.pumpId = pumpID.id; - temporaryBasal.date = timestamp; + temporaryBasal.date = timestamp - 1500L; temporaryBasals.add(temporaryBasal); } @@ -1447,8 +1459,8 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, ExtendedBolus extendedBolus = MainApp.getDbHelper().getExtendedBolusByPumpId(bolusID.id); if (extendedBolus != null) { final String _id = extendedBolus._id; - if (NSUpload.isIdValid(_id)) NSUpload.removeCareportalEntryFromNS(_id); - else UploadQueue.removeID("dbAdd", _id); + if (NSUpload.isIdValid(_id)) nsUpload.removeCareportalEntryFromNS(_id); + else uploadQueue.removeID("dbAdd", _id); MainApp.getDbHelper().delete(extendedBolus); } } else { @@ -1579,7 +1591,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, careportalEvent.eventType = CareportalEvent.NOTE; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } @@ -1613,7 +1625,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, careportalEvent.eventType = event; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error("Unhandled exception", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java index 65034d321a..c5121184ac 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/activities/InsightAlertActivity.java @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.pump.insight.InsightAlertService; import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert; import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertStatus; import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtils; +import info.nightscout.androidaps.utils.HtmlHelper; public class InsightAlertActivity extends DaggerAppCompatActivity { @@ -91,7 +92,7 @@ public class InsightAlertActivity extends DaggerAppCompatActivity { if (description == null) this.errorDescription.setVisibility(View.GONE); else { this.errorDescription.setVisibility(View.VISIBLE); - this.errorDescription.setText(Html.fromHtml(description)); + this.errorDescription.setText(HtmlHelper.INSTANCE.fromHtml(description)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java index f1b4c3f6de..6a4973b42b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/insight/app_layer/remote_control/DeliverBolusMessage.java @@ -14,6 +14,7 @@ public class DeliverBolusMessage extends AppLayerMessage { private double extendedAmount; private int duration; private int bolusId; + private boolean disableVibration = false; public DeliverBolusMessage() { super(MessagePriority.NORMAL, true, true, Service.REMOTE_CONTROL); @@ -22,7 +23,11 @@ public class DeliverBolusMessage extends AppLayerMessage { @Override protected ByteBuf getData() { ByteBuf byteBuf = new ByteBuf(22); - byteBuf.putUInt16LE(805); + // 805 => Old value with vibration (2.6.1 and earlier), 252 => new value without vibrations for firmware 3.x + if (disableVibration) + byteBuf.putUInt16LE(252); + else + byteBuf.putUInt16LE(805); byteBuf.putUInt16LE(BolusTypeIDs.IDS.getID(bolusType)); byteBuf.putUInt16LE(31); byteBuf.putUInt16LE(0); @@ -57,6 +62,8 @@ public class DeliverBolusMessage extends AppLayerMessage { this.duration = duration; } + public void setVibration(boolean disableVibration) { this.disableVibration = disableVibration;} + public int getBolusId() { return bolusId; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java index b5d7fafb4e..44550ebea6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.java @@ -227,14 +227,14 @@ public class MDIPlugin extends PumpPluginBase implements PumpInterface { } @NonNull @Override - public JSONObject getJSONStatus(Profile profile, String profileName) { + public JSONObject getJSONStatus(Profile profile, String profileName, String version) { long now = System.currentTimeMillis(); JSONObject pump = new JSONObject(); JSONObject status = new JSONObject(); JSONObject extended = new JSONObject(); try { status.put("status", "normal"); - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION); + extended.put("Version", version); try { extended.put("ActiveProfile", profileName); } catch (Exception e) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/PumpDeviceState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/PumpDeviceState.java deleted file mode 100644 index ba86963869..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/defs/PumpDeviceState.java +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.medtronic.defs; - -import info.nightscout.androidaps.R; - -/** - * Created by andy on 6/11/18. - */ - -public enum PumpDeviceState { - - NeverContacted(R.string.medtronic_pump_status_never_contacted), // - Sleeping(R.string.medtronic_pump_status_sleeping), // - WakingUp(R.string.medtronic_pump_status_waking_up), // - Active(R.string.medtronic_pump_status_active), // - ErrorWhenCommunicating(R.string.medtronic_pump_status_error_comm), // - TimeoutWhenCommunicating(R.string.medtronic_pump_status_timeout_comm), // - // ProblemContacting(R.string.medtronic_pump_status_problem_contacting), // - PumpUnreachable(R.string.medtronic_pump_status_pump_unreachable), // - InvalidConfiguration(R.string.medtronic_pump_status_invalid_config); - - Integer resourceId; - - PumpDeviceState(int resourceId) { - this.resourceId = resourceId; - } - - public Integer getResourceId() { - return resourceId; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt index bd2479f83f..9590fa25e0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodFragment.kt @@ -100,7 +100,7 @@ class OmnipodFragment : DaggerFragment() { omnipod_refresh.setOnClickListener { if (omnipodPumpPlugin.rileyLinkService?.verifyConfiguration() != true) { - OmnipodUtil.displayNotConfiguredDialog(context) + displayNotConfiguredDialog() } else { omnipod_refresh.isEnabled = false omnipodPumpPlugin.addPodStatusRequest(OmnipodStatusRequest.GetPodState); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java index d84f191f11..0b8adf1235 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/OmnipodPumpPlugin.java @@ -25,7 +25,6 @@ import javax.inject.Singleton; import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.BuildConfig; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.activities.ErrorHelperActivity; import info.nightscout.androidaps.data.DetailedBolusInfo; @@ -74,6 +73,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodRefres import info.nightscout.androidaps.plugins.pump.omnipod.service.RileyLinkOmnipodService; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodUtil; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.TimeChangeType; @@ -120,10 +120,9 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump private Profile currentProfile; - //boolean omnipodServiceRunning = false; + boolean omnipodServiceRunning = false; private long nextPodCheck = 0L; - protected boolean isOmnipodEros = true; //OmnipodDriverState driverState = OmnipodDriverState.NotInitalized; @Inject @@ -141,7 +140,9 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump CommandQueueProvider commandQueue, FabricPrivacy fabricPrivacy, RileyLinkServiceData rileyLinkServiceData, - ServiceTaskExecutor serviceTaskExecutor) { + ServiceTaskExecutor serviceTaskExecutor, + DateUtil dateUtil + ) { super(new PluginDescription() // .mainType(PluginType.PUMP) // @@ -151,47 +152,16 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump .preferencesId(R.xml.pref_omnipod) // .description(R.string.description_pump_omnipod), // PumpType.Insulet_Omnipod, - injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy + injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil ); this.podStateManager = podStateManager; this.rileyLinkServiceData = rileyLinkServiceData; this.serviceTaskExecutor = serviceTaskExecutor; displayConnectionMessages = false; - OmnipodPumpPlugin.plugin = this; this.omnipodUtil = omnipodUtil; this.omnipodPumpStatus = omnipodPumpStatus; - this.isOmnipodEros = true; - } - - protected OmnipodPumpPlugin(PluginDescription pluginDescription, PumpType pumpType, - HasAndroidInjector injector, - AAPSLogger aapsLogger, - RxBusWrapper rxBus, - Context context, - ResourceHelper resourceHelper, - ActivePluginProvider activePlugin, - info.nightscout.androidaps.utils.sharedPreferences.SP sp, - CommandQueueProvider commandQueue, - FabricPrivacy fabricPrivacy) { - super(pluginDescription, pumpType, injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy); - } - - @Deprecated - public static OmnipodPumpPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Plugin not injected jet"); - return plugin; - } - - public PodStateManager getPodStateManager() { - return podStateManager; - } - - @Override - protected void onStart() { - //OmnipodUtil.setDriverState(); // TODO loop @@ -203,39 +173,33 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump // // TODO ccc - if (isOmnipodEros) { + serviceConnection = new ServiceConnection() { - // We can't do this in PodStateManager itself, because JodaTimeAndroid.init() hasn't been called yet - // When PodStateManager is created, which causes an IllegalArgumentException for DateTimeZones not being recognized - podStateManager.loadPodState(); + @Override + public void onServiceDisconnected(ComponentName name) { - serviceConnection = new ServiceConnection() { + aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is disconnected"); + rileyLinkOmnipodService = null; + } - @Override - public void onServiceDisconnected(ComponentName name) { + @Override + public void onServiceConnected(ComponentName name, IBinder service) { - aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is disconnected"); - rileyLinkOmnipodService = null; - } + aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is connected"); + RileyLinkOmnipodService.LocalBinder mLocalBinder = (RileyLinkOmnipodService.LocalBinder) service; + rileyLinkOmnipodService = mLocalBinder.getServiceInstance(); + rileyLinkOmnipodService.verifyConfiguration(); - @Override - public void onServiceConnected(ComponentName name, IBinder service) { + new Thread(() -> { - aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is connected"); - RileyLinkOmnipodService.LocalBinder mLocalBinder = (RileyLinkOmnipodService.LocalBinder) service; - rileyLinkOmnipodService = mLocalBinder.getServiceInstance(); - rileyLinkOmnipodService.verifyConfiguration(); + for (int i = 0; i < 20; i++) { + SystemClock.sleep(5000); - new Thread(() -> { - - for (int i = 0; i < 20; i++) { - SystemClock.sleep(5000); - - aapsLogger.debug(LTag.PUMP, "Starting Omnipod-RileyLink service"); - if (rileyLinkOmnipodService.setNotInPreInit()) { - break; - } + aapsLogger.debug(LTag.PUMP, "Starting Omnipod-RileyLink service"); + if (rileyLinkOmnipodService.setNotInPreInit()) { + break; } + } // if (OmnipodPumpPlugin.this.omnipodPumpStatus != null) { @@ -259,12 +223,45 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump // } // // SystemClock.sleep(5000); - //} - }).start(); - } - }; - } + //} + }).start(); + } + }; + } + + protected OmnipodPumpPlugin(PluginDescription pluginDescription, PumpType pumpType, + HasAndroidInjector injector, + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + Context context, + ResourceHelper resourceHelper, + ActivePluginProvider activePlugin, + info.nightscout.androidaps.utils.sharedPreferences.SP sp, + CommandQueueProvider commandQueue, + FabricPrivacy fabricPrivacy, + DateUtil dateUtil) { + super(pluginDescription, pumpType, injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil); + +// this.rileyLinkUtil = rileyLinkUtil; +// this.medtronicUtil = medtronicUtil; +// this.sp = sp; +// this.medtronicPumpStatus = medtronicPumpStatus; +// this.medtronicHistoryData = medtronicHistoryData; +// this.rileyLinkServiceData = rileyLinkServiceData; +// this.serviceTaskExecutor = serviceTaskExecutor; + } + + public PodStateManager getPodStateManager() { + return podStateManager; + } + + @Override + protected void onStart() { + // We can't do this in PodStateManager itself, because JodaTimeAndroid.init() hasn't been called yet + // When PodStateManager is created, which causes an IllegalArgumentException for DateTimeZones not being recognized + // TODO either find a more elegant solution, or at least make sure this is the right place to do this + podStateManager.loadPodState(); disposable.add(rxBus .toObservable(EventPreferenceChange.class) @@ -440,13 +437,17 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump //rileyLinkOmnipodService.doTuneUpDevice(); } + @Override + public void triggerPumpConfigurationChangedEvent() { + rxBus.send(new EventOmnipodPumpValuesChanged()); + } + @Override public RileyLinkOmnipodService getRileyLinkService() { return rileyLinkOmnipodService; } - @Override public OmnipodUIComm getDeviceCommandExecutor() { return rileyLinkOmnipodService.getDeviceCommandExecutor(); } @@ -522,13 +523,13 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump } else { aapsLogger.warn(LTag.PUMP, "Result was NOT null."); - Intent i = new Intent(MainApp.instance(), ErrorHelperActivity.class); + Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra("soundid", 0); i.putExtra("status", "Pulse Log (copied to clipboard):\n" + result.toString()); i.putExtra("title", resourceHelper.gs(R.string.combo_warning)); i.putExtra("clipboardContent", result.toString()); i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(i); + context.startActivity(i); // OKDialog.show(MainApp.instance().getApplicationContext(), MainApp.gs(R.string.action), // "Pulse Log:\n" + result.toString(), null); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java index 154f45ea12..db56ed905b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodCommunicationManager.java @@ -11,6 +11,7 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy; @@ -19,7 +20,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMe import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RLMessageType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkBLEError; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; -import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.OmnipodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; @@ -95,8 +95,8 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { } @Override - public E createResponseMessage(byte[] payload, Class clazz) { - return (E) new OmnipodPacket(payload); + public RLMessage createResponseMessage(byte[] payload) { + return new OmnipodPacket(payload); } @Override @@ -321,7 +321,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { OmnipodPacket ack = createAckPacket(podStateManager, packetAddress, messageAddress); boolean quiet = false; while (!quiet) try { - sendAndListen(ack, 300, 1, 0, 40, OmnipodPacket.class); + sendAndListen(ack, 300, 1, 0, 40); } catch (RileyLinkCommunicationException ex) { if (RileyLinkBLEError.Timeout.equals(ex.getErrorCode())) { quiet = true; @@ -353,7 +353,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { while (System.currentTimeMillis() < timeoutTime) { OmnipodPacket response = null; try { - response = sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds, OmnipodPacket.class); + response = (OmnipodPacket) sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds); } catch (RileyLinkCommunicationException | OmnipodException ex) { aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in exchangePackets: " + ex.getClass().getSimpleName() + ": " + ex.getMessage()); continue; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodPacket.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodPacket.java index 157e72e51b..3764cf7b60 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodPacket.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodPacket.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.message; -import java.util.Arrays; - import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.RLMessage; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/data/RLHistoryItemOmnipod.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/data/RLHistoryItemOmnipod.java new file mode 100644 index 0000000000..ed4dcb6255 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/data/RLHistoryItemOmnipod.java @@ -0,0 +1,40 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.data; + +import org.joda.time.LocalDateTime; + +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; +import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType; +import info.nightscout.androidaps.utils.resources.ResourceHelper; + +public class RLHistoryItemOmnipod extends RLHistoryItem { + + private OmnipodCommandType omnipodCommandType; + + public RLHistoryItemOmnipod(OmnipodCommandType omnipodCommandType) { + super(new LocalDateTime(), RLHistoryItemSource.OmnipodCommand, RileyLinkTargetDevice.Omnipod); + this.omnipodCommandType = omnipodCommandType; + } + + public String getDescription(ResourceHelper resourceHelper) { + + switch (this.source) { + case RileyLink: + return "State: " + resourceHelper.gs(serviceState.getResourceId(targetDevice)) + + (this.errorCode == null ? "" : ", Error Code: " + errorCode); + + case MedtronicPump: + return resourceHelper.gs(pumpDeviceState.getResourceId()); + + case OmnipodCommand: + return omnipodCommandType.name(); + + default: + return "Unknown Description"; + } + } + + + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java index f2066ebb2b..0026d41f97 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodPumpPluginInterface.java @@ -10,6 +10,7 @@ public interface OmnipodPumpPluginInterface extends PumpInterface { void setDriverState(OmnipodDriverState state); + @Deprecated RxBusWrapper getRxBus(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodDeviceState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodDeviceState.java index 2336905a53..7e0094e637 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodDeviceState.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodDeviceState.java @@ -5,8 +5,9 @@ import info.nightscout.androidaps.R; /** * Created by andy on 4.8.2019 */ - -// FIXME remove +// TODO remove this class and use PumpDeviceState instead +// BS: Actually, don't use PumpDeviceState in Omnipod driver at all; use PodStateManager +// If PumpDeviceState is Omnipod specific; also remove that public enum PodDeviceState { // FIXME diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java index 9607df66a2..e1eefabce8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodStateManager.java @@ -34,11 +34,13 @@ import info.nightscout.androidaps.utils.DateUtil; public abstract class PodStateManager { private final AAPSLogger aapsLogger; + private DateUtil dateUtil; private final Gson gsonInstance; private PodState podState; - public PodStateManager(AAPSLogger aapsLogger) { + public PodStateManager(AAPSLogger aapsLogger, DateUtil dateUtil) { this.aapsLogger = aapsLogger; + this.dateUtil = dateUtil; this.gsonInstance = createGson(); } @@ -279,7 +281,7 @@ public abstract class PodStateManager { // TODO doesn't belong here public final String getExpiryDateAsString() { DateTime expiresAt = getExpiresAt(); - return expiresAt == null ? "???" : DateUtil.dateAndTimeString(expiresAt.toDate()); + return expiresAt == null ? "???" : dateUtil.dateAndTimeString(expiresAt.toDate()); } public final PodProgressStatus getPodProgressStatus() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java index d98721ff15..bfbdbfc9d6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodHistoryActivity.java @@ -148,7 +148,7 @@ public class PodHistoryActivity extends NoSplashAppCompatActivity { statusView.setVisibility(View.GONE); - typeListFull = getTypeList(PumpHistoryEntryGroup.getList()); + typeListFull = getTypeList(PumpHistoryEntryGroup.getTranslatedList(resourceHelper)); ArrayAdapter spinnerAdapter = new ArrayAdapter<>(this, R.layout.spinner_centered, typeListFull); historyTypeSpinner.setAdapter(spinnerAdapter); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt index c509627067..b6e60a707f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/PodManagementActivity.kt @@ -12,9 +12,9 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitPodTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitPodTask.java index 39a150a55d..129d551985 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitPodTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitPodTask.java @@ -6,7 +6,7 @@ import android.view.View; import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType; import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java index f888b30436..c6837f1644 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/pages/InitPodRefreshAction.java @@ -36,6 +36,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish @Inject PodStateManager podStateManager; @Inject AAPSLogger aapsLogger; @Inject SP sp; + @Inject NSUpload nsUpload; public InitPodRefreshAction(HasAndroidInjector injector, PodManagementActivity podManagementActivity, PodActionType actionType) { injector.androidInjector().inject(this); @@ -87,7 +88,7 @@ public class InitPodRefreshAction extends AbstractCancelAction implements Finish careportalEvent.eventType = event; careportalEvent.json = data.toString(); MainApp.getDbHelper().createOrUpdate(careportalEvent); - NSUpload.uploadCareportalEntryToNS(data); + nsUpload.uploadCareportalEntryToNS(data); } catch (JSONException e) { aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception when uploading SiteChange event.", e); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java index 2b0b76a223..47a36d9cb2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/OmnipodPumpStatus.java @@ -8,13 +8,13 @@ import javax.inject.Singleton; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; -import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState; -import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -89,6 +89,24 @@ public class OmnipodPumpStatus extends PumpStatus { return this.rileyLinkErrorDescription; } + @Override + public E getCustomData(String key, Class clazz) { + switch (key) { + // TODO + /* + case "POD_LOT_NUMBER": + return (E) podLotNumber; + + case "POD_AVAILABLE": + return (E) podAvailable; + */ + + default: + return null; + } + + } + // public boolean setNotInPreInit() { // this.inPreInit = false; @@ -168,7 +186,7 @@ public class OmnipodPumpStatus extends PumpStatus { rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(pumpDeviceState, RileyLinkTargetDevice.Omnipod)); - rxBus.send(new EventOmnipodDeviceStatusChange(pumpDeviceState)); + rxBus.send(new EventRileyLinkDeviceStatusChange(pumpDeviceState)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java index 76fde2cebb..a0c1034a1a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.pump.omnipod.driver.comm; +import android.content.Context; import android.content.Intent; import org.joda.time.DateTime; @@ -75,16 +76,18 @@ import io.reactivex.disposables.Disposable; public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface { private final PodStateManager podStateManager; - private OmnipodUtil omnipodUtil; - private AAPSLogger aapsLogger; - private RxBusWrapper rxBus; - private ResourceHelper resourceHelper; - private HasAndroidInjector injector; - private ActivePluginProvider activePlugin; - private OmnipodPumpStatus pumpStatus; + private final OmnipodUtil omnipodUtil; + private final AAPSLogger aapsLogger; + private final RxBusWrapper rxBus; + private final ResourceHelper resourceHelper; + private final HasAndroidInjector injector; + private final ActivePluginProvider activePlugin; + private final OmnipodPumpStatus pumpStatus; + private final Context context; private final OmnipodManager delegate; + //TODO: remove and use injection private static AapsOmnipodManager instance; public static AapsOmnipodManager getInstance() { @@ -93,14 +96,15 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface public AapsOmnipodManager(OmnipodCommunicationManager communicationService, PodStateManager podStateManager, - OmnipodPumpStatus _pumpStatus, + OmnipodPumpStatus pumpStatus, OmnipodUtil omnipodUtil, AAPSLogger aapsLogger, RxBusWrapper rxBus, SP sp, ResourceHelper resourceHelper, HasAndroidInjector injector, - ActivePluginProvider activePlugin) { + ActivePluginProvider activePlugin, + Context context) { if (podStateManager == null) { throw new IllegalArgumentException("Pod state manager can not be null"); } @@ -111,7 +115,8 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface this.resourceHelper = resourceHelper; this.injector = injector; this.activePlugin = activePlugin; - this.pumpStatus = _pumpStatus; + this.pumpStatus = pumpStatus; + this.context = context; delegate = new OmnipodManager(aapsLogger, sp, communicationService, podStateManager); instance = this; @@ -333,7 +338,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface pumpStatus.tempBasalEnd = DateTimeUtil.getTimeInFutureFromMinutes(time, tempBasalPair.getDurationMinutes()); pumpStatus.tempBasalPumpId = pumpId; - TemporaryBasal tempStart = new TemporaryBasal() // + TemporaryBasal tempStart = new TemporaryBasal(injector) // .date(time) // .duration(tempBasalPair.getDurationMinutes()) // .absolute(tempBasalPair.getInsulinRate()) // @@ -465,7 +470,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface addSuccessToHistory(time, PodHistoryEntryType.CancelTemporaryBasal, null); - TemporaryBasal temporaryBasal = new TemporaryBasal() // + TemporaryBasal temporaryBasal = new TemporaryBasal(injector) // .date(time) // .duration(0) // .pumpId(pumpStatus.tempBasalPumpId) @@ -595,12 +600,12 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } private void showErrorDialog(String message, Integer sound) { - Intent intent = new Intent(MainApp.instance(), ErrorHelperActivity.class); + Intent intent = new Intent(context, ErrorHelperActivity.class); intent.putExtra("soundid", sound == null ? 0 : sound); intent.putExtra("status", message); - intent.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror)); + intent.putExtra("title", resourceHelper.gs(R.string.treatmentdeliveryerror)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - MainApp.instance().startActivity(intent); + context.startActivity(intent); } private void showNotification(String message, int urgency, Integer sound) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java index 5723c5bce6..9ef2e31eee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsPodStateManager.java @@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManage import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodPumpValuesChanged; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -28,8 +29,8 @@ public class AapsPodStateManager extends PodStateManager { @Inject public AapsPodStateManager(AAPSLogger aapsLogger, SP sp, OmnipodPumpStatus omnipodPumpStatus, - RxBusWrapper rxBus, ResourceHelper resourceHelper) { - super(aapsLogger); + RxBusWrapper rxBus, ResourceHelper resourceHelper, DateUtil dateUtil) { + super(aapsLogger, dateUtil); if (aapsLogger == null) { throw new IllegalArgumentException("aapsLogger can not be null"); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/db/PodHistoryEntryType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/db/PodHistoryEntryType.java index e776de681f..981796b497 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/db/PodHistoryEntryType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/db/PodHistoryEntryType.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.driver.db; -import androidx.annotation.IdRes; import androidx.annotation.StringRes; import java.util.HashMap; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/ui/OmnipodUIPostprocessor.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/ui/OmnipodUIPostprocessor.java index 710fa47b88..4915069e4a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/ui/OmnipodUIPostprocessor.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/ui/OmnipodUIPostprocessor.java @@ -10,7 +10,6 @@ import javax.inject.Singleton; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.logging.L; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin; @@ -107,7 +106,7 @@ public class OmnipodUIPostprocessor { private boolean isLogEnabled() { - return L.isEnabled(LTag.PUMP); + return true; //L.isEnabled(LTag.PUMP); } public RxBusWrapper getRxBus() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt index 792ced5f32..85c25c21db 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/events/EventOmnipodDeviceStatusChange.kt @@ -1,9 +1,9 @@ package info.nightscout.androidaps.plugins.pump.omnipod.events -import info.nightscout.androidaps.events.Event +import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState +import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState -import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager @@ -11,29 +11,19 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManage /** * Created by andy on 4.8.2019 */ -// FIXME Rename this class to EventRileyLinkStatusChanged and use EventOmnipodPumpValuesChanged -// for changes in Pod status -class EventOmnipodDeviceStatusChange : Event { +// FIXME Remove in favor of EventRileyLinkDeviceStatusChange and EventOmnipodPumpValuesChanged +class EventOmnipodDeviceStatusChange : EventRileyLinkDeviceStatusChange { - var rileyLinkServiceState: RileyLinkServiceState? = null - var rileyLinkError: RileyLinkError? = null var podStateManager: PodStateManager? = null - var errorDescription: String? = null var podDeviceState: PodDeviceState? = null - var pumpDeviceState: PumpDeviceState? = null - @JvmOverloads - constructor(rileyLinkServiceState: RileyLinkServiceState?, rileyLinkError: RileyLinkError? = null) { - this.rileyLinkServiceState = rileyLinkServiceState - this.rileyLinkError = rileyLinkError + constructor(rileyLinkServiceState: RileyLinkServiceState?, rileyLinkError: RileyLinkError? = null) : super(rileyLinkServiceState, rileyLinkError) { } - constructor(commandType: OmnipodCommandType?) { } - constructor(podStateManager: PodStateManager?) { this.podStateManager = podStateManager } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java index c5fd6dd1ba..d96e5e0177 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/service/RileyLinkOmnipodService.java @@ -11,16 +11,15 @@ import javax.inject.Inject; import info.nightscout.androidaps.R; import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCommunicationManager; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RileyLinkBLE; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkEncodingType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; -import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; @@ -112,7 +111,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { this.omnipodCommunicationManager = omnipodCommunicationService; aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podStateManager, omnipodPumpStatus, - omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin); + omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin, this); omnipodUIComm = new OmnipodUIComm(injector, aapsLogger, omnipodUtil, omnipodUIPostprocessor, aapsOmnipodManager); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java index d8d501cf49..de791fe65b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodUtil.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.plugins.pump.omnipod.util; -import android.content.Context; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializer; @@ -18,14 +16,13 @@ import java.util.List; import javax.inject.Inject; import javax.inject.Singleton; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; +import info.nightscout.androidaps.plugins.pump.omnipod.data.RLHistoryItemOmnipod; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertType; @@ -35,8 +32,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodDriverState; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodDeviceStatusChange; -import info.nightscout.androidaps.utils.alertDialogs.OKDialog; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -53,7 +48,6 @@ public class OmnipodUtil { private final ResourceHelper resourceHelper; private final ActivePluginProvider activePlugins; private final SP sp; - private boolean lowLevelDebug = true; private OmnipodCommandType currentCommand; private Gson gsonInstance = createGson(); @@ -95,14 +89,7 @@ public class OmnipodUtil { this.currentCommand = currentCommand; if (currentCommand != null) - rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(currentCommand)); - - rxBus.send(new EventOmnipodDeviceStatusChange((OmnipodCommandType) null)); - } - - public static void displayNotConfiguredDialog(Context context) { - OKDialog.showConfirmation(context, MainApp.gs(R.string.combo_warning), - MainApp.gs(R.string.omnipod_error_operation_not_possible_no_configuration), (Runnable) null); + rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItemOmnipod(currentCommand)); } public OmnipodDriverState getDriverState() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java index 0a1ce1b009..546e3febcd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java @@ -33,6 +33,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodPumpVa import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodRefreshButtonState; import info.nightscout.androidaps.plugins.pump.omnipod.service.RileyLinkOmnipodService; import info.nightscout.androidaps.plugins.pump.omnipod_dash.comm.OmnipodDashCommunicationManager; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.TimeChangeType; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -49,7 +50,6 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP // TODO Dagger //private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); - protected static OmnipodDashPumpPlugin plugin = null; //private RileyLinkOmnipodService omnipodService; //private OmnipodPumpStatus pumpStatusLocal = null; @@ -76,7 +76,9 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP ActivePluginProvider activePlugin, SP sp, CommandQueueProvider commandQueue, - FabricPrivacy fabricPrivacy) { + FabricPrivacy fabricPrivacy, + DateUtil dateUtil + ) { super(new PluginDescription() // .mainType(PluginType.PUMP) // .fragmentClass(OmnipodFragment.class.getName()) // @@ -85,7 +87,7 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP .preferencesId(R.xml.pref_omnipod) // .description(R.string.description_pump_omnipod_dash), // PumpType.Insulet_Omnipod_Dash, - injector, aapsLogger, rxBus, context, resourceHelper, activePlugin, sp, commandQueue, fabricPrivacy + injector, aapsLogger, rxBus, context, resourceHelper, activePlugin, sp, commandQueue, fabricPrivacy, dateUtil ); displayConnectionMessages = false; @@ -133,14 +135,6 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP // }; } - @Deprecated - public static OmnipodDashPumpPlugin getPlugin() { - if (plugin == null) - throw new IllegalStateException("Plugin not injected jet"); - return plugin; - } - - private String getLogPrefix() { return "OmnipodPlugin::"; } @@ -154,7 +148,6 @@ public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodP @Override public void onStart() { - this.isOmnipodEros = false; super.onStart(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java index db594e6af1..023992d730 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java @@ -12,18 +12,19 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunication import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodStateManager; -import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; /** * Created by andy on 4.8.2019 */ // TODO refactor to use dagger, just commented out errors +// TODO is this class used? remove if not public class OmnipodDashCommunicationManager implements OmnipodCommunicationManagerInterface { // TODO Dagger // private static final Logger LOG = LoggerFactory.getLogger(L.PUMPCOMM); + // i didn't find where you instantiate this private static OmnipodDashCommunicationManager omnipodCommunicationManager; private String errorMessage; @@ -38,6 +39,7 @@ public class OmnipodDashCommunicationManager implements OmnipodCommunicationMana return null; } + @Deprecated public static OmnipodDashCommunicationManager getInstance() { return omnipodCommunicationManager; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt index d534e51e2f..3ca7e671ff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpFragment.kt @@ -84,6 +84,6 @@ class VirtualPumpFragment : DaggerFragment() { val pumpType = virtualPumpPlugin.pumpType virtualpump_type?.text = pumpType?.description - virtualpump_type_def?.text = pumpType?.getFullDescription(resourceHelper.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals()) + virtualpump_type_def?.text = pumpType?.getFullDescription(resourceHelper.gs(R.string.virtualpump_pump_def), pumpType.hasExtendedBasals(), resourceHelper) } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt index 007d585408..2ef49e95b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPlugin.kt @@ -2,7 +2,6 @@ package info.nightscout.androidaps.plugins.pump.virtual import android.os.SystemClock import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo @@ -17,7 +16,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.common.ManufacturerType -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.actions.defs.CustomActionType import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification @@ -51,30 +50,22 @@ class VirtualPumpPlugin @Inject constructor( private val sp: SP, private val profileFunction: ProfileFunction, private val treatmentsPlugin: TreatmentsPlugin, - commandQueue: CommandQueueProvider + commandQueue: CommandQueueProvider, + private val config: Config, + private val dateUtil: DateUtil ) : PumpPluginBase(PluginDescription() .mainType(PluginType.PUMP) .fragmentClass(VirtualPumpFragment::class.java.name) .pluginName(R.string.virtualpump) .shortName(R.string.virtualpump_shortname) .preferencesId(R.xml.pref_virtualpump) - .neverVisible(Config.NSCLIENT) + .neverVisible(config.NSCLIENT) .description(R.string.description_pump_virtual) .setDefault(), injector, aapsLogger, resourceHelper, commandQueue ), PumpInterface { - companion object { - private lateinit var virtualPumpPlugin: VirtualPumpPlugin - - @Deprecated("Use dagger to get an instance") - fun getPlugin(): VirtualPumpPlugin { - checkNotNull(virtualPumpPlugin) { "Accessing VirtualPumpPlugin before first instantiation" } - return virtualPumpPlugin - } - } - private val disposable = CompositeDisposable() var batteryPercent = 50 var reservoirInUnits = 50 @@ -85,7 +76,6 @@ class VirtualPumpPlugin @Inject constructor( private val pumpDescription = PumpDescription() init { - virtualPumpPlugin = this pumpDescription.isBolusCapable = true pumpDescription.bolusStep = 0.1 pumpDescription.isExtendedBolusCapable = true @@ -131,7 +121,7 @@ class VirtualPumpPlugin @Inject constructor( } override fun isFakingTempsByExtendedBoluses(): Boolean { - return Config.NSCLIENT && getFakingStatus() + return config.NSCLIENT && getFakingStatus() } override fun loadTDDs(): PumpEnactResult { //no result, could read DB in the future? @@ -335,7 +325,7 @@ class VirtualPumpPlugin @Inject constructor( return result } - override fun getJSONStatus(profile: Profile, profileName: String): JSONObject { + override fun getJSONStatus(profile: Profile, profileName: String, version: String): JSONObject { val now = System.currentTimeMillis() if (!sp.getBoolean("virtualpump_uploadstatus", false)) { return JSONObject() @@ -347,7 +337,7 @@ class VirtualPumpPlugin @Inject constructor( try { battery.put("percent", batteryPercent) status.put("status", "normal") - extended.put("Version", BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION) + extended.put("Version", version) try { extended.put("ActiveProfile", profileName) } catch (ignored: Exception) { @@ -355,13 +345,13 @@ class VirtualPumpPlugin @Inject constructor( val tb = treatmentsPlugin.getTempBasalFromHistory(now) if (tb != null) { extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(now, profile)) - extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)) + extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)) extended.put("TempBasalRemaining", tb.plannedRemainingMinutes) } val eb = treatmentsPlugin.getExtendedBolusFromHistory(now) if (eb != null) { extended.put("ExtendedBolusAbsoluteRate", eb.absoluteRate()) - extended.put("ExtendedBolusStart", DateUtil.dateAndTimeString(eb.date)) + extended.put("ExtendedBolusStart", dateUtil.dateAndTimeString(eb.date)) extended.put("ExtendedBolusRemaining", eb.plannedRemainingMinutes) } status.put("timestamp", DateUtil.toISOString(now)) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt index 43e8b89a5d..9e826156ee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPlugin.kt @@ -2,13 +2,13 @@ package info.nightscout.androidaps.plugins.sensitivity import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.SensitivityInterface import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.SafeParse import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -20,12 +20,11 @@ abstract class AbstractSensitivityPlugin( pluginDescription: PluginDescription, injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: - ResourceHelper, + resourceHelper: ResourceHelper, val sp: SP ) : PluginBase(pluginDescription, aapsLogger, resourceHelper, injector), SensitivityInterface { - abstract override fun detectSensitivity(plugin: IobCobCalculatorPlugin, fromTime: Long, toTime: Long): AutosensResult + abstract override fun detectSensitivity(plugin: IobCobCalculatorInterface, fromTime: Long, toTime: Long): AutosensResult fun fillResult(ratio: Double, carbsAbsorbed: Double, pastSensitivity: String, ratioLimit: String, sensResult: String, deviationsArraySize: Int): AutosensResult { @@ -65,4 +64,4 @@ abstract class AbstractSensitivityPlugin( output.sensResult = sensResult return output } -} \ No newline at end of file +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java index 090e980d9f..9f81d9306e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.java @@ -16,12 +16,13 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; import info.nightscout.androidaps.interfaces.PluginDescription; import info.nightscout.androidaps.interfaces.PluginType; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; +import info.nightscout.androidaps.interfaces.ProfileFunction; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; import info.nightscout.androidaps.utils.DateUtil; @@ -35,9 +36,8 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { - private SP sp; private ProfileFunction profileFunction; - private ResourceHelper resourceHelper; + private DateUtil dateUtil; @Inject public SensitivityAAPSPlugin( @@ -45,7 +45,8 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, - ProfileFunction profileFunction + ProfileFunction profileFunction, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -55,20 +56,20 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { .description(R.string.description_sensitivity_aaps), injector, aapsLogger, resourceHelper, sp ); - this.sp = sp; this.profileFunction = profileFunction; + this.dateUtil = dateUtil; } @NonNull @Override - public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); - String age = sp.getString(R.string.key_age, ""); + String age = getSp().getString(R.string.key_age, ""); int defaultHours = 24; - if (age.equals(resourceHelper.gs(R.string.key_adult))) defaultHours = 24; - if (age.equals(resourceHelper.gs(R.string.key_teenage))) defaultHours = 4; - if (age.equals(resourceHelper.gs(R.string.key_child))) defaultHours = 4; - int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); + if (age.equals(getResourceHelper().gs(R.string.key_adult))) defaultHours = 24; + if (age.equals(getResourceHelper().gs(R.string.key_teenage))) defaultHours = 4; + if (age.equals(getResourceHelper().gs(R.string.key_child))) defaultHours = 4; + int hoursForDetection = getSp().getInt(R.string.key_openapsama_autosens_period, defaultHours); Profile profile = profileFunction.getProfile(); @@ -84,7 +85,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -115,7 +116,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { } // reset deviations after profile switch - if (ProfileSwitch.isEvent5minBack(getAapsLogger(), profileSwitches, autosensData.time, true)) { + if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { deviationsArray.clear(); pastSensitivity += "(PROFILESWITCH)"; } @@ -171,7 +172,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { sensResult, deviationsArray.size()); getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + DateUtil.dateAndTimeString(toTime) + + + dateUtil.dateAndTimeString(toTime) + " ratio: " + output.ratio + " mealCOB: " + current.cob); getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: deviations " + Arrays.toString(deviations)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java index 8424a65a93..1283ef268a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.java @@ -2,6 +2,8 @@ package info.nightscout.androidaps.plugins.sensitivity; import androidx.collection.LongSparseArray; +import org.jetbrains.annotations.NotNull; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -15,14 +17,15 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; 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.logging.LTag; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -34,7 +37,8 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; @Singleton public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { - private ProfileFunction profileFunction; + private final ProfileFunction profileFunction; + private final DateUtil dateUtil; @Inject public SensitivityOref1Plugin( @@ -42,7 +46,8 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, - ProfileFunction profileFunction + ProfileFunction profileFunction, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -55,10 +60,11 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { injector, aapsLogger, resourceHelper, sp ); this.profileFunction = profileFunction; + this.dateUtil = dateUtil; } - @Override - public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + @NotNull @Override + public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { // todo this method is called from the IobCobCalculatorPlugin, which leads to a circular // dependency, this should be avoided LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); @@ -78,7 +84,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { // the current AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -88,13 +94,13 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { //[0] = 8 hour //[1] = 24 hour //Deviationshour has DeviationsArray - List deviationsHour = Arrays.asList(new ArrayList(),new ArrayList()); - List pastSensitivityArray = Arrays.asList("",""); - List sensResultArray = Arrays.asList("",""); - List ratioArray = Arrays.asList(0d,0d); - List deviationCategory = Arrays.asList(96d,288d); - List ratioLimitArray = Arrays.asList("",""); - List hoursDetection = Arrays.asList(8d,24d); + List> deviationsHour = Arrays.asList(new ArrayList<>(), new ArrayList<>()); + List pastSensitivityArray = Arrays.asList("", ""); + List sensResultArray = Arrays.asList("", ""); + List ratioArray = Arrays.asList(0d, 0d); + List deviationCategory = Arrays.asList(96d, 288d); + List ratioLimitArray = Arrays.asList("", ""); + List hoursDetection = Arrays.asList(8d, 24d); int index = 0; @@ -113,8 +119,8 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { int hoursegment = 0; //hoursegment = 0 = 8 hour //hoursegment = 1 = 24 hour - while (hoursegment < deviationsHour.size()){ - ArrayList deviationsArray = deviationsHour.get(hoursegment); + while (hoursegment < deviationsHour.size()) { + ArrayList deviationsArray = deviationsHour.get(hoursegment); String pastSensitivity = pastSensitivityArray.get(hoursegment); // reset deviations after site change @@ -124,7 +130,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { } // reset deviations after profile switch - if (ProfileSwitch.isEvent5minBack(getAapsLogger(),profileSwitches, autosensData.time, true)) { + if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { deviationsArray.clear(); pastSensitivity += "(PROFILESWITCH)"; } @@ -140,10 +146,9 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { deviationsArray.add(deviation); - for (int i = 0; i < autosensData.extraDeviation.size(); i++) - deviationsArray.add(autosensData.extraDeviation.get(i)); + deviationsArray.addAll(autosensData.extraDeviation); - if (deviationsArray.size() > deviationCategory.get(hoursegment)){ + if (deviationsArray.size() > deviationCategory.get(hoursegment)) { deviationsArray.remove(0); } @@ -155,41 +160,37 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { } //Update the data back to the parent - deviationsHour.set(hoursegment,deviationsArray); - pastSensitivityArray.set(hoursegment,pastSensitivity); + deviationsHour.set(hoursegment, deviationsArray); + pastSensitivityArray.set(hoursegment, pastSensitivity); hoursegment++; - } - index++; + } + index++; } // when we have less than 8h/24 worth of deviation data, add up to 90m of zero deviations // this dampens any large sensitivity changes detected based on too little data, without ignoring them completely for (int i = 0; i < deviationsHour.size(); i++) { - ArrayList deviations = deviationsHour.get(i); - getAapsLogger().debug(LTag.AUTOSENS,"Using most recent " + deviations.size() + " deviations"); + ArrayList deviations = deviationsHour.get(i); + getAapsLogger().debug(LTag.AUTOSENS, "Using most recent " + deviations.size() + " deviations"); if (deviations.size() < deviationCategory.get(i)) { int pad = (int) Math.round((1 - (double) deviations.size() / deviationCategory.get(i)) * 18); - getAapsLogger().debug(LTag.AUTOSENS,"Adding " + pad + " more zero deviations"); - for (int d = 0; d < pad; d++) { ; + getAapsLogger().debug(LTag.AUTOSENS, "Adding " + pad + " more zero deviations"); + for (int d = 0; d < pad; d++) { deviations.add(0d); } } //Update the data back to the parent - deviationsHour.set(i,deviations); + deviationsHour.set(i, deviations); } int hourused = 0; - while (hourused < deviationsHour.size()){ + while (hourused < deviationsHour.size()) { ArrayList deviationsArray = deviationsHour.get(hourused); String pastSensitivity = pastSensitivityArray.get(hourused); String sensResult = "(8 hours) "; - String senstime = sensResult; - if (hourused == 1){ - senstime = "(24 hours) "; - sensResult = senstime; - } + if (hourused == 1) sensResult = "(24 hours) "; String ratioLimit = ""; Double[] deviations = new Double[deviationsArray.size()]; @@ -198,7 +199,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { double sens = profile.getIsfMgdl(); - getAapsLogger().debug(LTag.AUTOSENS,"Records: " + index + " " + pastSensitivity); + getAapsLogger().debug(LTag.AUTOSENS, "Records: " + index + " " + pastSensitivity); Arrays.sort(deviations); double pSensitive = IobCobCalculatorPlugin.percentile(deviations, 0.50); @@ -207,39 +208,39 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { double basalOff = 0; if (pSensitive < 0) { // sensitive - basalOff = pSensitive * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); - sensResult+= "Excess insulin sensitivity detected"; + basalOff = pSensitive * (60.0 / 5) / sens; + sensResult += "Excess insulin sensitivity detected"; } else if (pResistant > 0) { // resistant - basalOff = pResistant * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); - sensResult+= "Excess insulin resistance detected"; + basalOff = pResistant * (60.0 / 5) / sens; + sensResult += "Excess insulin resistance detected"; } else { - sensResult+= "Sensitivity normal"; + sensResult += "Sensitivity normal"; } - getAapsLogger().debug(LTag.AUTOSENS,sensResult); + getAapsLogger().debug(LTag.AUTOSENS, sensResult); double ratio = 1 + (basalOff / profile.getMaxDailyBasal()); //Update the data back to the parent - sensResultArray.set(hourused,sensResult); - ratioArray.set(hourused,ratio); - ratioLimitArray.set(hourused,ratioLimit); + sensResultArray.set(hourused, sensResult); + ratioArray.set(hourused, ratio); + ratioLimitArray.set(hourused, ratioLimit); hourused++; } int key = 1; - String comparison = " 8 h ratio " +ratioArray.get(0)+" vs 24h ratio "+ratioArray.get(1); + String comparison = " 8 h ratio " + ratioArray.get(0) + " vs 24h ratio " + ratioArray.get(1); //use 24 hour ratio by default //if the 8 hour ratio is less than the 24 hour ratio, the 8 hour ratio is used - if(ratioArray.get(0) < ratioArray.get(1)){ - key = 0; + if (ratioArray.get(0) < ratioArray.get(1)) { + key = 0; } - String message = hoursDetection.get(key)+" of sensitivity used"; + //String message = hoursDetection.get(key) + " of sensitivity used"; AutosensResult output = fillResult(ratioArray.get(key), current.cob, pastSensitivityArray.get(key), ratioLimitArray.get(key), - sensResultArray.get(key)+comparison, deviationsHour.get(key).size()); + sensResultArray.get(key) + comparison, deviationsHour.get(key).size()); getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + DateUtil.dateAndTimeString(toTime) + + + dateUtil.dateAndTimeString(toTime) + " ratio: " + output.ratio + " mealCOB: " + current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java index 09a4a20838..27b1820735 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.java @@ -13,14 +13,14 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.ProfileSwitch; +import info.nightscout.androidaps.interfaces.IobCobCalculatorInterface; 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.logging.LTag; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensData; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.data.AutosensData; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -32,7 +32,7 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin { private SP sp; - private ResourceHelper resourceHelper; + private DateUtil dateUtil; private ProfileFunction profileFunction; @Inject @@ -41,7 +41,8 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, - ProfileFunction profileFunction + ProfileFunction profileFunction, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -52,19 +53,19 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin injector, aapsLogger, resourceHelper, sp ); this.sp = sp; - this.resourceHelper = resourceHelper; + this.dateUtil = dateUtil; this.profileFunction = profileFunction; } @Override - public AutosensResult detectSensitivity(IobCobCalculatorPlugin iobCobCalculatorPlugin, long fromTime, long toTime) { + public AutosensResult detectSensitivity(IobCobCalculatorInterface iobCobCalculatorPlugin, long fromTime, long toTime) { LongSparseArray autosensDataTable = iobCobCalculatorPlugin.getAutosensDataTable(); String age = sp.getString(R.string.key_age, ""); int defaultHours = 24; - if (age.equals(resourceHelper.gs(R.string.key_adult))) defaultHours = 24; - if (age.equals(resourceHelper.gs(R.string.key_teenage))) defaultHours = 4; - if (age.equals(resourceHelper.gs(R.string.key_child))) defaultHours = 4; + if (age.equals(getResourceHelper().gs(R.string.key_adult))) defaultHours = 24; + if (age.equals(getResourceHelper().gs(R.string.key_teenage))) defaultHours = 4; + if (age.equals(getResourceHelper().gs(R.string.key_child))) defaultHours = 4; int hoursForDetection = sp.getInt(R.string.key_openapsama_autosens_period, defaultHours); if (autosensDataTable == null || autosensDataTable.size() < 4) { @@ -74,7 +75,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin AutosensData current = iobCobCalculatorPlugin.getAutosensData(toTime); // this is running inside lock already if (current == null) { - getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + DateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); + getAapsLogger().debug(LTag.AUTOSENS, "No autosens data available. toTime: " + dateUtil.dateAndTimeString(toTime) + " lastDataTime: " + iobCobCalculatorPlugin.lastDataTime()); return new AutosensResult(); } @@ -117,7 +118,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } // reset deviations after profile switch - if (ProfileSwitch.isEvent5minBack(getAapsLogger(), profileSwitches, autosensData.time, true)) { + if (new ProfileSwitch(getInjector()).isEvent5minBack(profileSwitches, autosensData.time, true)) { data.clear(); pastSensitivity += "(PROFILESWITCH)"; } @@ -145,10 +146,10 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin } if (data.size() == 0) { - getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); + getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)); return new AutosensResult(); } else { - getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + DateUtil.dateAndTimeString(fromTime) + " toTime: " + DateUtil.dateAndTimeString(toTime)); + getAapsLogger().debug(LTag.AUTOSENS, "Data size: " + data.size() + " fromTime: " + dateUtil.dateAndTimeString(fromTime) + " toTime: " + dateUtil.dateAndTimeString(toTime)); } double weightedsum = 0; @@ -192,7 +193,7 @@ public class SensitivityWeightedAveragePlugin extends AbstractSensitivityPlugin sensResult, data.size()); getAapsLogger().debug(LTag.AUTOSENS, "Sensitivity to: " - + DateUtil.dateAndTimeString(toTime) + + + dateUtil.dateAndTimeString(toTime) + " ratio: " + output.ratio + " mealCOB: " + current.cob); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt index f95b8b1a05..2b0d38fab8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/BGSourceFragment.kt @@ -5,6 +5,7 @@ import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView @@ -12,15 +13,16 @@ import dagger.android.support.DaggerFragment import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished import info.nightscout.androidaps.plugins.source.BGSourceFragment.RecyclerViewAdapter.BgReadingsViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable @@ -32,6 +34,8 @@ class BGSourceFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil + @Inject lateinit var databaseHelper: DatabaseHelperInterface private val disposable = CompositeDisposable() private val MILLS_TO_THE_PAST = T.hours(12).msecs() @@ -81,9 +85,9 @@ class BGSourceFragment : DaggerFragment() { val bgReading = bgReadings[position] holder.ns.visibility = if (NSUpload.isIdValid(bgReading._id)) View.VISIBLE else View.GONE holder.invalid.visibility = if (!bgReading.isValid) View.VISIBLE else View.GONE - holder.date.text = DateUtil.dateAndTimeString(bgReading.date) + holder.date.text = dateUtil.dateAndTimeString(bgReading.date) holder.value.text = bgReading.valueToUnitsToString(profileFunction.getUnits()) - holder.direction.text = bgReading.directionToSymbol() + holder.direction.setImageResource(bgReading.directionToIcon(databaseHelper)) holder.remove.tag = bgReading } @@ -94,7 +98,7 @@ class BGSourceFragment : DaggerFragment() { inner class BgReadingsViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var date: TextView = itemView.findViewById(R.id.bgsource_date) var value: TextView = itemView.findViewById(R.id.bgsource_value) - var direction: TextView = itemView.findViewById(R.id.bgsource_direction) + var direction: ImageView = itemView.findViewById(R.id.bgsource_direction) var invalid: TextView = itemView.findViewById(R.id.invalid_sign) var ns: TextView = itemView.findViewById(R.id.ns_sign) var remove: TextView = itemView.findViewById(R.id.bgsource_remove) @@ -103,7 +107,7 @@ class BGSourceFragment : DaggerFragment() { remove.setOnClickListener { v: View -> val bgReading = v.tag as BgReading activity?.let { activity -> - val text = DateUtil.dateAndTimeString(bgReading.date) + "\n" + bgReading.valueToUnitsToString(profileFunction.getUnits()) + val text = dateUtil.dateAndTimeString(bgReading.date) + "\n" + bgReading.valueToUnitsToString(profileFunction.getUnits()) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { bgReading.isValid = false MainApp.getDbHelper().update(bgReading) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 7e854f7e96..27ad7fec82 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -4,6 +4,7 @@ import android.content.Intent import android.content.pm.PackageManager import androidx.core.content.ContextCompat import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Config import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -31,18 +32,25 @@ class DexcomPlugin @Inject constructor( private val sp: SP, private val mainApp: MainApp, resourceHelper: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val nsUpload: NSUpload, + config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.dexcom_app_patched) .shortName(R.string.dexcom_short) .preferencesId(R.xml.pref_bgsourcedexcom) - .description(R.string.description_source_dexcom) - .setDefault(), + .description(R.string.description_source_dexcom), aapsLogger, resourceHelper, injector ), BgSourceInterface { + init { + if (!config.NSCLIENT) { + pluginDescription.setDefault() + } + } + override fun advancedFilteringSupported(): Boolean { return true } @@ -78,10 +86,10 @@ class DexcomPlugin @Inject constructor( bgReading.raw = 0.0 if (MainApp.getDbHelper().createIfNotExists(bgReading, "Dexcom$sensorType")) { if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType") + nsUpload.uploadBg(bgReading, "AndroidAPS-Dexcom$sensorType") } if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } @@ -108,7 +116,7 @@ class DexcomPlugin @Inject constructor( careportalEvent.eventType = CareportalEvent.BGCHECK careportalEvent.json = jsonObject.toString() MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(jsonObject) + nsUpload.uploadCareportalEntryToNS(jsonObject) } } } @@ -128,7 +136,7 @@ class DexcomPlugin @Inject constructor( careportalEvent.eventType = CareportalEvent.SENSORCHANGE careportalEvent.json = jsonObject.toString() MainApp.getDbHelper().createOrUpdate(careportalEvent) - NSUpload.uploadCareportalEntryToNS(jsonObject) + nsUpload.uploadCareportalEntryToNS(jsonObject) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index 91683b3f4f..9141d57214 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt @@ -28,7 +28,9 @@ class EversensePlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -50,7 +52,7 @@ class EversensePlugin @Inject constructor( if (bundle.containsKey("placementModeInProgress")) aapsLogger.debug(LTag.BGSOURCE, "placementModeInProgress: " + bundle.getBoolean("placementModeInProgress")) if (bundle.containsKey("glucoseLevel")) aapsLogger.debug(LTag.BGSOURCE, "glucoseLevel: " + bundle.getInt("glucoseLevel")) if (bundle.containsKey("glucoseTrendDirection")) aapsLogger.debug(LTag.BGSOURCE, "glucoseTrendDirection: " + bundle.getString("glucoseTrendDirection")) - if (bundle.containsKey("glucoseTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamp: " + DateUtil.dateAndTimeString(bundle.getLong("glucoseTimestamp"))) + if (bundle.containsKey("glucoseTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamp: " + dateUtil.dateAndTimeString(bundle.getLong("glucoseTimestamp"))) if (bundle.containsKey("batteryLevel")) aapsLogger.debug(LTag.BGSOURCE, "batteryLevel: " + bundle.getString("batteryLevel")) if (bundle.containsKey("signalStrength")) aapsLogger.debug(LTag.BGSOURCE, "signalStrength: " + bundle.getString("signalStrength")) if (bundle.containsKey("transmitterVersionNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterVersionNumber: " + bundle.getString("transmitterVersionNumber")) @@ -58,7 +60,7 @@ class EversensePlugin @Inject constructor( if (bundle.containsKey("transmitterModelNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterModelNumber: " + bundle.getString("transmitterModelNumber")) if (bundle.containsKey("transmitterSerialNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterSerialNumber: " + bundle.getString("transmitterSerialNumber")) if (bundle.containsKey("transmitterAddress")) aapsLogger.debug(LTag.BGSOURCE, "transmitterAddress: " + bundle.getString("transmitterAddress")) - if (bundle.containsKey("sensorInsertionTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "sensorInsertionTimestamp: " + DateUtil.dateAndTimeString(bundle.getLong("sensorInsertionTimestamp"))) + if (bundle.containsKey("sensorInsertionTimestamp")) aapsLogger.debug(LTag.BGSOURCE, "sensorInsertionTimestamp: " + dateUtil.dateAndTimeString(bundle.getLong("sensorInsertionTimestamp"))) if (bundle.containsKey("transmitterVersionNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterVersionNumber: " + bundle.getString("transmitterVersionNumber")) if (bundle.containsKey("transmitterConnectionState")) aapsLogger.debug(LTag.BGSOURCE, "transmitterConnectionState: " + bundle.getString("transmitterConnectionState")) if (bundle.containsKey("glucoseLevels")) { @@ -76,10 +78,10 @@ class EversensePlugin @Inject constructor( bgReading.raw = 0.0 val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Eversense") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Eversense") + nsUpload.uploadBg(bgReading, "AndroidAPS-Eversense") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } @@ -102,7 +104,7 @@ class EversensePlugin @Inject constructor( data.put("glucoseType", "Finger") data.put("glucose", calibrationGlucoseLevels[i]) data.put("units", Constants.MGDL) - NSUpload.uploadCareportalEntryToNS(data) + nsUpload.uploadCareportalEntryToNS(data) } } catch (e: JSONException) { aapsLogger.error("Unhandled exception", e) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt index aa498105a6..4e10a9c728 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/NSClientSourcePlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.db.BgReading @@ -26,7 +27,8 @@ class NSClientSourcePlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + config: Config ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -38,6 +40,14 @@ class NSClientSourcePlugin @Inject constructor( private var lastBGTimeStamp: Long = 0 private var isAdvancedFilteringEnabled = false + init { + if (config.NSCLIENT) { + pluginDescription + .alwaysEnabled(true) + .setDefault() + } + } + override fun advancedFilteringSupported(): Boolean { return isAdvancedFilteringEnabled } @@ -70,7 +80,7 @@ class NSClientSourcePlugin @Inject constructor( private fun storeSgv(sgvJson: JSONObject) { val nsSgv = NSSgv(sgvJson) - val bgReading = BgReading(nsSgv) + val bgReading = BgReading(injector, nsSgv) MainApp.getDbHelper().createIfNotExists(bgReading, "NS") detectSource(safeGetString(sgvJson, "device", "none"), safeGetLong(sgvJson, "mills")) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index c33cfaee0f..2032dd4479 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -26,7 +26,8 @@ class PoctechPlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -58,10 +59,10 @@ class PoctechPlugin @Inject constructor( if (safeGetString(json, "units", Constants.MGDL) == "mmol/L") bgReading.value = bgReading.value * Constants.MMOLL_TO_MGDL val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Poctech") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Poctech") + nsUpload.uploadBg(bgReading, "AndroidAPS-Poctech") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } catch (e: JSONException) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index bb008b383b..3678f130a4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -2,6 +2,7 @@ package info.nightscout.androidaps.plugins.source import android.content.Intent import android.os.Handler +import android.os.HandlerThread import dagger.android.HasAndroidInjector import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R @@ -12,12 +13,15 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag +import info.nightscout.androidaps.plugins.general.automation.AutomationPlugin +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP import java.util.* import javax.inject.Inject import javax.inject.Singleton @@ -30,17 +34,20 @@ class RandomBgPlugin @Inject constructor( resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, private val virtualPumpPlugin: VirtualPumpPlugin, - private val buildHelper: BuildHelper + private val buildHelper: BuildHelper, + private val sp: SP, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) .pluginName(R.string.randombg) .shortName(R.string.randombg_short) + .preferencesId(R.xml.pref_bgsource) .description(R.string.description_source_randombg), aapsLogger, resourceHelper, injector ), BgSourceInterface { - private val loopHandler = Handler() + private val loopHandler : Handler = Handler(HandlerThread(RandomBgPlugin::class.java.simpleName + "Handler").also { it.start() }.looper) private lateinit var refreshLoop: Runnable companion object { @@ -55,7 +62,7 @@ class RandomBgPlugin @Inject constructor( } override fun advancedFilteringSupported(): Boolean { - return false + return true } override fun onStart() { @@ -85,7 +92,12 @@ class RandomBgPlugin @Inject constructor( bgReading.value = bgMgdl bgReading.date = DateUtil.now() bgReading.raw = bgMgdl - MainApp.getDbHelper().createIfNotExists(bgReading, "RandomBG") + if (MainApp.getDbHelper().createIfNotExists(bgReading, "RandomBG")) { + if (sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) + nsUpload.uploadBg(bgReading, "AndroidAPS-RandomBG") + if (sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) + nsUpload.sendToXdrip(bgReading) + } aapsLogger.debug(LTag.BGSOURCE, "Generated BG: $bgReading") } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index db4c658614..1ba7958b61 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -22,7 +22,8 @@ class TomatoPlugin @Inject constructor( injector: HasAndroidInjector, resourceHelper: ResourceHelper, aapsLogger: AAPSLogger, - private val sp: SP + private val sp: SP, + private val nsUpload: NSUpload ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -46,10 +47,10 @@ class TomatoPlugin @Inject constructor( bgReading.date = bundle.getLong("com.fanqies.tomatofn.Extras.Time") val isNew = MainApp.getDbHelper().createIfNotExists(bgReading, "Tomato") if (isNew && sp.getBoolean(R.string.key_dexcomg5_nsupload, false)) { - NSUpload.uploadBg(bgReading, "AndroidAPS-Tomato") + nsUpload.uploadBg(bgReading, "AndroidAPS-Tomato") } if (isNew && sp.getBoolean(R.string.key_dexcomg5_xdripupload, false)) { - NSUpload.sendToXdrip(bgReading) + nsUpload.sendToXdrip(bgReading) } } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index cd81621252..34ab6bde72 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java @@ -33,16 +33,19 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.db.DatabaseHelper; import info.nightscout.androidaps.db.ICallback; import info.nightscout.androidaps.db.Source; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.events.Event; import info.nightscout.androidaps.events.EventNsTreatment; import info.nightscout.androidaps.events.EventReloadTreatmentData; import info.nightscout.androidaps.events.EventTreatmentChange; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.JsonHelper; import io.reactivex.disposables.CompositeDisposable; @@ -59,6 +62,7 @@ public class TreatmentService extends OrmLiteBaseService { @Inject FabricPrivacy fabricPrivacy; @Inject RxBusWrapper rxBus; @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject DatabaseHelperInterface databaseHelper; private CompositeDisposable disposable = new CompositeDisposable(); @@ -288,7 +292,7 @@ public class TreatmentService extends OrmLiteBaseService { } try { Treatment old; - treatment.date = DatabaseHelper.roundDateToSec(treatment.date); + treatment.date = databaseHelper.roundDateToSec(treatment.date); if (treatment.source == Source.PUMP) { // check for changed from pump change in NS @@ -304,6 +308,9 @@ public class TreatmentService extends OrmLiteBaseService { //preserve carbs if (existingTreatment.isValid && existingTreatment.carbs > 0 && treatment.carbs == 0) { treatment.carbs = existingTreatment.carbs; + // preserve insulin + } else if (existingTreatment.isValid && existingTreatment.insulin > 0 && treatment.insulin == 0) { + treatment.insulin = existingTreatment.insulin; } getDao().delete(existingTreatment); // need to delete/create because date may change too @@ -411,7 +418,7 @@ public class TreatmentService extends OrmLiteBaseService { aapsLogger.debug(LTag.DATATREATMENTS, "DoubleBolusDebug: createOrUpdateMedtronic:: originalTreatment={}, fromNightScout={}", treatment, fromNightScout); try { - treatment.date = DatabaseHelper.roundDateToSec(treatment.date); + treatment.date = databaseHelper.roundDateToSec(treatment.date); Treatment existingTreatment = getRecord(treatment.pumpId, treatment.date); @@ -538,37 +545,6 @@ public class TreatmentService extends OrmLiteBaseService { return (Math.abs(diff) <= 0.00001); } - @Deprecated - private void treatmentCopy(Treatment oldTreatment, Treatment newTreatment, boolean fromNightScout) { - - aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [old={}, new={}]", oldTreatment.toString(), newTreatment.toString()); - - - if (fromNightScout) { - long pumpId_old = oldTreatment.pumpId; - boolean isSMB = (oldTreatment.isSMB || newTreatment.isSMB); - - oldTreatment.copyFrom(newTreatment); - - if (pumpId_old != 0) { - oldTreatment.pumpId = pumpId_old; - } - - if (oldTreatment.pumpId != 0 && oldTreatment.source != Source.PUMP) { - oldTreatment.source = Source.PUMP; - } - - oldTreatment.isSMB = isSMB; - - } else { - oldTreatment.copyFrom(newTreatment); - } - - aapsLogger.debug(LTag.DATATREATMENTS, "treatmentCopy [newAfterChange={}]", oldTreatment.toString()); - - } - - public Treatment getRecord(long pumpId, long date) { Treatment record = null; @@ -616,6 +592,53 @@ public class TreatmentService extends OrmLiteBaseService { } } + /** + * Returns the newest record with insulin > 0 + */ + @Nullable + public Treatment getLastBolus(boolean excludeSMB) { + try { + QueryBuilder queryBuilder = getDao().queryBuilder(); + Where where = queryBuilder.where(); + where.gt("insulin", 0); + where.and().le("date", DateUtil.now()); + where.and().eq("isValid", true); + if (excludeSMB) where.and().eq("isSMB", false); + queryBuilder.orderBy("date", false); + queryBuilder.limit(1L); + + List result = getDao().query(queryBuilder.prepare()); + if (result.isEmpty()) + return null; + return result.get(0); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + + /** + * Returns the newest record with carbs > 0 + */ + @Nullable + public Treatment getLastCarb() { + try { + QueryBuilder queryBuilder = getDao().queryBuilder(); + Where where = queryBuilder.where(); + where.gt("carbs", 0); + where.and().le("date", DateUtil.now()); + where.and().eq("isValid", true); + queryBuilder.orderBy("date", false); + queryBuilder.limit(1L); + + List result = getDao().query(queryBuilder.prepare()); + if (result.isEmpty()) + return null; + return result.get(0); + } catch (SQLException e) { + throw new RuntimeException(e); + } + } + public void deleteNS(JSONObject json) { String _id = JsonHelper.safeGetString(json, "_id"); if (_id != null && !_id.isEmpty()) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java index 51c602bfd2..01ae2f9dcd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentsPlugin.java @@ -8,7 +8,6 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.firebase.analytics.FirebaseAnalytics; -import com.google.gson.GsonBuilder; import org.jetbrains.annotations.NotNull; @@ -31,7 +30,8 @@ import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.OverlappingIntervals; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.ProfileIntervals; -import info.nightscout.androidaps.data.ProfileStore; +import info.nightscout.androidaps.db.Treatment; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.db.ExtendedBolus; import info.nightscout.androidaps.db.ProfileSwitch; import info.nightscout.androidaps.db.Source; @@ -50,7 +50,7 @@ import info.nightscout.androidaps.interfaces.TreatmentsInterface; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; @@ -74,7 +74,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final ResourceHelper resourceHelper; private final ProfileFunction profileFunction; private final ActivePluginProvider activePlugin; + private final NSUpload nsUpload; private final FabricPrivacy fabricPrivacy; + private final DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -99,7 +101,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface SP sp, ProfileFunction profileFunction, ActivePluginProvider activePlugin, - FabricPrivacy fabricPrivacy + NSUpload nsUpload, + FabricPrivacy fabricPrivacy, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.TREATMENT) @@ -118,6 +122,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface this.profileFunction = profileFunction; this.activePlugin = activePlugin; this.fabricPrivacy = fabricPrivacy; + this.dateUtil = dateUtil; + this.nsUpload = nsUpload; } @Override @@ -171,7 +177,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface return this.service; } - private long range() { + protected long range() { double dia = Constants.defaultDIA; if (profileFunction.getProfile() != null) dia = profileFunction.getProfile().getDia(); @@ -267,7 +273,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface for (int pos = 0; pos < extendedBoluses.size(); pos++) { ExtendedBolus e = extendedBoluses.get(pos); if (e.date > time) continue; - IobTotal calc = e.iobCalc(time); + IobTotal calc = e.iobCalc(time, profile); total.plus(calc); } } @@ -289,7 +295,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface /** * Returns all Treatments after specified timestamp. Also returns invalid entries (required to - * map "Fill Canulla" entries to history (and not to add double bolus for it) + * map "Fill Canula" entries to history (and not to add double bolus for it) * * @param fromTimestamp * @return @@ -300,13 +306,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface long time = System.currentTimeMillis(); synchronized (treatments) { - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); +// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: AllTreatmentsInDb: " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(treatments)); for (Treatment t : treatments) { if (t.date <= time && t.date >= fromTimestamp) in5minback.add(t); } - getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); +// getAapsLogger().debug(MedtronicHistoryData.doubleBolusDebug, LTag.DATATREATMENTS, "DoubleBolusDebug: FilteredTreatments: AfterTime={}, Items={} " + fromTimestamp + " " + new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().toJson(in5minback)); return in5minback; } } @@ -328,35 +334,42 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface @Override public long getLastBolusTime() { - long now = System.currentTimeMillis(); - long last = 0; - synchronized (treatments) { - for (Treatment t : treatments) { - if (!t.isValid) - continue; - if (t.date > last && t.insulin > 0 && t.date <= now) - last = t.date; - } + Treatment last = getService().getLastBolus(false); + if (last == null) { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: NOTHING FOUND"); + return 0; + } + else { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + dateUtil.dateAndTimeString(last.date)); + return last.date; } - getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + DateUtil.dateAndTimeString(last)); - return last; } - public long getLastBolusTime(boolean isSMB) { - long now = System.currentTimeMillis(); - long last = 0; - synchronized (treatments) { - for (Treatment t : treatments) { - if (!t.isValid) - continue; - if (t.date > last && t.insulin > 0 && t.date <= now && isSMB == t.isSMB) - last = t.date; - } + public long getLastBolusTime(boolean excludeSMB) { + Treatment last = getService().getLastBolus(excludeSMB); + if (last == null) { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: NOTHING FOUND"); + return 0; + } + else { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + dateUtil.dateAndTimeString(last.date)); + return last.date; } - getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + DateUtil.dateAndTimeString(last)); - return last; } + public long getLastCarbTime() { + Treatment last = getService().getLastCarb(); + if (last == null) { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: NOTHING FOUND"); + return 0; + } + else { + getAapsLogger().debug(LTag.DATATREATMENTS, "Last Carb time: " + dateUtil.dateAndTimeString(last.date)); + return last.date; + } + } + + @Override public boolean isInHistoryRealTempBasalInProgress() { return getRealTempBasalFromHistory(System.currentTimeMillis()) != null; @@ -426,9 +439,9 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface ExtendedBolus dummyExt = new ExtendedBolus(getInjector()); dummyExt.copyFrom(e); dummyExt.cutEndTo(truncateTime); - calc = dummyExt.iobCalc(time); + calc = dummyExt.iobCalc(time, profile); } else { - calc = e.iobCalc(time); + calc = e.iobCalc(time, profile); } totalExt.plus(calc); } @@ -457,8 +470,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface Treatment treatment = new Treatment(getInjector()); treatment.date = i; treatment.insulin = running * 5.0 / 60.0; // 5 min chunk - Iob iob = treatment.iobCalc(i, profile.getDia()); - total.iob += iob.iobContrib; + Iob iob = treatment.iobCalc(time, profile.getDia()); + total.basaliob += iob.iobContrib; total.activity += iob.activityContrib; } return total; @@ -549,13 +562,13 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface if (newRecordCreated) { if (extendedBolus.durationInMinutes == 0) { if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); + nsUpload.uploadTempBasalEnd(extendedBolus.date, true, extendedBolus.pumpId); else - NSUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); + nsUpload.uploadExtendedBolusEnd(extendedBolus.date, extendedBolus.pumpId); } else if (activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) - NSUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); + nsUpload.uploadTempBasalStartAbsolute(new TemporaryBasal(extendedBolus), extendedBolus.insulin); else - NSUpload.uploadExtendedBolus(extendedBolus); + nsUpload.uploadExtendedBolus(extendedBolus); } return newRecordCreated; } @@ -582,15 +595,21 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface boolean newRecordCreated = MainApp.getDbHelper().createOrUpdate(tempBasal); if (newRecordCreated) { if (tempBasal.durationInMinutes == 0) - NSUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); + nsUpload.uploadTempBasalEnd(tempBasal.date, false, tempBasal.pumpId); else if (tempBasal.isAbsolute) - NSUpload.uploadTempBasalStartAbsolute(tempBasal, null); + nsUpload.uploadTempBasalStartAbsolute(tempBasal, null); else - NSUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); + nsUpload.uploadTempBasalStartPercent(tempBasal, profileFunction.getProfile(tempBasal.date)); } return newRecordCreated; } + public TreatmentUpdateReturn createOrUpdateMedtronic(Treatment treatment, boolean fromNightScout) { + TreatmentService.UpdateReturn resultRecord = getService().createOrUpdateMedtronic(treatment, fromNightScout); + + return new TreatmentUpdateReturn(resultRecord.success, resultRecord.newRecord); + } + // return true if new record is created @Override public boolean addToHistoryTreatment(DetailedBolusInfo detailedBolusInfo, boolean allowUpdate) { @@ -637,12 +656,12 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface //log.debug("Adding new Treatment record" + carbsTreatment); } if (newRecordCreated && detailedBolusInfo.isValid) - NSUpload.uploadTreatmentRecord(detailedBolusInfo); + nsUpload.uploadTreatmentRecord(detailedBolusInfo); if (!allowUpdate && !creatOrUpdateResult.success) { getAapsLogger().error("Treatment could not be added to DB", new Exception()); - String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, DateUtil.dateAndTimeString(treatment.date)); + String status = String.format(resourceHelper.gs(R.string.error_adding_treatment_message), treatment.insulin, (int) treatment.carbs, dateUtil.dateAndTimeString(treatment.date)); Intent i = new Intent(context, ErrorHelperActivity.class); i.putExtra("soundid", R.raw.error); @@ -706,7 +725,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface public void addToHistoryTempTarget(TempTarget tempTarget) { //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); MainApp.getDbHelper().createOrUpdate(tempTarget); - NSUpload.uploadTempTarget(tempTarget, profileFunction); + nsUpload.uploadTempTarget(tempTarget, profileFunction); } @Override @@ -729,7 +748,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface //log.debug("Adding new TemporaryBasal record" + profileSwitch.log()); rxBus.send(new EventDismissNotification(Notification.PROFILE_SWITCH_MISSING)); MainApp.getDbHelper().createOrUpdate(profileSwitch); - NSUpload.uploadProfileSwitch(profileSwitch); + nsUpload.uploadProfileSwitch(profileSwitch); } @Override diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/ProfileGraph.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/ProfileGraph.kt deleted file mode 100644 index a48f5e4118..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/ProfileGraph.kt +++ /dev/null @@ -1,38 +0,0 @@ -package info.nightscout.androidaps.plugins.treatments.fragments - -import android.content.Context -import android.util.AttributeSet -import com.jjoe64.graphview.GraphView -import com.jjoe64.graphview.series.DataPoint -import com.jjoe64.graphview.series.LineGraphSeries -import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.utils.Round -import java.util.* - -class ProfileGraph : GraphView { - - constructor(context: Context?) : super(context) - constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) - - fun show(profile: Profile) { - removeAllSeries() - val basalArray: MutableList = ArrayList() - for (hour in 0..23) { - basalArray.add(DataPoint(hour.toDouble(), profile.getBasalTimeFromMidnight(hour * 60 * 60))) - basalArray.add(DataPoint((hour + 1).toDouble(), profile.getBasalTimeFromMidnight(hour * 60 * 60))) - } - val basalDataPoints: Array = Array(basalArray.size){ i-> basalArray[i]} - val basalSeries: LineGraphSeries = LineGraphSeries(basalDataPoints) - addSeries(basalSeries) - basalSeries.thickness = 8 - basalSeries.isDrawBackground = true - viewport.isXAxisBoundsManual = true - viewport.setMinX(0.0) - viewport.setMaxX(24.0) - viewport.isYAxisBoundsManual = true - viewport.setMinY(0.0) - viewport.setMaxY(Round.ceilTo(profile.maxDailyBasal * 1.1, 0.5)) - gridLabelRenderer.numHorizontalLabels = 13 - gridLabelRenderer.verticalLabelsColor = basalSeries.color - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt index 7e130ceab9..e6d2f02883 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsBolusFragment.kt @@ -14,12 +14,12 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.events.EventTreatmentChange import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.dialogs.WizardInfoDialog import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsBolusFragment.RecyclerViewAdapter.TreatmentsViewHolder @@ -42,6 +42,9 @@ class TreatmentsBolusFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -67,9 +70,9 @@ class TreatmentsBolusFragment : DaggerFragment() { val futureTreatments = treatmentsPlugin.service.getTreatmentDataFromTime(DateUtil.now() + 1000, true) for (treatment in futureTreatments) { if (NSUpload.isIdValid(treatment._id)) - NSUpload.removeCareportalEntryFromNS(treatment._id) + nsUpload.removeCareportalEntryFromNS(treatment._id) else - UploadQueue.removeID("dbAdd", treatment._id) + uploadQueue.removeID("dbAdd", treatment._id) treatmentsPlugin.service.delete(treatment) } updateGui() @@ -109,7 +112,7 @@ class TreatmentsBolusFragment : DaggerFragment() { override fun onBindViewHolder(holder: TreatmentsViewHolder, position: Int) { val profile = profileFunction.getProfile() ?: return val t = treatments[position] - holder.date.text = DateUtil.dateAndTimeString(t.date) + holder.date.text = dateUtil.dateAndTimeString(t.date) holder.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, t.insulin) holder.carbs.text = resourceHelper.gs(R.string.format_carbs, t.carbs.toInt()) val iob = t.iobCalc(System.currentTimeMillis(), profile.dia) @@ -158,16 +161,16 @@ class TreatmentsBolusFragment : DaggerFragment() { val text = resourceHelper.gs(R.string.configbuilder_insulin) + ": " + resourceHelper.gs(R.string.formatinsulinunits, treatment.insulin) + "\n" + resourceHelper.gs(R.string.carbs) + ": " + resourceHelper.gs(R.string.format_carbs, treatment.carbs.toInt()) + "\n" + - resourceHelper.gs(R.string.date) + ": " + DateUtil.dateAndTimeString(treatment.date) + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(treatment.date) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { if (treatment.source == Source.PUMP) { treatment.isValid = false treatmentsPlugin.service.update(treatment) } else { if (NSUpload.isIdValid(treatment._id)) - NSUpload.removeCareportalEntryFromNS(treatment._id) + nsUpload.removeCareportalEntryFromNS(treatment._id) else - UploadQueue.removeID("dbAdd", treatment._id) + uploadQueue.removeID("dbAdd", treatment._id) treatmentsPlugin.service.delete(treatment) } updateGui() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt index d7a5e99496..26165ec661 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsCareportalFragment.kt @@ -38,6 +38,9 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -65,9 +68,9 @@ class TreatmentsCareportalFragment : DaggerFragment() { val careportalEvent = events[i] if (careportalEvent.json.contains(resourceHelper.gs(R.string.androidaps_start))) { if (NSUpload.isIdValid(careportalEvent._id)) - NSUpload.removeCareportalEntryFromNS(careportalEvent._id) + nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else - UploadQueue.removeID("dbAdd", careportalEvent._id) + uploadQueue.removeID("dbAdd", careportalEvent._id) MainApp.getDbHelper().delete(careportalEvent) } } @@ -106,7 +109,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { override fun onBindViewHolder(holder: CareportalEventsViewHolder, position: Int) { val careportalEvent = careportalEventList[position] holder.ns.visibility = if (NSUpload.isIdValid(careportalEvent._id)) View.VISIBLE else View.GONE - holder.date.text = DateUtil.dateAndTimeString(careportalEvent.date) + holder.date.text = dateUtil.dateAndTimeString(careportalEvent.date) holder.duration.text = if (careportalEvent.durationInMsec() == 0L) "" else DateUtil.niceTimeScalar(careportalEvent.durationInMsec(), resourceHelper) holder.note.text = careportalEvent.notes holder.type.text = translator.translate(careportalEvent.eventType) @@ -130,14 +133,14 @@ class TreatmentsCareportalFragment : DaggerFragment() { remove.setOnClickListener { v: View -> val careportalEvent = v.tag as CareportalEvent activity?.let { activity -> - val text = resourceHelper.gs(R.string.careportal_newnstreatment_eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + + val text = resourceHelper.gs(R.string.eventtype) + ": " + translator.translate(careportalEvent.eventType) + "\n" + resourceHelper.gs(R.string.careportal_newnstreatment_notes_label) + ": " + careportalEvent.notes + "\n" + - resourceHelper.gs(R.string.date) + ": " + DateUtil.dateAndTimeString(careportalEvent.date) + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(careportalEvent.date) OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), text, Runnable { if (NSUpload.isIdValid(careportalEvent._id)) - NSUpload.removeCareportalEntryFromNS(careportalEvent._id) + nsUpload.removeCareportalEntryFromNS(careportalEvent._id) else - UploadQueue.removeID("dbAdd", careportalEvent._id) + uploadQueue.removeID("dbAdd", careportalEvent._id) MainApp.getDbHelper().delete(careportalEvent) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt index 8ce87e6b5e..f502d0f317 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsExtendedBolusesFragment.kt @@ -19,6 +19,7 @@ import info.nightscout.androidaps.db.ExtendedBolus import info.nightscout.androidaps.db.Source import info.nightscout.androidaps.events.EventExtendedBolusChange import info.nightscout.androidaps.interfaces.ActivePluginProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue @@ -40,6 +41,10 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -63,7 +68,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { holder.ph.visibility = if (extendedBolus.source == Source.PUMP) View.VISIBLE else View.GONE holder.ns.visibility = if (NSUpload.isIdValid(extendedBolus._id)) View.VISIBLE else View.GONE if (extendedBolus.isEndingEvent) { - holder.date.text = DateUtil.dateAndTimeString(extendedBolus.date) + holder.date.text = dateUtil.dateAndTimeString(extendedBolus.date) holder.duration.text = resourceHelper.gs(R.string.cancel) holder.insulin.text = "" holder.realDuration.text = "" @@ -72,18 +77,18 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { holder.ratio.text = "" } else { @SuppressLint("SetTextI18n") - if (extendedBolus.isInProgress) holder.date.text = DateUtil.dateAndTimeString(extendedBolus.date) - else holder.date.text = DateUtil.dateAndTimeString(extendedBolus.date) + " - " + DateUtil.timeString(extendedBolus.end()) - + if (extendedBolus.isInProgress) holder.date.text = dateUtil.dateAndTimeString(extendedBolus.date) + else holder.date.text = dateUtil.dateAndTimeString(extendedBolus.date) + " - " + dateUtil.timeString(extendedBolus.end()) + val profile = profileFunction.getProfile(extendedBolus.date) holder.duration.text = resourceHelper.gs(R.string.format_mins, extendedBolus.durationInMinutes) holder.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.insulin) holder.realDuration.text = resourceHelper.gs(R.string.format_mins, extendedBolus.realDuration) - val iob = extendedBolus.iobCalc(System.currentTimeMillis()) + val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile) holder.iob.text = resourceHelper.gs(R.string.formatinsulinunits, iob.iob) holder.insulinSoFar.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.insulinSoFar()) holder.ratio.text = resourceHelper.gs(R.string.pump_basebasalrate, extendedBolus.absoluteRate()) if (extendedBolus.isInProgress) holder.date.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.date.setTextColor(holder.insulin.currentTextColor) - if (extendedBolus.iobCalc(System.currentTimeMillis()).iob != 0.0) holder.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.iob.setTextColor(holder.insulin.currentTextColor) + if (iob.iob != 0.0) holder.iob.setTextColor(resourceHelper.gc(R.color.colorActive)) else holder.iob.setTextColor(holder.insulin.currentTextColor) } holder.remove.tag = extendedBolus } @@ -112,11 +117,11 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { showConfirmation(it, resourceHelper.gs(R.string.removerecord), """ ${resourceHelper.gs(R.string.extended_bolus)} - ${resourceHelper.gs(R.string.date)}: ${DateUtil.dateAndTimeString(extendedBolus.date)} + ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(extendedBolus.date)} """.trimIndent(), DialogInterface.OnClickListener { _: DialogInterface, _: Int -> val id = extendedBolus._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(extendedBolus) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt index d45d547ef0..29e31e544d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsProfileSwitchFragment.kt @@ -6,7 +6,6 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView -import androidx.cardview.widget.CardView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import dagger.android.support.DaggerFragment @@ -25,11 +24,11 @@ import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfile import info.nightscout.androidaps.plugins.treatments.fragments.TreatmentsProfileSwitchFragment.RecyclerProfileViewAdapter.ProfileSwitchViewHolder import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.T +import info.nightscout.androidaps.utils.alertDialogs.OKDialog +import info.nightscout.androidaps.utils.extensions.toVisibility import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import info.nightscout.androidaps.utils.extensions.toVisibility import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.treatments_profileswitch_fragment.* @@ -43,6 +42,9 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -95,7 +97,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { val profileSwitch = profileSwitchList[position] holder.ph.visibility = (profileSwitch.source == Source.PUMP).toVisibility() holder.ns.visibility = NSUpload.isIdValid(profileSwitch._id).toVisibility() - holder.date.text = DateUtil.dateAndTimeString(profileSwitch.date) + holder.date.text = dateUtil.dateAndTimeString(profileSwitch.date) if (!profileSwitch.isEndingEvent) { holder.duration.text = resourceHelper.gs(R.string.format_mins, profileSwitch.durationInMinutes) } else { @@ -115,7 +117,6 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { } inner class ProfileSwitchViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { - var cv: CardView = itemView.findViewById(R.id.profileswitch_cardview) as CardView var date: TextView = itemView.findViewById(R.id.profileswitch_date) as TextView var duration: TextView = itemView.findViewById(R.id.profileswitch_duration) as TextView var name: TextView = itemView.findViewById(R.id.profileswitch_name) as TextView @@ -132,19 +133,19 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { activity?.let { activity -> OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.removerecord), resourceHelper.gs(R.string.careportal_profileswitch) + ": " + profileSwitch.profileName + - "\n" + resourceHelper.gs(R.string.date) + ": " + DateUtil.dateAndTimeString(profileSwitch.date), Runnable { + "\n" + resourceHelper.gs(R.string.date) + ": " + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { val id = profileSwitch._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(profileSwitch) }) } R.id.profileswitch_clone -> activity?.let { activity -> - OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.customizedName + "\n" + DateUtil.dateAndTimeString(profileSwitch.date), Runnable { + OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.careportal_profileswitch), resourceHelper.gs(R.string.copytolocalprofile) + "\n" + profileSwitch.customizedName + "\n" + dateUtil.dateAndTimeString(profileSwitch.date), Runnable { profileSwitch.profileObject?.let { val nonCustomized = it.convertToNonCustomizedProfile() - localProfilePlugin.addProfile(LocalProfilePlugin.SingleProfile().copyFrom(localProfilePlugin.rawProfile, nonCustomized, profileSwitch.customizedName + " " + DateUtil.dateAndTimeString(profileSwitch.date).replace(".", "_"))) + localProfilePlugin.addProfile(localProfilePlugin.copyFrom(nonCustomized, profileSwitch.customizedName + " " + dateUtil.dateAndTimeString(profileSwitch.date).replace(".", "_"))) rxBus.send(EventLocalProfileChanged()) } }) @@ -153,7 +154,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { R.id.profileswitch_date, R.id.profileswitch_name -> { val args = Bundle() args.putLong("time", (v.tag as ProfileSwitch).date) - args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) + args.putInt("mode", ProfileViewerDialog.Mode.DB_PROFILE.ordinal) val pvd = ProfileViewerDialog() pvd.arguments = args pvd.show(childFragmentManager, "ProfileViewDialog") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java index 1d95d4306b..980e9efe7d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTempTargetFragment.java @@ -23,7 +23,7 @@ import info.nightscout.androidaps.db.Source; import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.events.EventTempTargetChange; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientRestart; @@ -47,7 +47,10 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { @Inject RxBusWrapper rxBus; @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; + @Inject NSUpload nsUpload; + @Inject UploadQueue uploadQueue; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -77,13 +80,13 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { holder.ph.setVisibility(tempTarget.source == Source.PUMP ? View.VISIBLE : View.GONE); holder.ns.setVisibility(NSUpload.isIdValid(tempTarget._id) ? View.VISIBLE : View.GONE); if (!tempTarget.isEndingEvent()) { - holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date) + " - " + DateUtil.timeString(tempTarget.originalEnd())); + holder.date.setText(dateUtil.dateAndTimeString(tempTarget.date) + " - " + dateUtil.timeString(tempTarget.originalEnd())); holder.duration.setText(DecimalFormatter.to0Decimal(tempTarget.durationInMinutes) + " min"); holder.low.setText(tempTarget.lowValueToUnitsToString(units)); holder.high.setText(tempTarget.highValueToUnitsToString(units)); holder.reason.setText(tempTarget.reason); } else { - holder.date.setText(DateUtil.dateAndTimeString(tempTarget.date)); + holder.date.setText(dateUtil.dateAndTimeString(tempTarget.date)); holder.duration.setText(R.string.cancel); holder.low.setText(""); holder.high.setText(""); @@ -141,13 +144,13 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { final TempTarget tempTarget = (TempTarget) v.getTag(); OKDialog.showConfirmation(getContext(), resourceHelper.gs(R.string.removerecord), resourceHelper.gs(R.string.careportal_temporarytarget) + ": " + tempTarget.friendlyDescription(profileFunction.getUnits(), resourceHelper) + - "\n" + DateUtil.dateAndTimeString(tempTarget.date), + "\n" + dateUtil.dateAndTimeString(tempTarget.date), (dialog, id) -> { final String _id = tempTarget._id; if (NSUpload.isIdValid(_id)) { - NSUpload.removeCareportalEntryFromNS(_id); + nsUpload.removeCareportalEntryFromNS(_id); } else { - UploadQueue.removeID("dbAdd", _id); + uploadQueue.removeID("dbAdd", _id); } MainApp.getDbHelper().delete(tempTarget); }, null); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt index d863754d07..fed0ba1137 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.db.TemporaryBasal import info.nightscout.androidaps.events.EventTempBasalChange import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.nsclient.UploadQueue import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished @@ -44,6 +44,9 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var uploadQueue: UploadQueue + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -88,7 +91,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { holder.ph.visibility = if (tempBasal.source == Source.PUMP) View.VISIBLE else View.GONE holder.ns.visibility = if (NSUpload.isIdValid(tempBasal._id)) View.VISIBLE else View.GONE if (tempBasal.isEndingEvent) { - holder.date.text = DateUtil.dateAndTimeString(tempBasal.date) + holder.date.text = dateUtil.dateAndTimeString(tempBasal.date) holder.duration.text = resourceHelper.gs(R.string.cancel) holder.absolute.text = "" holder.percent.text = "" @@ -100,10 +103,10 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { holder.iob.setTextColor(holder.netRatio.currentTextColor) } else { if (tempBasal.isInProgress) { - holder.date.text = DateUtil.dateAndTimeString(tempBasal.date) + holder.date.text = dateUtil.dateAndTimeString(tempBasal.date) holder.date.setTextColor(resourceHelper.gc(R.color.colorActive)) } else { - holder.date.text = DateUtil.dateAndTimeRangeString(tempBasal.date, tempBasal.end()) + holder.date.text = dateUtil.dateAndTimeRangeString(tempBasal.date, tempBasal.end()) holder.date.setTextColor(holder.netRatio.currentTextColor) } holder.duration.text = resourceHelper.gs(R.string.format_mins, tempBasal.durationInMinutes) @@ -159,13 +162,13 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { context?.let { showConfirmation(it, resourceHelper.gs(R.string.removerecord), """ - ${resourceHelper.gs(R.string.pump_tempbasal_label)}: ${tempBasal.toStringFull()} - ${resourceHelper.gs(R.string.date)}: ${DateUtil.dateAndTimeString(tempBasal.date)} + ${resourceHelper.gs(R.string.tempbasal_label)}: ${tempBasal.toStringFull()} + ${resourceHelper.gs(R.string.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)} """.trimIndent(), DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> val id = tempBasal._id - if (NSUpload.isIdValid(id)) NSUpload.removeCareportalEntryFromNS(id) - else UploadQueue.removeID("dbAdd", id) + if (NSUpload.isIdValid(id)) nsUpload.removeCareportalEntryFromNS(id) + else uploadQueue.removeID("dbAdd", id) MainApp.getDbHelper().delete(tempBasal) }, null) } diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt index fd93f772aa..bbc541c7b9 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueue.kt @@ -24,11 +24,12 @@ import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification +import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.queue.commands.* import info.nightscout.androidaps.queue.commands.Command.CommandType import info.nightscout.androidaps.utils.FabricPrivacy @@ -374,12 +375,14 @@ class CommandQueue @Inject constructor( callback?.result(PumpEnactResult(injector).success(true).enacted(false))?.run() return false } + /* this is breaking setting of profile at all if not engineering mode if (!buildHelper.isEngineeringModeOrRelease()) { val notification = Notification(Notification.NOT_ENG_MODE_OR_RELEASE, resourceHelper.gs(R.string.not_eng_mode_or_release), Notification.URGENT) rxBus.send(EventNewNotification(notification)) callback?.result(PumpEnactResult(injector).success(false).enacted(false).comment(resourceHelper.gs(R.string.not_eng_mode_or_release)))?.run() return false } + */ // Compare with pump limits val basalValues = profile.basalValues for (basalValue in basalValues) { diff --git a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt index a52a23bd09..f18ae1db9f 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/commands/CommandSMBBolus.kt @@ -17,6 +17,7 @@ class CommandSMBBolus( callback: Callback? ) : Command(injector, CommandType.SMB_BOLUS, callback) { + @Inject lateinit var dateUtil: DateUtil @Inject lateinit var activePlugin: ActivePluginProvider override fun execute() { @@ -29,7 +30,7 @@ class CommandSMBBolus( r = activePlugin.activePump.deliverTreatment(detailedBolusInfo) } else { r = PumpEnactResult(injector).enacted(false).success(false).comment("SMB request too old") - aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + DateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)) + aapsLogger.debug(LTag.PUMPQUEUE, "SMB bolus canceled. deliverAt: " + dateUtil.dateAndTimeString(detailedBolusInfo.deliverAt)) } aapsLogger.debug(LTag.PUMPQUEUE, "Result success: ${r.success} enacted: ${r.enacted}") callback?.result(r)?.run() diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt index 2c99b1e4f1..bd532dc462 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -8,15 +8,16 @@ import android.content.Intent import android.os.PowerManager import android.os.SystemClock import dagger.android.DaggerBroadcastReceiver +import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.Config import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.commands.Command @@ -38,12 +39,14 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { @Inject lateinit var localAlertUtils: LocalAlertUtils @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var receiverStatusStore: ReceiverStatusStore - + @Inject lateinit var config: Config + @Inject lateinit var nsUpload: NSUpload + @Inject lateinit var dateUtil: DateUtil companion object { private val KEEP_ALIVE_MILLISECONDS = T.mins(5).msecs() private val STATUS_UPDATE_FREQUENCY = T.mins(15).msecs() - private val IOB_UPDATE_FREQUENCY = T.mins(5).msecs() + private val IOB_UPDATE_FREQUENCY_IN_MINS = 5L private var lastReadStatus: Long = 0 private var lastRun: Long = 0 @@ -100,14 +103,14 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { // IOB displayed in NS private fun checkAPS() { var shouldUploadStatus = false - if (Config.NSCLIENT) return - if (Config.PUMPCONTROL) shouldUploadStatus = true + if (config.NSCLIENT) return + if (config.PUMPCONTROL) shouldUploadStatus = true else if (!loopPlugin.isEnabled() || iobCobCalculatorPlugin.actualBg() == null) shouldUploadStatus = true else if (DateUtil.isOlderThan(activePlugin.activeAPS.lastAPSRun, 5)) shouldUploadStatus = true - if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY) && shouldUploadStatus) { + if (DateUtil.isOlderThan(lastIobUpload, IOB_UPDATE_FREQUENCY_IN_MINS) && shouldUploadStatus) { lastIobUpload = DateUtil.now() - NSUpload.uploadDeviceStatus(loopPlugin, iobCobCalculatorPlugin, profileFunction, activePlugin.activePump, receiverStatusStore) + nsUpload.uploadDeviceStatus(loopPlugin, iobCobCalculatorPlugin, profileFunction, activePlugin.activePump, receiverStatusStore, BuildConfig.VERSION_NAME + "-" + BuildConfig.BUILDVERSION) } } @@ -117,7 +120,7 @@ class KeepAliveReceiver : DaggerBroadcastReceiver() { val lastConnection = pump.lastDataTime() val isStatusOutdated = lastConnection + STATUS_UPDATE_FREQUENCY < System.currentTimeMillis() val isBasalOutdated = abs(profile.basal - pump.baseBasalRate) > pump.pumpDescription.basalStep - aapsLogger.debug(LTag.CORE, "Last connection: " + DateUtil.dateAndTimeString(lastConnection)) + aapsLogger.debug(LTag.CORE, "Last connection: " + dateUtil.dateAndTimeString(lastConnection)) // sometimes keep alive broadcast stops // as as workaround test if readStatus was requested before an alarm is generated if (lastReadStatus != 0L && lastReadStatus > System.currentTimeMillis() - T.mins(5).msecs()) { diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/TimeDateOrTZChangeReceiver.kt b/app/src/main/java/info/nightscout/androidaps/receivers/TimeDateOrTZChangeReceiver.kt index 916239ae82..de7249b938 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/TimeDateOrTZChangeReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/TimeDateOrTZChangeReceiver.kt @@ -7,6 +7,7 @@ import dagger.android.DaggerBroadcastReceiver import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.PumpInterface import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.logging.BundleLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.utils.TimeChangeType import java.util.* @@ -38,33 +39,39 @@ class TimeDateOrTZChangeReceiver : DaggerBroadcastReceiver() { val action = intent.action val activePump: PumpInterface = activePlugin.activePump - aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Date, Time and/or TimeZone changed. [action={}]", action) - aapsLogger.debug(LTag.PUMP,"TimeDateOrTZChangeReceiver::Intent::{}", gson.toJson(intent)) + aapsLogger.debug(LTag.PUMP, "TimeDateOrTZChangeReceiver::Date, Time and/or TimeZone changed. [action={}]", action) + aapsLogger.debug(LTag.PUMP, "TimeDateOrTZChangeReceiver::Intent::{}", BundleLogger.log(intent.extras)) - if (action == null) { - aapsLogger.error(LTag.PUMP,"TimeDateOrTZChangeReceiver::Action is null. Exiting.") - } else if (Intent.ACTION_TIMEZONE_CHANGED == action) { - aapsLogger.info(LTag.PUMP,"TimeDateOrTZChangeReceiver::Timezone changed. Notifying pump driver.") - activePump.timezoneOrDSTChanged(TimeChangeType.TimezoneChange) - } else if (Intent.ACTION_TIME_CHANGED == action) { - val currentDst = calculateDST() - if (currentDst == isDST) { - aapsLogger.info(LTag.PUMP,"TimeDateOrTZChangeReceiver::Time changed (manual). Notifying pump driver.") - activePump.timezoneOrDSTChanged(TimeChangeType.ManualTimeChange) - } else { - if (currentDst) { - aapsLogger.info(LTag.PUMP,"TimeDateOrTZChangeReceiver::DST started. Notifying pump driver.") - activePump.timezoneOrDSTChanged(TimeChangeType.DST_Started) - } else { - aapsLogger.info(LTag.PUMP,"TimeDateOrTZChangeReceiver::DST ended. Notifying pump driver.") - activePump.timezoneOrDSTChanged(TimeChangeType.DST_Ended) - } + when { + action == null -> { + aapsLogger.error(LTag.PUMP, "TimeDateOrTZChangeReceiver::Action is null. Exiting.") + } + + Intent.ACTION_TIMEZONE_CHANGED == action -> { + aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::Timezone changed. Notifying pump driver.") + activePump.timezoneOrDSTChanged(TimeChangeType.TimezoneChange) + } + + Intent.ACTION_TIME_CHANGED == action -> { + val currentDst = calculateDST() + if (currentDst == isDST) { + aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::Time changed (manual). Notifying pump driver.") + activePump.timezoneOrDSTChanged(TimeChangeType.ManualTimeChange) + } else { + if (currentDst) { + aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::DST started. Notifying pump driver.") + activePump.timezoneOrDSTChanged(TimeChangeType.DST_Started) + } else { + aapsLogger.info(LTag.PUMP, "TimeDateOrTZChangeReceiver::DST ended. Notifying pump driver.") + activePump.timezoneOrDSTChanged(TimeChangeType.DST_Ended) + } + } + isDST = currentDst + } + + else -> { + aapsLogger.error(LTag.PUMP, "TimeDateOrTZChangeReceiver::Unknown action received [name={}]. Exiting.", action) } - isDST = currentDst - } else { - aapsLogger.error(LTag.PUMP,"TimeDateOrTZChangeReceiver::Unknown action received [name={}]. Exiting.", action) } } - - } diff --git a/app/src/main/java/info/nightscout/androidaps/services/DataService.java b/app/src/main/java/info/nightscout/androidaps/services/DataService.java index 83891275a2..26814a7644 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/DataService.java +++ b/app/src/main/java/info/nightscout/androidaps/services/DataService.java @@ -11,6 +11,7 @@ import org.json.JSONObject; import javax.inject.Inject; import dagger.android.DaggerIntentService; +import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.db.CareportalEvent; @@ -20,6 +21,7 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.BundleLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.notifications.Notification; @@ -42,6 +44,7 @@ public class DataService extends DaggerIntentService { @Inject AAPSLogger aapsLogger; @Inject SP sp; @Inject RxBusWrapper rxBus; + @Inject NSUpload nsUpload; @Inject SmsCommunicatorPlugin smsCommunicatorPlugin; @Inject DexcomPlugin dexcomPlugin; @Inject EversensePlugin eversensePlugin; @@ -53,6 +56,7 @@ public class DataService extends DaggerIntentService { @Inject XdripPlugin xdripPlugin; @Inject NSProfilePlugin nsProfilePlugin; @Inject ActivePluginProvider activePlugin; + @Inject Config config; public DataService() { super("DataService"); @@ -66,7 +70,6 @@ public class DataService extends DaggerIntentService { boolean acceptNSData = !sp.getBoolean(R.string.key_ns_upload_only, false); - Bundle bundles = intent.getExtras(); final String action = intent.getAction(); if (Intents.ACTION_NEW_BG_ESTIMATE.equals(action)) { @@ -210,7 +213,7 @@ public class DataService extends DaggerIntentService { } else if (eventType.equals(CareportalEvent.COMBOBOLUS)) { MainApp.getDbHelper().createExtendedBolusFromJsonIfNotExists(json); } else if (eventType.equals(CareportalEvent.PROFILESWITCH)) { - MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePlugin, json); + MainApp.getDbHelper().createProfileSwitchFromJsonIfNotExists(activePlugin, nsUpload, json); } else if (eventType.equals(CareportalEvent.SITECHANGE) || eventType.equals(CareportalEvent.INSULINCHANGE) || eventType.equals(CareportalEvent.SENSORCHANGE) || @@ -232,8 +235,11 @@ public class DataService extends DaggerIntentService { String notes = JsonHelper.safeGetString(json, "notes", ""); if (date > now - 15 * 60 * 1000L && !notes.isEmpty() && !enteredBy.equals(sp.getString("careportal_enteredby", "AndroidAPS"))) { - Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); - rxBus.send(new EventNewNotification(announcement)); + boolean defaultVal = config.getNSCLIENT(); + if (sp.getBoolean(R.string.key_ns_announcements, defaultVal)) { + Notification announcement = new Notification(Notification.NSANNOUNCEMENT, notes, Notification.ANNOUNCEMENT, 60); + rxBus.send(new EventNewNotification(announcement)); + } } } } diff --git a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt index 35374b47d7..2357dcebeb 100644 --- a/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt +++ b/app/src/main/java/info/nightscout/androidaps/services/LocationService.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.services import android.Manifest +import android.app.Notification import android.app.Service import android.content.Context import android.content.Intent @@ -71,19 +72,29 @@ class LocationService : DaggerService() { } } - override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) - startForeground(notificationHolder.notificationID, notificationHolder.notification) + try { + startForeground(notificationHolder.notificationID, notificationHolder.notification) + } catch (e: Exception) { + startForeground(4711, Notification()) + } return Service.START_STICKY } override fun onCreate() { super.onCreate() - startForeground(notificationHolder.notificationID, notificationHolder.notification) + try { + startForeground(notificationHolder.notificationID, notificationHolder.notification) + } catch (e: Exception) { + startForeground(4711, Notification()) + } // Get last location once until we get regular update - LocationServices.getFusedLocationProviderClient(this).lastLocation.addOnSuccessListener { - lastLocationDataContainer.lastLocation = it + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { + LocationServices.getFusedLocationProviderClient(this).lastLocation.addOnSuccessListener { + lastLocationDataContainer.lastLocation = it + } } initializeLocationManager() diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt index 5fca6651da..73cd2d6e37 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesFragment import info.nightscout.androidaps.plugins.constraints.objectives.ObjectivesPlugin import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs @@ -34,7 +34,7 @@ import info.nightscout.androidaps.setupwizard.elements.* import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.CryptoUtil -import info.nightscout.androidaps.utils.LocaleHelper.update +import info.nightscout.androidaps.utils.locale.LocaleHelper.update import info.nightscout.androidaps.utils.extensions.isRunningTest import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.resources.ResourceHelper @@ -62,7 +62,8 @@ class SWDefinition @Inject constructor( private val protectionCheck: ProtectionCheck, private val importExportPrefs: ImportExportPrefs, private val androidPermission: AndroidPermission, - private val cryptoUtil: CryptoUtil + private val cryptoUtil: CryptoUtil, + private val config: Config ) { lateinit var activity: AppCompatActivity @@ -339,7 +340,7 @@ class SWDefinition @Inject constructor( }, null) }) .visibility(SWValidator { (activePlugin.activeAPS as PluginBase).preferencesId > 0 })) - .visibility(SWValidator { Config.APS }) + .visibility(SWValidator { config.APS }) private val screenApsMode = SWScreen(injector, R.string.apsmode_title) .skippable(false) .add(SWRadioButton(injector) @@ -364,7 +365,7 @@ class SWDefinition @Inject constructor( }) .visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) })) .validator(SWValidator { loopPlugin.isEnabled(PluginType.LOOP) }) - .visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) && Config.APS }) + .visibility(SWValidator { !loopPlugin.isEnabled(PluginType.LOOP) && config.APS }) private val screenSensitivity = SWScreen(injector, R.string.configbuilder_sensitivity) .skippable(false) .add(SWInfotext(injector) @@ -395,7 +396,7 @@ class SWDefinition @Inject constructor( .add(SWFragment(injector, this) .add(ObjectivesFragment())) .validator(SWValidator { objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted }) - .visibility(SWValidator { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && Config.APS }) + .visibility(SWValidator { !objectivesPlugin.objectives[ObjectivesPlugin.FIRST_OBJECTIVE].isStarted && config.APS }) private fun swDefinitionFull() { // List all the screens here add(screenSetupWizard) @@ -460,7 +461,7 @@ class SWDefinition @Inject constructor( .add(screenUnits) .add(displaySettings) .add(screenNsClient) - .add(screenBgSource) + //.add(screenBgSource) .add(screenPatientName) .add(screenAge) .add(screenInsulin) @@ -468,6 +469,6 @@ class SWDefinition @Inject constructor( } init { - if (Config.APS) swDefinitionFull() else if (Config.PUMPCONTROL) swDefinitionPumpControl() else if (Config.NSCLIENT) swDefinitionNSClient() + if (config.APS) swDefinitionFull() else if (config.PUMPCONTROL) swDefinitionPumpControl() else if (config.NSCLIENT) swDefinitionNSClient() } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt index b265af0d4c..44af0e1312 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SetupWizardActivity.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.setupwizard.elements.SWItem import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.LocaleHelper.update +import info.nightscout.androidaps.utils.locale.LocaleHelper.update import info.nightscout.androidaps.utils.alertDialogs.OKDialog.show import info.nightscout.androidaps.utils.alertDialogs.OKDialog.showConfirmation import info.nightscout.androidaps.utils.resources.ResourceHelper diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.kt index 80ed784fff..2d49eb3a97 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.kt @@ -9,9 +9,9 @@ import android.widget.TextView import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.setupwizard.SWNumberValidator -import info.nightscout.androidaps.utils.NumberPicker +import info.nightscout.androidaps.utils.ui.NumberPicker import info.nightscout.androidaps.utils.SafeParse import java.text.DecimalFormat import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt index 3bc092dfc2..9584ce2f4b 100644 --- a/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt @@ -6,14 +6,16 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class SkinButtonsOn @Inject constructor() : SkinInterface { +class SkinButtonsOn @Inject constructor(private val config: Config) : SkinInterface { - override val description: Int get() = R.string.buttonson_desrciption + override val description: Int get() = R.string.buttonson_description + override val mainGraphHeight: Int get() = 200 + override val secondaryGraphHeight: Int get() = 100 override fun overviewLayout(isLandscape: Boolean, isTablet: Boolean, isSmallHeight: Boolean): Int = when { - Config.NSCLIENT && isTablet -> R.layout.overview_fragment_nsclient_tablet - Config.NSCLIENT -> R.layout.overview_fragment_nsclient + config.NSCLIENT && isTablet -> R.layout.overview_fragment_nsclient_tablet + config.NSCLIENT -> R.layout.overview_fragment_nsclient else -> R.layout.overview_fragment } diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt index 15e69e9ad9..9388843db8 100644 --- a/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt @@ -6,14 +6,16 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class SkinClassic @Inject constructor(): SkinInterface { +class SkinClassic @Inject constructor(private val config: Config): SkinInterface { - override val description: Int get() = R.string.classic_desrciption + override val description: Int get() = R.string.classic_description + override val mainGraphHeight: Int get() = 200 + override val secondaryGraphHeight: Int get() = 100 override fun overviewLayout(isLandscape: Boolean, isTablet: Boolean, isSmallHeight: Boolean): Int = when { - Config.NSCLIENT && isTablet -> R.layout.overview_fragment_nsclient_tablet - Config.NSCLIENT -> R.layout.overview_fragment_nsclient + config.NSCLIENT && isTablet -> R.layout.overview_fragment_nsclient_tablet + config.NSCLIENT -> R.layout.overview_fragment_nsclient isSmallHeight || isLandscape -> R.layout.overview_fragment_landscape else -> R.layout.overview_fragment } diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt index 6a9d055a13..73c047d100 100644 --- a/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt @@ -6,5 +6,7 @@ import androidx.annotation.StringRes interface SkinInterface { @get:StringRes val description : Int + val mainGraphHeight : Int // in dp + val secondaryGraphHeight : Int // in dp @LayoutRes fun overviewLayout(isLandscape : Boolean, isTablet : Boolean, isSmallHeight : Boolean): Int } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinLargeDisplay.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinLargeDisplay.kt new file mode 100644 index 0000000000..b28a0e3e0a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinLargeDisplay.kt @@ -0,0 +1,23 @@ +package info.nightscout.androidaps.skins + +import info.nightscout.androidaps.Config +import info.nightscout.androidaps.R +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SkinLargeDisplay @Inject constructor(private val config: Config): SkinInterface { + + override val description: Int get() = R.string.largedisplay_description + override val mainGraphHeight: Int get() = 400 + override val secondaryGraphHeight: Int get() = 150 + + override fun overviewLayout(isLandscape: Boolean, isTablet: Boolean, isSmallHeight: Boolean): Int = + when { + config.NSCLIENT && isTablet -> R.layout.overview_fragment_nsclient_tablet + config.NSCLIENT -> R.layout.overview_fragment_nsclient + isSmallHeight || isLandscape -> R.layout.overview_fragment_landscape + else -> R.layout.overview_fragment + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt b/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt index 01cc925942..e78b112615 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/CryptoUtil.kt @@ -1,6 +1,7 @@ package info.nightscout.androidaps.utils import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.utils.extensions.toHex import org.spongycastle.util.encoders.Base64 import java.nio.ByteBuffer import java.security.MessageDigest @@ -16,42 +17,10 @@ import javax.crypto.spec.SecretKeySpec import javax.inject.Inject import javax.inject.Singleton -private val HEX_CHARS = "0123456789abcdef" -private val HEX_CHARS_ARRAY = "0123456789abcdef".toCharArray() - -fun String.hexStringToByteArray() : ByteArray { - - val upperCased = this.toLowerCase() - val result = ByteArray(length / 2) - for (i in 0 until length step 2) { - val firstIndex = HEX_CHARS.indexOf(upperCased[i]); - val secondIndex = HEX_CHARS.indexOf(upperCased[i + 1]); - - val octet = firstIndex.shl(4).or(secondIndex) - result.set(i.shr(1), octet.toByte()) - } - - return result -} - -fun ByteArray.toHex() : String{ - val result = StringBuffer() - - forEach { - val octet = it.toInt() - val firstIndex = (octet and 0xF0).ushr(4) - val secondIndex = octet and 0x0F - result.append(HEX_CHARS_ARRAY[firstIndex]) - result.append(HEX_CHARS_ARRAY[secondIndex]) - } - - return result.toString() -} - @Singleton class CryptoUtil @Inject constructor( val aapsLogger: AAPSLogger -) { +) { companion object { private const val IV_LENGTH_BYTE = 12 @@ -71,26 +40,26 @@ class CryptoUtil @Inject constructor( } fun hmac256(str: String, secret: String): String? { - val sha256_HMAC = Mac.getInstance("HmacSHA256") + val sha256HMAC = Mac.getInstance("HmacSHA256") val secretKey = SecretKeySpec(secret.toByteArray(), "HmacSHA256") - sha256_HMAC.init(secretKey) - return sha256_HMAC.doFinal(str.toByteArray()).toHex() + sha256HMAC.init(secretKey) + return sha256HMAC.doFinal(str.toByteArray()).toHex() } - private fun prepCipherKey(passPhrase: String, salt:ByteArray, iterationCount:Int = PBKDF2_ITERATIONS, keyStrength:Int = AES_KEY_SIZE_BIT): SecretKeySpec { + private fun prepCipherKey(passPhrase: String, salt: ByteArray, iterationCount: Int = PBKDF2_ITERATIONS, keyStrength: Int = AES_KEY_SIZE_BIT): SecretKeySpec { val factory: SecretKeyFactory = SecretKeyFactory.getInstance("PBKDF2withHmacSHA1") val spec: KeySpec = PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount, keyStrength) val tmp: SecretKey = factory.generateSecret(spec) - return SecretKeySpec(tmp.getEncoded(), "AES") + return SecretKeySpec(tmp.encoded, "AES") } - fun mineSalt(len :Int = SALT_SIZE_BYTE): ByteArray { + fun mineSalt(len: Int = SALT_SIZE_BYTE): ByteArray { val salt = ByteArray(len) secureRandom.nextBytes(salt) return salt } - fun encrypt(passPhrase: String, salt:ByteArray, rawData: String ): String? { + fun encrypt(passPhrase: String, salt: ByteArray, rawData: String): String? { val iv: ByteArray? val encrypted: ByteArray? return try { @@ -107,12 +76,12 @@ class CryptoUtil @Inject constructor( String(Base64.encode(byteBuffer.array())) } catch (e: Exception) { lastException = e - aapsLogger.error("Encryption failed due to technical exception: ${e}") + aapsLogger.error("Encryption failed due to technical exception: $e") null } } - fun decrypt(passPhrase: String, salt:ByteArray, encryptedData: String): String? { + fun decrypt(passPhrase: String, salt: ByteArray, encryptedData: String): String? { val iv: ByteArray? val encrypted: ByteArray? return try { @@ -129,7 +98,7 @@ class CryptoUtil @Inject constructor( String(dec) } catch (e: Exception) { lastException = e - aapsLogger.error("Decryption failed due to technical exception: ${e}") + aapsLogger.error("Decryption failed due to technical exception: $e") null } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index c9e2835ceb..37b0c0beb6 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -12,11 +12,12 @@ import javax.inject.Singleton @Singleton class HardLimits @Inject constructor( - val aapsLogger: AAPSLogger, - val rxBus: RxBusWrapper, - val sp: SP, - val resourceHelper: ResourceHelper, - val context: Context + private val aapsLogger: AAPSLogger, + private val rxBus: RxBusWrapper, + private val sp: SP, + private val resourceHelper: ResourceHelper, + private val context: Context, + private val nsUpload: NSUpload ) { val CHILD = 0 @@ -35,7 +36,7 @@ class HardLimits @Inject constructor( val VERY_HARD_LIMIT_TEMP_MIN_BG = intArrayOf(72, 180) val VERY_HARD_LIMIT_TEMP_MAX_BG = intArrayOf(72, 270) val VERY_HARD_LIMIT_TEMP_TARGET_BG = intArrayOf(72, 200) - val MINDIA = 2.0 + val MINDIA = 5.0 val MAXDIA = 7.0 val MINIC = 2.0 val MAXIC = 100.0 @@ -90,7 +91,7 @@ class HardLimits @Inject constructor( msg += ".\n" msg += String.format(resourceHelper.gs(R.string.valuelimitedto), value, newvalue) aapsLogger.error(msg) - NSUpload.uploadError(msg) + nsUpload.uploadError(msg) ToastUtils.showToastInUiThread(context, rxBus, msg, R.raw.error) } return newvalue diff --git a/app/src/main/java/info/nightscout/androidaps/utils/HtmlHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/HtmlHelper.kt deleted file mode 100644 index b79fe884b4..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/HtmlHelper.kt +++ /dev/null @@ -1,16 +0,0 @@ -package info.nightscout.androidaps.utils - -import android.os.Build -import android.text.Html -import android.text.Spanned - -object HtmlHelper { - fun fromHtml(source: String): Spanned { - // API level 24 to replace call - @Suppress("DEPRECATION") - return when { - Build.VERSION.SDK_INT >= Build.VERSION_CODES.N -> Html.fromHtml(source, Html.FROM_HTML_MODE_LEGACY) - else -> Html.fromHtml(source) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/JSONFormatter.java b/app/src/main/java/info/nightscout/androidaps/utils/JSONFormatter.java index 9b754ac47a..db1f6af239 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/JSONFormatter.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/JSONFormatter.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.utils; -import android.os.Build; import android.text.Html; import android.text.Spanned; @@ -8,7 +7,6 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Iterator; @@ -24,33 +22,24 @@ public class JSONFormatter { final JsonVisitor visitor = new JsonVisitor(1, '\t'); try { if (jsonString.equals("undefined")) - return Html.fromHtml("undefined"); + return HtmlHelper.INSTANCE.fromHtml("undefined"); else if (jsonString.getBytes()[0] == '[') - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return Html.fromHtml(visitor.visit(new JSONArray(jsonString), 0), Html.FROM_HTML_MODE_COMPACT); - } else { - return Html.fromHtml(visitor.visit(new JSONArray(jsonString), 0)); - } - else { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { - return Html.fromHtml(visitor.visit(new JSONObject(jsonString), 0), Html.FROM_HTML_MODE_COMPACT); - } else { - return Html.fromHtml(visitor.visit(new JSONObject(jsonString), 0)); - } - } + return HtmlHelper.INSTANCE.fromHtml(visitor.visit(new JSONArray(jsonString), 0)); + else + return HtmlHelper.INSTANCE.fromHtml(visitor.visit(new JSONObject(jsonString), 0)); } catch (JSONException e) { log.error("Unhandled exception", e); - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } } public static Spanned format(final JSONObject object) { final JsonVisitor visitor = new JsonVisitor(1, '\t'); try { - return Html.fromHtml(visitor.visit(object, 0)); + return HtmlHelper.INSTANCE.fromHtml(visitor.visit(object, 0)); } catch (JSONException e) { log.error("Unhandled exception", e); - return Html.fromHtml(""); + return HtmlHelper.INSTANCE.fromHtml(""); } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt index d766b92ee8..499fe8afa8 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction 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 @@ -29,7 +29,10 @@ class LocalAlertUtils @Inject constructor( private val resourceHelper: ResourceHelper, private val activePlugin: ActivePluginProvider, private val profileFunction: ProfileFunction, - private val iobCobCalculatorPlugin: IobCobCalculatorPlugin + private val iobCobCalculatorPlugin: IobCobCalculatorPlugin, + private val config: Config, + private val nsUpload: NSUpload, + private val dateUtil: DateUtil ) { fun missedReadingsThreshold(): Long { @@ -43,15 +46,15 @@ class LocalAlertUtils @Inject constructor( fun checkPumpUnreachableAlarm(lastConnection: Long, isStatusOutdated: Boolean, isDisconnected: Boolean) { val alarmTimeoutExpired = isAlarmTimeoutExpired(lastConnection, pumpUnreachableThreshold()) val nextAlarmOccurrenceReached = sp.getLong("nextPumpDisconnectedAlarm", 0L) < System.currentTimeMillis() - if (Config.APS && sp.getBoolean(resourceHelper.gs(R.string.key_enable_pump_unreachable_alert), true) + if (config.APS && sp.getBoolean(resourceHelper.gs(R.string.key_enable_pump_unreachable_alert), true) && isStatusOutdated && alarmTimeoutExpired && nextAlarmOccurrenceReached && !isDisconnected) { - aapsLogger.debug(LTag.CORE, "Generating pump unreachable alarm. lastConnection: " + DateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: " + isStatusOutdated) + aapsLogger.debug(LTag.CORE, "Generating pump unreachable alarm. lastConnection: " + dateUtil.dateAndTimeString(lastConnection) + " isStatusOutdated: " + isStatusOutdated) val n = Notification(Notification.PUMP_UNREACHABLE, resourceHelper.gs(R.string.pump_unreachable), Notification.URGENT) n.soundId = R.raw.alarm sp.putLong("nextPumpDisconnectedAlarm", System.currentTimeMillis() + pumpUnreachableThreshold()) rxBus.send(EventNewNotification(n)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text) + nsUpload.uploadError(n.text) } } if (!isStatusOutdated && !alarmTimeoutExpired) rxBus.send(EventDismissNotification(Notification.PUMP_UNREACHABLE)) @@ -107,7 +110,7 @@ class LocalAlertUtils @Inject constructor( sp.putLong("nextMissedReadingsAlarm", System.currentTimeMillis() + missedReadingsThreshold()) rxBus.send(EventNewNotification(n)) if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { - NSUpload.uploadError(n.text) + nsUpload.uploadError(n.text) } } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java b/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java index cae1a3cde3..5244c5c4ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/NumberPickerVertical.java @@ -1,37 +1,16 @@ package info.nightscout.androidaps.utils; import android.content.Context; -import android.os.Handler; -import android.os.Message; -import android.text.Editable; -import android.text.TextWatcher; import android.util.AttributeSet; -import android.view.KeyEvent; import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.widget.Button; -import android.widget.EditText; -import android.widget.LinearLayout; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.text.NumberFormat; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; - -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.utils.ui.NumberPicker; /** * Created by mike on 28.06.2016. */ public class NumberPickerVertical extends NumberPicker { - private static Logger log = StacktraceLoggerWrapper.getLogger(NumberPickerVertical.class); - public NumberPickerVertical(Context context) { super(context); } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SP.java b/app/src/main/java/info/nightscout/androidaps/utils/SP.java deleted file mode 100644 index a6124acf10..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/utils/SP.java +++ /dev/null @@ -1,50 +0,0 @@ -package info.nightscout.androidaps.utils; - -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import java.util.Map; - -import info.nightscout.androidaps.MainApp; - -/** - * Created by mike on 17.02.2017. - */ - -public class SP { - private static SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(MainApp.instance().getApplicationContext()); - - @Deprecated - static public Map getAll() { - return sharedPreferences.getAll(); - } - - @Deprecated - static public String getString(String key, String defaultValue) { - return sharedPreferences.getString(key, defaultValue); - } - - @Deprecated - static public boolean getBoolean(int resourceID, Boolean defaultValue) { - try { - return sharedPreferences.getBoolean(MainApp.gs(resourceID), defaultValue); - } catch (Exception e) { - return defaultValue; - } - } - - @Deprecated - static public void putString(int resourceID, String value) { - sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply(); - } - - @Deprecated - static public void putString(String key, String value) { - sharedPreferences.edit().putString(key, value).apply(); - } - - @Deprecated - static public void remove(String key) { - sharedPreferences.edit().remove(key).apply(); - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java b/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java index fa79caaf2b..098b90c5d1 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SPBackupAgent.java @@ -2,21 +2,14 @@ package info.nightscout.androidaps.utils; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; - -import info.nightscout.androidaps.MainApp; public class SPBackupAgent extends BackupAgentHelper { - // API 24 - //static final String PREFS = PreferenceManager.getDefaultSharedPreferencesName(MainApp.instance().getApplicationContext()); - static final String PREFS = MainApp.instance().getApplicationContext().getPackageName() + "_preferences"; - - static final String PREFS_BACKUP_KEY = "SP"; - @Override public void onCreate() { + // API 24 + final String PREFS = getApplicationContext().getPackageName() + "_preferences"; + final String PREFS_BACKUP_KEY = "SP"; SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, PREFS); addHelper(PREFS_BACKUP_KEY, helper); diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java index 38ef842f8d..0bfa1cbd0d 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java @@ -23,6 +23,10 @@ import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; +import javax.inject.Inject; +import javax.inject.Singleton; + +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; @@ -38,31 +42,42 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; * } * */ +@Singleton public class SntpClient { - private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.CORE); + private final AAPSLogger aapsLogger; + private final DateUtil dateUtil; + + //private final int REFERENCE_TIME_OFFSET = 16; + private final int ORIGINATE_TIME_OFFSET = 24; + private final int RECEIVE_TIME_OFFSET = 32; + private final int TRANSMIT_TIME_OFFSET = 40; + private final int NTP_PACKET_SIZE = 48; - //private static final int REFERENCE_TIME_OFFSET = 16; - private static final int ORIGINATE_TIME_OFFSET = 24; - private static final int RECEIVE_TIME_OFFSET = 32; - private static final int TRANSMIT_TIME_OFFSET = 40; - private static final int NTP_PACKET_SIZE = 48; + private final int NTP_PORT = 123; + private final int NTP_MODE_CLIENT = 3; + private final int NTP_VERSION = 3; - private static final int NTP_PORT = 123; - private static final int NTP_MODE_CLIENT = 3; - private static final int NTP_VERSION = 3; + @Inject + public SntpClient( + AAPSLogger aapsLogger, + DateUtil dateUtil + ) { + this.aapsLogger = aapsLogger; + this.dateUtil = dateUtil; + } // Number of seconds between Jan 1, 1900 and Jan 1, 1970 // 70 years plus 17 leap days - private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; + private final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L; // system time computed from NTP server response - private static long mNtpTime; + private long mNtpTime; // value of SystemClock.elapsedRealtime() corresponding to mNtpTime - private static long mNtpTimeReference; + private long mNtpTimeReference; // round trip time in milliseconds - private static long mRoundTripTime; + private long mRoundTripTime; public static abstract class Callback implements Runnable { public boolean networkConnected = false; @@ -70,7 +85,7 @@ public class SntpClient { public long time = 0; } - public static synchronized void ntpTime(final Callback callback, boolean isConnected) { + public synchronized void ntpTime(final Callback callback, boolean isConnected) { callback.networkConnected = isConnected; if (callback.networkConnected) { new Thread(() -> doNtpTime(callback)).start(); @@ -79,11 +94,11 @@ public class SntpClient { } } - static void doNtpTime(final Callback callback) { - log.debug("Time detection started"); + void doNtpTime(final Callback callback) { + aapsLogger.debug("Time detection started"); callback.success = requestTime("time.google.com", 5000); callback.time = getNtpTime() + SystemClock.elapsedRealtime() - getNtpTimeReference(); - log.debug("Time detection ended: " + callback.success + " " + DateUtil.dateAndTimeString(getNtpTime())); + aapsLogger.debug("Time detection ended: " + callback.success + " " + dateUtil.dateAndTimeString(getNtpTime())); callback.run(); } @@ -94,7 +109,7 @@ public class SntpClient { * @param timeout network timeout in milliseconds. * @return true if the transaction was successful. */ - private static synchronized boolean requestTime(String host, int timeout) { + private synchronized boolean requestTime(String host, int timeout) { try { DatagramSocket socket = new DatagramSocket(); socket.setSoTimeout(timeout); @@ -144,7 +159,7 @@ public class SntpClient { mNtpTimeReference = responseTicks; mRoundTripTime = roundTripTime; } catch (Exception e) { - log.debug("request time failed: " + e); + aapsLogger.debug("request time failed: " + e); return false; } @@ -156,7 +171,7 @@ public class SntpClient { * * @return time value computed from NTP server response. */ - private static long getNtpTime() { + private long getNtpTime() { return mNtpTime; } @@ -166,7 +181,7 @@ public class SntpClient { * * @return reference clock corresponding to the NTP time. */ - private static long getNtpTimeReference() { + private long getNtpTimeReference() { return mNtpTimeReference; } @@ -182,7 +197,7 @@ public class SntpClient { /** * Reads an unsigned 32 bit big endian number from the given offset in the buffer. */ - private static long read32(byte[] buffer, int offset) { + private long read32(byte[] buffer, int offset) { byte b0 = buffer[offset]; byte b1 = buffer[offset + 1]; byte b2 = buffer[offset + 2]; @@ -201,7 +216,7 @@ public class SntpClient { * Reads the NTP time stamp at the given offset in the buffer and returns * it as a system time (milliseconds since January 1, 1970). */ - private static long readTimeStamp(byte[] buffer, int offset) { + private long readTimeStamp(byte[] buffer, int offset) { long seconds = read32(buffer, offset); long fraction = read32(buffer, offset + 4); return ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L); @@ -211,7 +226,7 @@ public class SntpClient { * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp * at the given offset in the buffer. */ - private static void writeTimeStamp(byte[] buffer, int offset, long time) { + private void writeTimeStamp(byte[] buffer, int offset, long time) { long seconds = time / 1000L; long milliseconds = time - seconds * 1000L; seconds += OFFSET_1900_TO_1970; diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java b/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java index 892f9b2667..1440a65c21 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java @@ -13,30 +13,28 @@ import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.NonNull; -import androidx.core.content.ContextCompat; import androidx.core.widget.TextViewCompat; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; -import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.utils.ui.NumberPicker; /** * Created by mike on 29.12.2016. */ public class TimeListEdit { - private static Logger log = StacktraceLoggerWrapper.getLogger(TimeListEdit.class); + private final AAPSLogger aapsLogger; + private final DateUtil dateUtil; private final int ONEHOURINSECONDS = 60 * 60; @@ -65,8 +63,14 @@ public class TimeListEdit { private int inflatedUntil = -1; - public TimeListEdit(Context context, View view, int resLayoutId, String tagPrefix, String label, JSONArray data1, JSONArray data2, double min, double max, double step, NumberFormat formatter, Runnable save) { + public TimeListEdit( + Context context, + AAPSLogger aapsLogger, + DateUtil dateUtil, + View view, int resLayoutId, String tagPrefix, String label, JSONArray data1, JSONArray data2, double min, double max, double step, NumberFormat formatter, Runnable save) { this.context = context; + this.aapsLogger = aapsLogger; + this.dateUtil = dateUtil; this.view = view; this.resLayoutId = resLayoutId; this.tagPrefix = tagPrefix; @@ -103,7 +107,7 @@ public class TimeListEdit { // last "plus" to append new interval float factor = layout.getContext().getResources().getDisplayMetrics().density; finalAdd = new ImageView(context); - finalAdd.setImageResource(R.drawable.add); + finalAdd.setImageResource(R.drawable.ic_add); LinearLayout.LayoutParams illp = new LinearLayout.LayoutParams((int) (35d * factor), (int) (35 * factor)); illp.setMargins(0, 25, 0, 25); // llp.setMargins(left, top, right, bottom); illp.gravity = Gravity.CENTER; @@ -281,7 +285,7 @@ public class TimeListEdit { ArrayList timeListValues = new ArrayList<>(); int pos = 0; for (int t = previous + ONEHOURINSECONDS; t < next; t += ONEHOURINSECONDS) { - timeList.add(DateUtil.timeStringFromSeconds(t)); + timeList.add(dateUtil.timeStringFromSeconds(t)); timeListValues.add(t); if (secondsFromMidnight == t) posInList = pos; pos++; @@ -311,7 +315,7 @@ public class TimeListEdit { return time; } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -323,7 +327,7 @@ public class TimeListEdit { return item.getDouble("value"); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0d; } @@ -336,7 +340,7 @@ public class TimeListEdit { return item.getDouble("value"); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } return 0d; @@ -362,7 +366,7 @@ public class TimeListEdit { data2.put(index, newObject2); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -383,7 +387,7 @@ public class TimeListEdit { // add new object editItem(index, timeAsSeconds, value1, value2); } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -396,7 +400,7 @@ public class TimeListEdit { private void log() { for (int i = 0; i < data1.length(); i++) { - log.debug(i + ": @" + DateUtil.timeStringFromSeconds(secondFromMidnight(i)) + " " + value1(i) + (data2 != null ? " " + value2(i) : "")); + aapsLogger.debug(i + ": @" + dateUtil.timeStringFromSeconds(secondFromMidnight(i)) + " " + value1(i) + (data2 != null ? " " + value2(i) : "")); } } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt index 9c32ccadef..af13dadb1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/XdripCalibrations.kt @@ -6,7 +6,7 @@ import android.os.Bundle import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt index 6ee23a85f5..028c63086e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolder.kt @@ -10,6 +10,7 @@ import androidx.core.app.TaskStackBuilder import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R +import info.nightscout.androidaps.interfaces.NotificationHolderInterface import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject @@ -20,11 +21,11 @@ class NotificationHolder @Inject constructor( private val resourceHelper: ResourceHelper, private val context: Context, private val iconsProvider: IconsProvider -) { +) : NotificationHolderInterface { - val channelID = "AndroidAPS-Ongoing" - val notificationID = 4711 - var notification: Notification + override val channelID = "AndroidAPS-Ongoing" + override val notificationID = 4711 + override lateinit var notification: Notification init { val stackBuilder = TaskStackBuilder.create(context) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt b/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt index f1cec2109f..a08f671512 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/buildHelper/BuildHelper.kt @@ -8,7 +8,7 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class BuildHelper @Inject constructor() { +class BuildHelper @Inject constructor(private val config: Config) { private var devBranch = false private var engineeringMode = false @@ -22,10 +22,10 @@ class BuildHelper @Inject constructor() { } fun isEngineeringModeOrRelease(): Boolean = - if (!Config.APS) true else engineeringMode || !devBranch + if (!config.APS) true else engineeringMode || !devBranch fun isEngineeringMode(): Boolean = - if (!Config.APS) true else engineeringMode || !devBranch + if (!config.APS) true else engineeringMode || !devBranch fun isDev(): Boolean = devBranch } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt b/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt index d707caaaa1..6bdeaa73a8 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt @@ -6,19 +6,19 @@ import javax.inject.Inject import javax.inject.Singleton @Singleton -class IconsProvider @Inject constructor() { +class IconsProvider @Inject constructor(private val config: Config) { fun getIcon(): Int = when { - Config.NSCLIENT -> R.mipmap.ic_yellowowl - Config.PUMPCONTROL -> R.mipmap.ic_pumpcontrol + config.NSCLIENT -> R.mipmap.ic_yellowowl + config.PUMPCONTROL -> R.mipmap.ic_pumpcontrol else -> R.mipmap.ic_launcher } fun getNotificationIcon(): Int = when { - Config.NSCLIENT -> R.drawable.ic_notif_nsclient - Config.PUMPCONTROL -> R.drawable.ic_notif_pumpcontrol + config.NSCLIENT -> R.drawable.ic_notif_nsclient + config.PUMPCONTROL -> R.drawable.ic_notif_pumpcontrol else -> R.drawable.ic_notif_aaps } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt index f6db77e09f..2b7806468e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TIR.kt @@ -21,7 +21,7 @@ class TIR(val date: Long, val lowThreshold: Double, val highThreshold: Double) { fun inRangePct() = if (count > 0) (inRange.toDouble() / count * 100.0).roundToInt() else 0 fun abovePct() = if (count > 0) (above.toDouble() / count * 100.0).roundToInt() else 0 - fun toText(resourceHelper: ResourceHelper): String = resourceHelper.gs(R.string.tirformat, DateUtil.dateStringShort(date), belowPct(), inRangePct(), abovePct()) + fun toText(resourceHelper: ResourceHelper, dateUtil: DateUtil): String = resourceHelper.gs(R.string.tirformat, dateUtil.dateStringShort(date), belowPct(), inRangePct(), abovePct()) fun toText(resourceHelper: ResourceHelper, days: Int): String = resourceHelper.gs(R.string.tirformat, "%02d".format(days) + " " + resourceHelper.gs(R.string.days), belowPct(), inRangePct(), abovePct()) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt index 906516d5ea..6cecfa4f73 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TddCalculator.kt @@ -10,7 +10,8 @@ import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil @@ -31,8 +32,10 @@ class TddCalculator @Inject constructor( val sp: SP, val activePlugin: ActivePluginProvider, val profileFunction: ProfileFunction, - fabricPrivacy: FabricPrivacy -) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy) { + fabricPrivacy: FabricPrivacy, + nsUpload: NSUpload, + private val dateUtil: DateUtil +) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, nsUpload, fabricPrivacy, dateUtil) { init { service = TreatmentService(injector) // plugin is not started @@ -51,6 +54,7 @@ class TddCalculator @Inject constructor( val midnight = MidnightTime.calc(t.date) val tdd = result[midnight] ?: TDD(midnight, 0.0, 0.0, 0.0) tdd.bolus += t.insulin + tdd.carbs += t.carbs result.put(midnight, tdd) } @@ -61,6 +65,13 @@ class TddCalculator @Inject constructor( val profile = profileFunction.getProfile(t) ?: continue val absoluteRate = tbr?.tempBasalConvertedToAbsolute(t, profile) ?: profile.getBasal(t) tdd.basal += absoluteRate / 60.0 * 5.0 + + if (!activePlugin.getActivePump().isFakingTempsByExtendedBoluses()) { + // they are not included in TBRs + val eb = getExtendedBolusFromHistory(t) + val absoluteEbRate = eb?.absoluteRate() ?: 0.0 + tdd.bolus += absoluteEbRate / 60.0 * 5.0 + } result.put(midnight, tdd) } for (i in 0 until result.size()) { @@ -78,10 +89,12 @@ class TddCalculator @Inject constructor( totalTdd.basal += tdd.basal totalTdd.bolus += tdd.bolus totalTdd.total += tdd.total + totalTdd.carbs += tdd.carbs } totalTdd.basal /= tdds.size().toDouble() totalTdd.bolus /= tdds.size().toDouble() totalTdd.total /= tdds.size().toDouble() + totalTdd.carbs /= tdds.size().toDouble() return totalTdd } @@ -90,16 +103,16 @@ class TddCalculator @Inject constructor( val averageTdd = averageTDD(tdds) return HtmlHelper.fromHtml( "" + resourceHelper.gs(R.string.tdd) + ":
" + - toText(tdds) + + toText(tdds, true) + "" + resourceHelper.gs(R.string.average) + ":
" + - averageTdd.toText(resourceHelper, tdds.size()) + averageTdd.toText(resourceHelper, tdds.size(), true) ) } - private fun toText(tdds: LongSparseArray): String { + private fun toText(tdds: LongSparseArray, includeCarbs: Boolean): String { var t = "" for (i in 0 until tdds.size()) { - t += "${tdds.valueAt(i).toText(resourceHelper)}
" + t += "${tdds.valueAt(i).toText(resourceHelper, dateUtil, includeCarbs)}
" } return t } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt index f1f13cbf0d..bbda132d80 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/stats/TirCalculator.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.MidnightTime @@ -18,7 +18,8 @@ import javax.inject.Singleton @Singleton class TirCalculator @Inject constructor( private val resourceHelper: ResourceHelper, - private val profileFunction: ProfileFunction + private val profileFunction: ProfileFunction, + private val dateUtil: DateUtil ){ fun calculate(days: Long, lowMgdl: Double, highMgdl: Double): LongSparseArray { if (lowMgdl < 39) throw RuntimeException("Low below 39") @@ -89,7 +90,7 @@ class TirCalculator @Inject constructor( fun toText(resourceHelper: ResourceHelper, tirs: LongSparseArray): String { var t = "" for (i in 0 until tirs.size()) { - t += "${tirs.valueAt(i).toText(resourceHelper)}
" + t += "${tirs.valueAt(i).toText(resourceHelper, dateUtil)}
" } return t } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt index 8416eff715..13fede251e 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/BolusWizard.kt @@ -5,6 +5,7 @@ import android.content.Intent import android.text.Spanned import com.google.common.base.Joiner import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Config import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.data.DetailedBolusInfo @@ -19,7 +20,7 @@ import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.queue.Callback @@ -49,6 +50,7 @@ class BolusWizard @Inject constructor( @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var loopPlugin: LoopPlugin @Inject lateinit var iobCobCalculatorPlugin: IobCobCalculatorPlugin + @Inject lateinit var config: Config init { injector.androidInjector().inject(this) @@ -278,9 +280,9 @@ class BolusWizard @Inject constructor( if (carbs > 0) { var timeShift = "" if (carbTime > 0) { - timeShift += " ( +" + resourceHelper.gs(R.string.mins, carbTime) + " )" + timeShift += " (+" + resourceHelper.gs(R.string.mins, carbTime) + ")" } else if (carbTime < 0) { - timeShift += " ( -" + resourceHelper.gs(R.string.mins, carbTime) + " )" + timeShift += " (-" + resourceHelper.gs(R.string.mins, carbTime) + ")" } actions.add(resourceHelper.gs(R.string.carbs) + ": " + "" + carbs + "g" + timeShift + "") } @@ -293,6 +295,8 @@ class BolusWizard @Inject constructor( if (abs(insulinAfterConstraints - calculatedTotalInsulin) > pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints)) { actions.add(resourceHelper.gs(R.string.bolusconstraintappliedwarning, resourceHelper.gc(R.color.warning), calculatedTotalInsulin, insulinAfterConstraints)) } + if (config.NSCLIENT) + actions.add("" + resourceHelper.gs(R.string.bolusrecordedonly) + "") return HtmlHelper.fromHtml(Joiner.on("
").join(actions)) } diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt index f24f3d72f4..baf858dc14 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizardEntry.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.db.BgReading import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin diff --git a/app/src/main/jniLibs/README.md b/app/src/main/jniLibs/README.md new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/src/main/jniLibs/arm64-v8a/libBleCommandUtil.so b/app/src/main/jniLibs/arm64-v8a/libBleCommandUtil.so new file mode 100644 index 0000000000..69e283b5fe Binary files /dev/null and b/app/src/main/jniLibs/arm64-v8a/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/armeabi-v7a/libBleCommandUtil.so b/app/src/main/jniLibs/armeabi-v7a/libBleCommandUtil.so new file mode 100644 index 0000000000..0c717bc3e8 Binary files /dev/null and b/app/src/main/jniLibs/armeabi-v7a/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/armeabi/libBleCommandUtil.so b/app/src/main/jniLibs/armeabi/libBleCommandUtil.so new file mode 100644 index 0000000000..a51a8c7d9a Binary files /dev/null and b/app/src/main/jniLibs/armeabi/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/mips/libBleCommandUtil.so b/app/src/main/jniLibs/mips/libBleCommandUtil.so new file mode 100644 index 0000000000..fcff5eb6b2 Binary files /dev/null and b/app/src/main/jniLibs/mips/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/mips64/libBleCommandUtil.so b/app/src/main/jniLibs/mips64/libBleCommandUtil.so new file mode 100644 index 0000000000..a8a292ea13 Binary files /dev/null and b/app/src/main/jniLibs/mips64/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/x86/libBleCommandUtil.so b/app/src/main/jniLibs/x86/libBleCommandUtil.so new file mode 100644 index 0000000000..638a9def95 Binary files /dev/null and b/app/src/main/jniLibs/x86/libBleCommandUtil.so differ diff --git a/app/src/main/jniLibs/x86_64/libBleCommandUtil.so b/app/src/main/jniLibs/x86_64/libBleCommandUtil.so new file mode 100644 index 0000000000..94873d3732 Binary files /dev/null and b/app/src/main/jniLibs/x86_64/libBleCommandUtil.so differ diff --git a/app/src/main/res/drawable-hdpi-v11/ic_settings.png b/app/src/main/res/drawable-hdpi-v11/ic_settings.png deleted file mode 100644 index 8a55c0221f..0000000000 Binary files a/app/src/main/res/drawable-hdpi-v11/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi-v9/ic_settings.png b/app/src/main/res/drawable-hdpi-v9/ic_settings.png deleted file mode 100644 index 23b7ef3529..0000000000 Binary files a/app/src/main/res/drawable-hdpi-v9/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/bad.png b/app/src/main/res/drawable-hdpi/bad.png deleted file mode 100644 index 139bf1ddee..0000000000 Binary files a/app/src/main/res/drawable-hdpi/bad.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/good.png b/app/src/main/res/drawable-hdpi/good.png deleted file mode 100644 index 05723ff4ea..0000000000 Binary files a/app/src/main/res/drawable-hdpi/good.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_error.png b/app/src/main/res/drawable-hdpi/ic_error.png deleted file mode 100644 index 5b57c7458f..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_error.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_exit_to_app.png b/app/src/main/res/drawable-hdpi/ic_exit_to_app.png deleted file mode 100644 index f028ac5539..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_exit_to_app.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_maintenance.png b/app/src/main/res/drawable-hdpi/ic_maintenance.png deleted file mode 100644 index 60f34eb201..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_maintenance.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_notif_aaps.png b/app/src/main/res/drawable-hdpi/ic_notif_aaps.png deleted file mode 100644 index 453ed7b382..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_notif_aaps.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_notif_nsclient.png b/app/src/main/res/drawable-hdpi/ic_notif_nsclient.png deleted file mode 100644 index e6d52996a6..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_notif_nsclient.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_notif_pumpcontrol.png b/app/src/main/res/drawable-hdpi/ic_notif_pumpcontrol.png deleted file mode 100644 index 5562fef378..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_notif_pumpcontrol.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_reminder.png b/app/src/main/res/drawable-hdpi/ic_reminder.png deleted file mode 100644 index b45924d4eb..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_reminder.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_settings.png b/app/src/main/res/drawable-hdpi/ic_settings.png deleted file mode 100644 index 20d9681376..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_visibility.png b/app/src/main/res/drawable-hdpi/ic_visibility.png deleted file mode 100644 index a014628e30..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_visibility.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/ic_warning.png b/app/src/main/res/drawable-hdpi/ic_warning.png deleted file mode 100644 index d7aa344bca..0000000000 Binary files a/app/src/main/res/drawable-hdpi/ic_warning.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_cancelextbolus.png b/app/src/main/res/drawable-hdpi/icon_actions_cancelextbolus.png deleted file mode 100644 index 95761084a9..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_profileswitch.png b/app/src/main/res/drawable-hdpi/icon_actions_profileswitch.png deleted file mode 100644 index 4b36a0cc23..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_refill.png b/app/src/main/res/drawable-hdpi/icon_actions_refill.png deleted file mode 100644 index ace25d1558..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_startextbolus.png b/app/src/main/res/drawable-hdpi/icon_actions_startextbolus.png deleted file mode 100644 index a67d52838c..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_starttempbasal.png b/app/src/main/res/drawable-hdpi/icon_actions_starttempbasal.png deleted file mode 100644 index 8772df62a4..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_actions_temptarget.png b/app/src/main/res/drawable-hdpi/icon_actions_temptarget.png deleted file mode 100644 index f839a6894b..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_bolus.png b/app/src/main/res/drawable-hdpi/icon_bolus.png deleted file mode 100644 index b212194219..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_calculator.png b/app/src/main/res/drawable-hdpi/icon_calculator.png deleted file mode 100644 index 2eb2a3b96c..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_calibration.png b/app/src/main/res/drawable-hdpi/icon_calibration.png deleted file mode 100644 index 605635f41d..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cancelbasal.png b/app/src/main/res/drawable-hdpi/icon_cancelbasal.png deleted file mode 100644 index 91803a3f3c..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_aaps_offline.png b/app/src/main/res/drawable-hdpi/icon_cp_aaps_offline.png deleted file mode 100644 index 0fe1cd628b..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_age_battery.png b/app/src/main/res/drawable-hdpi/icon_cp_age_battery.png deleted file mode 100644 index abc626901a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_age_canula.png b/app/src/main/res/drawable-hdpi/icon_cp_age_canula.png deleted file mode 100644 index ecccc39426..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_age_insulin.png b/app/src/main/res/drawable-hdpi/icon_cp_age_insulin.png deleted file mode 100644 index ab4d345881..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_age_sensor.png b/app/src/main/res/drawable-hdpi/icon_cp_age_sensor.png deleted file mode 100644 index 30d5d02de0..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_announcement.png b/app/src/main/res/drawable-hdpi/icon_cp_announcement.png deleted file mode 100644 index 23c9a9847d..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_basal_end.png b/app/src/main/res/drawable-hdpi/icon_cp_basal_end.png deleted file mode 100644 index b9cdf5cc1f..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_basal_start.png b/app/src/main/res/drawable-hdpi/icon_cp_basal_start.png deleted file mode 100644 index d79ca15f86..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bgcheck.png b/app/src/main/res/drawable-hdpi/icon_cp_bgcheck.png deleted file mode 100644 index 56569a264a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bolus_carbs.png b/app/src/main/res/drawable-hdpi/icon_cp_bolus_carbs.png deleted file mode 100644 index ed6be099aa..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bolus_combo.png b/app/src/main/res/drawable-hdpi/icon_cp_bolus_combo.png deleted file mode 100644 index 98c076905c..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bolus_correction.png b/app/src/main/res/drawable-hdpi/icon_cp_bolus_correction.png deleted file mode 100644 index 8ad7864406..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bolus_meal.png b/app/src/main/res/drawable-hdpi/icon_cp_bolus_meal.png deleted file mode 100644 index 97dd4e2ed8..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_bolus_snack.png b/app/src/main/res/drawable-hdpi/icon_cp_bolus_snack.png deleted file mode 100644 index 710bf6e0da..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_cgm_insert.png b/app/src/main/res/drawable-hdpi/icon_cp_cgm_insert.png deleted file mode 100644 index 699be54792..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_cgm_profile.png b/app/src/main/res/drawable-hdpi/icon_cp_cgm_profile.png deleted file mode 100644 index 8887e60f27..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_cgm_start.png b/app/src/main/res/drawable-hdpi/icon_cp_cgm_start.png deleted file mode 100644 index e917402c48..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_cgm_target.png b/app/src/main/res/drawable-hdpi/icon_cp_cgm_target.png deleted file mode 100644 index 2cf826dad1..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_exercise.png b/app/src/main/res/drawable-hdpi/icon_cp_exercise.png deleted file mode 100644 index e9aee1ac8a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_note.png b/app/src/main/res/drawable-hdpi/icon_cp_note.png deleted file mode 100644 index b6b752e150..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_pump_battery.png b/app/src/main/res/drawable-hdpi/icon_cp_pump_battery.png deleted file mode 100644 index b4a4f2923a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_pump_canula.png b/app/src/main/res/drawable-hdpi/icon_cp_pump_canula.png deleted file mode 100644 index e75d9ed81d..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_pump_cartridge.png b/app/src/main/res/drawable-hdpi/icon_cp_pump_cartridge.png deleted file mode 100644 index f780c23e37..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_cp_question.png b/app/src/main/res/drawable-hdpi/icon_cp_question.png deleted file mode 100644 index 65102f2abf..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_danar_useropthdpi.png b/app/src/main/res/drawable-hdpi/icon_danar_useropthdpi.png deleted file mode 100644 index ee3ab7725e..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_danar_useropthdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_danarhistory.png b/app/src/main/res/drawable-hdpi/icon_danarhistory.png deleted file mode 100644 index 2de295946a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_danarhistory.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_danarprofile.png b/app/src/main/res/drawable-hdpi/icon_danarprofile.png deleted file mode 100644 index 31148c5647..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_danarprofile.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_danarstats.png b/app/src/main/res/drawable-hdpi/icon_danarstats.png deleted file mode 100644 index 9caa112e0e..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_danarstats.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_home_loop.png b/app/src/main/res/drawable-hdpi/icon_home_loop.png deleted file mode 100644 index b0f9f6ea29..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_home_profile.png b/app/src/main/res/drawable-hdpi/icon_home_profile.png deleted file mode 100644 index b288171332..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_activate.png b/app/src/main/res/drawable-hdpi/icon_local_activate.png deleted file mode 100644 index 4ef567ffb6..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_activate.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_activatehdpi.png b/app/src/main/res/drawable-hdpi/icon_local_activatehdpi.png deleted file mode 100644 index 4ef567ffb6..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_activatehdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_reset.png b/app/src/main/res/drawable-hdpi/icon_local_reset.png deleted file mode 100644 index 7d38cf0b50..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_reset.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_resethdpi.png b/app/src/main/res/drawable-hdpi/icon_local_resethdpi.png deleted file mode 100644 index 7d38cf0b50..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_resethdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_save.png b/app/src/main/res/drawable-hdpi/icon_local_save.png deleted file mode 100644 index e5c1d5cedc..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_save.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png b/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png deleted file mode 100644 index e5c1d5cedc..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_local_savehdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_quickwizard.png b/app/src/main/res/drawable-hdpi/icon_quickwizard.png deleted file mode 100644 index 67a020c05e..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/icon_xdrip.png b/app/src/main/res/drawable-hdpi/icon_xdrip.png deleted file mode 100644 index bda51738e7..0000000000 Binary files a/app/src/main/res/drawable-hdpi/icon_xdrip.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_closed.png b/app/src/main/res/drawable-hdpi/loop_closed.png deleted file mode 100644 index 066dd4c26a..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_closed.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_disabled.png b/app/src/main/res/drawable-hdpi/loop_disabled.png deleted file mode 100644 index 268a9bc76b..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_disabled.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_disconnected.png b/app/src/main/res/drawable-hdpi/loop_disconnected.png deleted file mode 100644 index bfff44ea1e..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_disconnected.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_lgs.png b/app/src/main/res/drawable-hdpi/loop_lgs.png deleted file mode 100644 index e45fda615b..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_lgs.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_open.png b/app/src/main/res/drawable-hdpi/loop_open.png deleted file mode 100644 index cdefc55ce8..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_pause.png b/app/src/main/res/drawable-hdpi/loop_pause.png deleted file mode 100644 index bb97008a07..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_pause.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/loop_superbolus.png b/app/src/main/res/drawable-hdpi/loop_superbolus.png deleted file mode 100644 index d9cec8f047..0000000000 Binary files a/app/src/main/res/drawable-hdpi/loop_superbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-hdpi/soso.png b/app/src/main/res/drawable-hdpi/soso.png deleted file mode 100644 index f7a9be577e..0000000000 Binary files a/app/src/main/res/drawable-hdpi/soso.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi-v11/ic_settings.png b/app/src/main/res/drawable-mdpi-v11/ic_settings.png deleted file mode 100644 index 9053263239..0000000000 Binary files a/app/src/main/res/drawable-mdpi-v11/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi-v11/refresh.xml b/app/src/main/res/drawable-mdpi-v11/refresh.xml deleted file mode 100644 index 677809a8c2..0000000000 --- a/app/src/main/res/drawable-mdpi-v11/refresh.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable-mdpi-v9/ic_settings.png b/app/src/main/res/drawable-mdpi-v9/ic_settings.png deleted file mode 100644 index 3c39ceb390..0000000000 Binary files a/app/src/main/res/drawable-mdpi-v9/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/bad.png b/app/src/main/res/drawable-mdpi/bad.png deleted file mode 100644 index 9210154195..0000000000 Binary files a/app/src/main/res/drawable-mdpi/bad.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/good.png b/app/src/main/res/drawable-mdpi/good.png deleted file mode 100644 index a15f82c2b2..0000000000 Binary files a/app/src/main/res/drawable-mdpi/good.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_error.png b/app/src/main/res/drawable-mdpi/ic_error.png deleted file mode 100644 index 68a4b0e48c..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_error.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_exit_to_app.png b/app/src/main/res/drawable-mdpi/ic_exit_to_app.png deleted file mode 100644 index d2531b3e46..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_exit_to_app.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_maintenance.png b/app/src/main/res/drawable-mdpi/ic_maintenance.png deleted file mode 100644 index 728313d9e7..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_maintenance.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_notif_aaps.png b/app/src/main/res/drawable-mdpi/ic_notif_aaps.png deleted file mode 100644 index c483ada178..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_notif_aaps.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_notif_nsclient.png b/app/src/main/res/drawable-mdpi/ic_notif_nsclient.png deleted file mode 100644 index 0e55ac39eb..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_notif_nsclient.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_notif_pumpcontrol.png b/app/src/main/res/drawable-mdpi/ic_notif_pumpcontrol.png deleted file mode 100644 index 3feb5d6248..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_notif_pumpcontrol.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_reminder.png b/app/src/main/res/drawable-mdpi/ic_reminder.png deleted file mode 100644 index 2c269d5530..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_reminder.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_settings.png b/app/src/main/res/drawable-mdpi/ic_settings.png deleted file mode 100644 index 60b53e614e..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_visibility.png b/app/src/main/res/drawable-mdpi/ic_visibility.png deleted file mode 100644 index d5a9dc9ca4..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_visibility.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/ic_warning.png b/app/src/main/res/drawable-mdpi/ic_warning.png deleted file mode 100644 index 1ff44a152a..0000000000 Binary files a/app/src/main/res/drawable-mdpi/ic_warning.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_cancelextbolus.png b/app/src/main/res/drawable-mdpi/icon_actions_cancelextbolus.png deleted file mode 100644 index 4ad378e374..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_profileswitch.png b/app/src/main/res/drawable-mdpi/icon_actions_profileswitch.png deleted file mode 100644 index eeae6ccfdb..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_refill.png b/app/src/main/res/drawable-mdpi/icon_actions_refill.png deleted file mode 100644 index 737cca8b00..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_startextbolus.png b/app/src/main/res/drawable-mdpi/icon_actions_startextbolus.png deleted file mode 100644 index 338df773c2..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_starttempbasal.png b/app/src/main/res/drawable-mdpi/icon_actions_starttempbasal.png deleted file mode 100644 index 18fbd8c111..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_actions_temptarget.png b/app/src/main/res/drawable-mdpi/icon_actions_temptarget.png deleted file mode 100644 index 39170bab37..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_bolus.png b/app/src/main/res/drawable-mdpi/icon_bolus.png deleted file mode 100644 index c083219b45..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_calculator.png b/app/src/main/res/drawable-mdpi/icon_calculator.png deleted file mode 100644 index 056722a440..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_calibration.png b/app/src/main/res/drawable-mdpi/icon_calibration.png deleted file mode 100644 index 0929d3690d..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cancelbasal.png b/app/src/main/res/drawable-mdpi/icon_cancelbasal.png deleted file mode 100644 index c48a20792d..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_aaps_offline.png b/app/src/main/res/drawable-mdpi/icon_cp_aaps_offline.png deleted file mode 100644 index dc50653883..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_age_battery.png b/app/src/main/res/drawable-mdpi/icon_cp_age_battery.png deleted file mode 100644 index 6c7fc56139..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_age_canula.png b/app/src/main/res/drawable-mdpi/icon_cp_age_canula.png deleted file mode 100644 index 303ad946cd..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_age_insulin.png b/app/src/main/res/drawable-mdpi/icon_cp_age_insulin.png deleted file mode 100644 index 5cd8598faa..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_age_sensor.png b/app/src/main/res/drawable-mdpi/icon_cp_age_sensor.png deleted file mode 100644 index d312b6c572..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_announcement.png b/app/src/main/res/drawable-mdpi/icon_cp_announcement.png deleted file mode 100644 index 6e1338ac24..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_basal_end.png b/app/src/main/res/drawable-mdpi/icon_cp_basal_end.png deleted file mode 100644 index be8474f002..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_basal_start.png b/app/src/main/res/drawable-mdpi/icon_cp_basal_start.png deleted file mode 100644 index 34cd31f14b..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bgcheck.png b/app/src/main/res/drawable-mdpi/icon_cp_bgcheck.png deleted file mode 100644 index 0cb14c2f57..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bolus_carbs.png b/app/src/main/res/drawable-mdpi/icon_cp_bolus_carbs.png deleted file mode 100644 index 561703fb06..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bolus_combo.png b/app/src/main/res/drawable-mdpi/icon_cp_bolus_combo.png deleted file mode 100644 index ce4d8fb9d3..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bolus_correction.png b/app/src/main/res/drawable-mdpi/icon_cp_bolus_correction.png deleted file mode 100644 index 582472dc92..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bolus_meal.png b/app/src/main/res/drawable-mdpi/icon_cp_bolus_meal.png deleted file mode 100644 index 54b51e126e..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_bolus_snack.png b/app/src/main/res/drawable-mdpi/icon_cp_bolus_snack.png deleted file mode 100644 index b2ba41c27d..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_cgm_insert.png b/app/src/main/res/drawable-mdpi/icon_cp_cgm_insert.png deleted file mode 100644 index 67c0fb1ba2..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_cgm_profile.png b/app/src/main/res/drawable-mdpi/icon_cp_cgm_profile.png deleted file mode 100644 index e0f0a15cc8..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_cgm_start.png b/app/src/main/res/drawable-mdpi/icon_cp_cgm_start.png deleted file mode 100644 index 14a44bc852..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_cgm_target.png b/app/src/main/res/drawable-mdpi/icon_cp_cgm_target.png deleted file mode 100644 index 86ce00442c..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_exercise.png b/app/src/main/res/drawable-mdpi/icon_cp_exercise.png deleted file mode 100644 index 1c92c0ebb5..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_note.png b/app/src/main/res/drawable-mdpi/icon_cp_note.png deleted file mode 100644 index 7c8663a4fe..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_pump_battery.png b/app/src/main/res/drawable-mdpi/icon_cp_pump_battery.png deleted file mode 100644 index f4dab169a8..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_pump_canula.png b/app/src/main/res/drawable-mdpi/icon_cp_pump_canula.png deleted file mode 100644 index ee512c5fef..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_pump_cartridge.png b/app/src/main/res/drawable-mdpi/icon_cp_pump_cartridge.png deleted file mode 100644 index 70a90c596f..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_cp_question.png b/app/src/main/res/drawable-mdpi/icon_cp_question.png deleted file mode 100644 index 5d430d9164..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_danar_useroptmdpi.png b/app/src/main/res/drawable-mdpi/icon_danar_useroptmdpi.png deleted file mode 100644 index 1fadcd446b..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_danar_useroptmdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_danarhistory.png b/app/src/main/res/drawable-mdpi/icon_danarhistory.png deleted file mode 100644 index 60e61d125a..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_danarhistory.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_danarprofile.png b/app/src/main/res/drawable-mdpi/icon_danarprofile.png deleted file mode 100644 index 485eb6dc61..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_danarprofile.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_danarstats.png b/app/src/main/res/drawable-mdpi/icon_danarstats.png deleted file mode 100644 index a0fcd27008..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_danarstats.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_home_loop.png b/app/src/main/res/drawable-mdpi/icon_home_loop.png deleted file mode 100644 index 5240cc85db..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_home_profile.png b/app/src/main/res/drawable-mdpi/icon_home_profile.png deleted file mode 100644 index f689df10c6..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_activate.png b/app/src/main/res/drawable-mdpi/icon_local_activate.png deleted file mode 100644 index b39c72b407..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_activate.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_activatemdpi.png b/app/src/main/res/drawable-mdpi/icon_local_activatemdpi.png deleted file mode 100644 index b39c72b407..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_activatemdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_reset.png b/app/src/main/res/drawable-mdpi/icon_local_reset.png deleted file mode 100644 index ad2e0eaf6d..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_reset.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_resetmdpi.png b/app/src/main/res/drawable-mdpi/icon_local_resetmdpi.png deleted file mode 100644 index ad2e0eaf6d..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_resetmdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_save.png b/app/src/main/res/drawable-mdpi/icon_local_save.png deleted file mode 100644 index 843beed523..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_save.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_local_savemdpi.png b/app/src/main/res/drawable-mdpi/icon_local_savemdpi.png deleted file mode 100644 index 843beed523..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_local_savemdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_quickwizard.png b/app/src/main/res/drawable-mdpi/icon_quickwizard.png deleted file mode 100644 index d65347f235..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/icon_xdrip.png b/app/src/main/res/drawable-mdpi/icon_xdrip.png deleted file mode 100644 index 700e274f5b..0000000000 Binary files a/app/src/main/res/drawable-mdpi/icon_xdrip.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_closed.png b/app/src/main/res/drawable-mdpi/loop_closed.png deleted file mode 100644 index ba4283035b..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_closed.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_disabled.png b/app/src/main/res/drawable-mdpi/loop_disabled.png deleted file mode 100644 index e4650ec0ac..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_disabled.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_disconnected.png b/app/src/main/res/drawable-mdpi/loop_disconnected.png deleted file mode 100644 index 0bc9949349..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_disconnected.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_lgs.png b/app/src/main/res/drawable-mdpi/loop_lgs.png deleted file mode 100644 index a49229d4d8..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_lgs.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_open.png b/app/src/main/res/drawable-mdpi/loop_open.png deleted file mode 100644 index f82346f739..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_paused.png b/app/src/main/res/drawable-mdpi/loop_paused.png deleted file mode 100644 index 7258615f66..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_paused.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/loop_superbolus.png b/app/src/main/res/drawable-mdpi/loop_superbolus.png deleted file mode 100644 index 34a61c1bf3..0000000000 Binary files a/app/src/main/res/drawable-mdpi/loop_superbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-mdpi/soso.png b/app/src/main/res/drawable-mdpi/soso.png deleted file mode 100644 index 91d9bd7ddf..0000000000 Binary files a/app/src/main/res/drawable-mdpi/soso.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi-v11/ic_settings.png b/app/src/main/res/drawable-xhdpi-v11/ic_settings.png deleted file mode 100644 index e433609716..0000000000 Binary files a/app/src/main/res/drawable-xhdpi-v11/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi-v9/ic_settings.png b/app/src/main/res/drawable-xhdpi-v9/ic_settings.png deleted file mode 100644 index 8caf4ecbdd..0000000000 Binary files a/app/src/main/res/drawable-xhdpi-v9/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/bad.png b/app/src/main/res/drawable-xhdpi/bad.png deleted file mode 100644 index 46dca7155f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/bad.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/good.png b/app/src/main/res/drawable-xhdpi/good.png deleted file mode 100644 index 08946fed3e..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/good.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_error.png b/app/src/main/res/drawable-xhdpi/ic_error.png deleted file mode 100644 index dee2d5af82..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_error.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_exit_to_app.png b/app/src/main/res/drawable-xhdpi/ic_exit_to_app.png deleted file mode 100644 index d35a1f0d4e..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_exit_to_app.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_maintenance.png b/app/src/main/res/drawable-xhdpi/ic_maintenance.png deleted file mode 100644 index 303e1780f9..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_maintenance.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_notif_aaps.png b/app/src/main/res/drawable-xhdpi/ic_notif_aaps.png deleted file mode 100644 index 56c4049e84..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_notif_aaps.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_notif_nsclient.png b/app/src/main/res/drawable-xhdpi/ic_notif_nsclient.png deleted file mode 100644 index 0ec8b219b6..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_notif_nsclient.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_notif_pumpcontrol.png b/app/src/main/res/drawable-xhdpi/ic_notif_pumpcontrol.png deleted file mode 100644 index e5eb24b9da..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_notif_pumpcontrol.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_reminder.png b/app/src/main/res/drawable-xhdpi/ic_reminder.png deleted file mode 100644 index 904a608285..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_reminder.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_settings.png b/app/src/main/res/drawable-xhdpi/ic_settings.png deleted file mode 100644 index 58099b4ce7..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_visibility.png b/app/src/main/res/drawable-xhdpi/ic_visibility.png deleted file mode 100644 index 1e16fb934f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_visibility.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/ic_warning.png b/app/src/main/res/drawable-xhdpi/ic_warning.png deleted file mode 100644 index 652a1bb1d9..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/ic_warning.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_cancelextbolus.png b/app/src/main/res/drawable-xhdpi/icon_actions_cancelextbolus.png deleted file mode 100644 index 8c4ee82d1e..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_profileswitch.png b/app/src/main/res/drawable-xhdpi/icon_actions_profileswitch.png deleted file mode 100644 index 57864f6ed5..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_refill.png b/app/src/main/res/drawable-xhdpi/icon_actions_refill.png deleted file mode 100644 index ace20f3bfe..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_startextbolus.png b/app/src/main/res/drawable-xhdpi/icon_actions_startextbolus.png deleted file mode 100644 index 0e59f6ec36..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_starttempbasal.png b/app/src/main/res/drawable-xhdpi/icon_actions_starttempbasal.png deleted file mode 100644 index 1deb6f3ca8..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_actions_temptarget.png b/app/src/main/res/drawable-xhdpi/icon_actions_temptarget.png deleted file mode 100644 index c484837e53..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_bolus.png b/app/src/main/res/drawable-xhdpi/icon_bolus.png deleted file mode 100644 index a472289d6b..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_calculator.png b/app/src/main/res/drawable-xhdpi/icon_calculator.png deleted file mode 100644 index 9352f7b2a7..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_calibration.png b/app/src/main/res/drawable-xhdpi/icon_calibration.png deleted file mode 100644 index 98a24e4c78..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cancelbasal.png b/app/src/main/res/drawable-xhdpi/icon_cancelbasal.png deleted file mode 100644 index a6eb55c6cb..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_aaps_offline.png b/app/src/main/res/drawable-xhdpi/icon_cp_aaps_offline.png deleted file mode 100644 index 4239e40ba7..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_age_battery.png b/app/src/main/res/drawable-xhdpi/icon_cp_age_battery.png deleted file mode 100644 index 3d75b9dc7a..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_age_canula.png b/app/src/main/res/drawable-xhdpi/icon_cp_age_canula.png deleted file mode 100644 index 8629a7998d..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_age_insulin.png b/app/src/main/res/drawable-xhdpi/icon_cp_age_insulin.png deleted file mode 100644 index 2e88ec9ad4..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_age_sensor.png b/app/src/main/res/drawable-xhdpi/icon_cp_age_sensor.png deleted file mode 100644 index a3577da118..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_announcement.png b/app/src/main/res/drawable-xhdpi/icon_cp_announcement.png deleted file mode 100644 index 472b51d775..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_basal_end.png b/app/src/main/res/drawable-xhdpi/icon_cp_basal_end.png deleted file mode 100644 index c92af22df3..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_basal_start.png b/app/src/main/res/drawable-xhdpi/icon_cp_basal_start.png deleted file mode 100644 index 5e694ba89c..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bgcheck.png b/app/src/main/res/drawable-xhdpi/icon_cp_bgcheck.png deleted file mode 100644 index 030099f910..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_carbs.png b/app/src/main/res/drawable-xhdpi/icon_cp_bolus_carbs.png deleted file mode 100644 index 64815bc8f0..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_combo.png b/app/src/main/res/drawable-xhdpi/icon_cp_bolus_combo.png deleted file mode 100644 index 908f33ccd8..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_correction.png b/app/src/main/res/drawable-xhdpi/icon_cp_bolus_correction.png deleted file mode 100644 index 0fe89d5f8b..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_meal.png b/app/src/main/res/drawable-xhdpi/icon_cp_bolus_meal.png deleted file mode 100644 index 52ef734adf..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_snack.png b/app/src/main/res/drawable-xhdpi/icon_cp_bolus_snack.png deleted file mode 100644 index 8d2e9690fc..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_insert.png b/app/src/main/res/drawable-xhdpi/icon_cp_cgm_insert.png deleted file mode 100644 index af93321e3a..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_profile.png b/app/src/main/res/drawable-xhdpi/icon_cp_cgm_profile.png deleted file mode 100644 index e4c50f2667..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_start.png b/app/src/main/res/drawable-xhdpi/icon_cp_cgm_start.png deleted file mode 100644 index ce23d1cf54..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_target.png b/app/src/main/res/drawable-xhdpi/icon_cp_cgm_target.png deleted file mode 100644 index fbd5880490..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_exercise.png b/app/src/main/res/drawable-xhdpi/icon_cp_exercise.png deleted file mode 100644 index 90cc102c07..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_note.png b/app/src/main/res/drawable-xhdpi/icon_cp_note.png deleted file mode 100644 index cf821a9d1f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_pump_battery.png b/app/src/main/res/drawable-xhdpi/icon_cp_pump_battery.png deleted file mode 100644 index 15af2af396..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_pump_canula.png b/app/src/main/res/drawable-xhdpi/icon_cp_pump_canula.png deleted file mode 100644 index 84ae19c4a3..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_pump_cartridge.png b/app/src/main/res/drawable-xhdpi/icon_cp_pump_cartridge.png deleted file mode 100644 index d40a8540e6..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_cp_question.png b/app/src/main/res/drawable-xhdpi/icon_cp_question.png deleted file mode 100644 index 43df04ef81..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_danar_useroptxhdpi.png b/app/src/main/res/drawable-xhdpi/icon_danar_useroptxhdpi.png deleted file mode 100644 index 126122a570..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_danar_useroptxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_danarhistory.png b/app/src/main/res/drawable-xhdpi/icon_danarhistory.png deleted file mode 100644 index 8dba1c6a8e..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_danarhistory.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_danarprofile.png b/app/src/main/res/drawable-xhdpi/icon_danarprofile.png deleted file mode 100644 index 227b49a89c..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_danarprofile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_danarstats.png b/app/src/main/res/drawable-xhdpi/icon_danarstats.png deleted file mode 100644 index 3d525ea4e6..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_danarstats.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_home_loop.png b/app/src/main/res/drawable-xhdpi/icon_home_loop.png deleted file mode 100644 index 09ebbed57f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_home_profile.png b/app/src/main/res/drawable-xhdpi/icon_home_profile.png deleted file mode 100644 index 95c0ca4502..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_activate.png b/app/src/main/res/drawable-xhdpi/icon_local_activate.png deleted file mode 100644 index 75e9af38ed..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_activate.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png deleted file mode 100644 index 75e9af38ed..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_activatexhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_reset.png b/app/src/main/res/drawable-xhdpi/icon_local_reset.png deleted file mode 100644 index 2813cb448d..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_reset.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png deleted file mode 100644 index 2813cb448d..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_resetxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_save.png b/app/src/main/res/drawable-xhdpi/icon_local_save.png deleted file mode 100644 index 0cf81430cc..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_save.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png b/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png deleted file mode 100644 index 0cf81430cc..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_local_savexhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_quickwizard.png b/app/src/main/res/drawable-xhdpi/icon_quickwizard.png deleted file mode 100644 index b937f1448f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/icon_xdrip.png b/app/src/main/res/drawable-xhdpi/icon_xdrip.png deleted file mode 100644 index ae4c77b1a8..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/icon_xdrip.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_closed.png b/app/src/main/res/drawable-xhdpi/loop_closed.png deleted file mode 100644 index f7548add59..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_closed.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_disabled.png b/app/src/main/res/drawable-xhdpi/loop_disabled.png deleted file mode 100644 index 0f7db5d681..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_disabled.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_disconnected.png b/app/src/main/res/drawable-xhdpi/loop_disconnected.png deleted file mode 100644 index 7db5047b9f..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_disconnected.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_lgs.png b/app/src/main/res/drawable-xhdpi/loop_lgs.png deleted file mode 100644 index baa073ac8c..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_lgs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_open.png b/app/src/main/res/drawable-xhdpi/loop_open.png deleted file mode 100644 index 55726849d0..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_paused.png b/app/src/main/res/drawable-xhdpi/loop_paused.png deleted file mode 100644 index 399ec449bc..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_paused.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/loop_superbolus.png b/app/src/main/res/drawable-xhdpi/loop_superbolus.png deleted file mode 100644 index 8bcf96248b..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/loop_superbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xhdpi/soso.png b/app/src/main/res/drawable-xhdpi/soso.png deleted file mode 100644 index 8e19db274b..0000000000 Binary files a/app/src/main/res/drawable-xhdpi/soso.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi-v11/ic_settings.png b/app/src/main/res/drawable-xxhdpi-v11/ic_settings.png deleted file mode 100644 index 4130b7aa9f..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi-v11/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi-v9/ic_settings.png b/app/src/main/res/drawable-xxhdpi-v9/ic_settings.png deleted file mode 100644 index 4f61e7d059..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi-v9/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/bad.png b/app/src/main/res/drawable-xxhdpi/bad.png deleted file mode 100644 index b7a3201d60..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/bad.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/good.png b/app/src/main/res/drawable-xxhdpi/good.png deleted file mode 100644 index 9f5c243b04..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/good.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_error.png b/app/src/main/res/drawable-xxhdpi/ic_error.png deleted file mode 100644 index cf389b5d96..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_error.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_exit_to_app.png b/app/src/main/res/drawable-xxhdpi/ic_exit_to_app.png deleted file mode 100644 index 884eb3b242..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_exit_to_app.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_maintenance.png b/app/src/main/res/drawable-xxhdpi/ic_maintenance.png deleted file mode 100644 index 952e7b9ef3..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_maintenance.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_notif_aaps.png b/app/src/main/res/drawable-xxhdpi/ic_notif_aaps.png deleted file mode 100644 index 6ef4df1823..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_notif_aaps.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_notif_nsclient.png b/app/src/main/res/drawable-xxhdpi/ic_notif_nsclient.png deleted file mode 100644 index ce7eb909ff..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_notif_nsclient.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_notif_pumpcontrol.png b/app/src/main/res/drawable-xxhdpi/ic_notif_pumpcontrol.png deleted file mode 100644 index 12bf9fd364..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_notif_pumpcontrol.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_reminder.png b/app/src/main/res/drawable-xxhdpi/ic_reminder.png deleted file mode 100644 index e918305ba0..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_reminder.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_settings.png b/app/src/main/res/drawable-xxhdpi/ic_settings.png deleted file mode 100644 index 8f3d91a45a..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_settings.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_visibility.png b/app/src/main/res/drawable-xxhdpi/ic_visibility.png deleted file mode 100644 index dbc192368f..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_visibility.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_warning.png b/app/src/main/res/drawable-xxhdpi/ic_warning.png deleted file mode 100644 index 7ab70f77c2..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/ic_warning.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_cancelextbolus.png b/app/src/main/res/drawable-xxhdpi/icon_actions_cancelextbolus.png deleted file mode 100644 index d223d16d8f..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_profileswitch.png b/app/src/main/res/drawable-xxhdpi/icon_actions_profileswitch.png deleted file mode 100644 index 29e28afe02..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_refill.png b/app/src/main/res/drawable-xxhdpi/icon_actions_refill.png deleted file mode 100644 index 45cc5d3e1a..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_startextbolus.png b/app/src/main/res/drawable-xxhdpi/icon_actions_startextbolus.png deleted file mode 100644 index e33b5e0a64..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_starttempbasal.png b/app/src/main/res/drawable-xxhdpi/icon_actions_starttempbasal.png deleted file mode 100644 index 9e4aca67e2..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_actions_temptarget.png b/app/src/main/res/drawable-xxhdpi/icon_actions_temptarget.png deleted file mode 100644 index 4fa88421ae..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_bolus.png b/app/src/main/res/drawable-xxhdpi/icon_bolus.png deleted file mode 100644 index efa063d54d..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_calculator.png b/app/src/main/res/drawable-xxhdpi/icon_calculator.png deleted file mode 100644 index 18ab99e92b..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_calibration.png b/app/src/main/res/drawable-xxhdpi/icon_calibration.png deleted file mode 100644 index 3fd492a623..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cancelbasal.png b/app/src/main/res/drawable-xxhdpi/icon_cancelbasal.png deleted file mode 100644 index 2bb5d6df09..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_aaps_offline.png b/app/src/main/res/drawable-xxhdpi/icon_cp_aaps_offline.png deleted file mode 100644 index 1b4603bafc..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_age_battery.png b/app/src/main/res/drawable-xxhdpi/icon_cp_age_battery.png deleted file mode 100644 index d32a7791e1..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_age_canula.png b/app/src/main/res/drawable-xxhdpi/icon_cp_age_canula.png deleted file mode 100644 index 715682129b..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_age_insulin.png b/app/src/main/res/drawable-xxhdpi/icon_cp_age_insulin.png deleted file mode 100644 index 79a21cea45..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_age_sensor.png b/app/src/main/res/drawable-xxhdpi/icon_cp_age_sensor.png deleted file mode 100644 index bb269c3af9..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_announcement.png b/app/src/main/res/drawable-xxhdpi/icon_cp_announcement.png deleted file mode 100644 index e287fa15d4..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_basal_end.png b/app/src/main/res/drawable-xxhdpi/icon_cp_basal_end.png deleted file mode 100644 index 08acae3012..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_basal_start.png b/app/src/main/res/drawable-xxhdpi/icon_cp_basal_start.png deleted file mode 100644 index 1b6d970b95..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bgcheck.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bgcheck.png deleted file mode 100644 index 4e68c25d70..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_carbs.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_carbs.png deleted file mode 100644 index a110276120..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_combo.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_combo.png deleted file mode 100644 index c91b515001..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_correction.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_correction.png deleted file mode 100644 index d0c7a40613..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_meal.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_meal.png deleted file mode 100644 index e13a420bad..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_snack.png b/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_snack.png deleted file mode 100644 index 6a9fb42088..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_insert.png b/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_insert.png deleted file mode 100644 index f1a791b702..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_profile.png b/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_profile.png deleted file mode 100644 index d40cba3c46..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_start.png b/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_start.png deleted file mode 100644 index 47d5de66a1..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_target.png b/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_target.png deleted file mode 100644 index 13fc303aa2..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_exercise.png b/app/src/main/res/drawable-xxhdpi/icon_cp_exercise.png deleted file mode 100644 index 4fb54d3703..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_note.png b/app/src/main/res/drawable-xxhdpi/icon_cp_note.png deleted file mode 100644 index c1881112b7..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_battery.png b/app/src/main/res/drawable-xxhdpi/icon_cp_pump_battery.png deleted file mode 100644 index 1a6d44bba0..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_canula.png b/app/src/main/res/drawable-xxhdpi/icon_cp_pump_canula.png deleted file mode 100644 index 6021f928ed..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_cartridge.png b/app/src/main/res/drawable-xxhdpi/icon_cp_pump_cartridge.png deleted file mode 100644 index c7a8897a52..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_cp_question.png b/app/src/main/res/drawable-xxhdpi/icon_cp_question.png deleted file mode 100644 index 09455d09fd..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_danar_useroptxxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_danar_useroptxxhdpi.png deleted file mode 100644 index b2a8eb9313..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_danar_useroptxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_danarhistory.png b/app/src/main/res/drawable-xxhdpi/icon_danarhistory.png deleted file mode 100644 index dcd00419a3..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_danarhistory.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_danarprofile.png b/app/src/main/res/drawable-xxhdpi/icon_danarprofile.png deleted file mode 100644 index 7da3c045fe..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_danarprofile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_danarstats.png b/app/src/main/res/drawable-xxhdpi/icon_danarstats.png deleted file mode 100644 index 254623e213..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_danarstats.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_home_loop.png b/app/src/main/res/drawable-xxhdpi/icon_home_loop.png deleted file mode 100644 index c33f090311..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_home_profile.png b/app/src/main/res/drawable-xxhdpi/icon_home_profile.png deleted file mode 100644 index 00c4de023a..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_activate.png b/app/src/main/res/drawable-xxhdpi/icon_local_activate.png deleted file mode 100644 index 600e6ee61c..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_activate.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png deleted file mode 100644 index 600e6ee61c..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_activatexxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_reset.png b/app/src/main/res/drawable-xxhdpi/icon_local_reset.png deleted file mode 100644 index dc9d659dd7..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_reset.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_resetxxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_local_resetxxhdpi.png deleted file mode 100644 index dc9d659dd7..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_resetxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_save.png b/app/src/main/res/drawable-xxhdpi/icon_local_save.png deleted file mode 100644 index 20448e4bf9..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_save.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png b/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png deleted file mode 100644 index 20448e4bf9..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_local_savexxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_quickwizard.png b/app/src/main/res/drawable-xxhdpi/icon_quickwizard.png deleted file mode 100644 index 9f2c9c9350..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/icon_xdrip.png b/app/src/main/res/drawable-xxhdpi/icon_xdrip.png deleted file mode 100644 index c375417b1c..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/icon_xdrip.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_closed.png b/app/src/main/res/drawable-xxhdpi/loop_closed.png deleted file mode 100644 index 5418ef1e7e..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_closed.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_disabled.png b/app/src/main/res/drawable-xxhdpi/loop_disabled.png deleted file mode 100644 index 580dc5a5f5..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_disabled.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_disconnected.png b/app/src/main/res/drawable-xxhdpi/loop_disconnected.png deleted file mode 100644 index 6e991f8ebf..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_disconnected.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_lgs.png b/app/src/main/res/drawable-xxhdpi/loop_lgs.png deleted file mode 100644 index 86b4910f33..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_lgs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_open.png b/app/src/main/res/drawable-xxhdpi/loop_open.png deleted file mode 100644 index 1d35a9c987..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_paused.png b/app/src/main/res/drawable-xxhdpi/loop_paused.png deleted file mode 100644 index 6db561b858..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_paused.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_superbolus.png b/app/src/main/res/drawable-xxhdpi/loop_superbolus.png deleted file mode 100644 index c5187cf95d..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/loop_superbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxhdpi/soso.png b/app/src/main/res/drawable-xxhdpi/soso.png deleted file mode 100644 index 6caac0cc05..0000000000 Binary files a/app/src/main/res/drawable-xxhdpi/soso.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/bad.png b/app/src/main/res/drawable-xxxhdpi/bad.png deleted file mode 100644 index 484bd8fd0b..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/bad.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/good.png b/app/src/main/res/drawable-xxxhdpi/good.png deleted file mode 100644 index eb81a2b978..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/good.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_error.png b/app/src/main/res/drawable-xxxhdpi/ic_error.png deleted file mode 100644 index b8743474f7..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_error.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_exit_to_app.png b/app/src/main/res/drawable-xxxhdpi/ic_exit_to_app.png deleted file mode 100644 index 903a7230fd..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_exit_to_app.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_maintenance.png b/app/src/main/res/drawable-xxxhdpi/ic_maintenance.png deleted file mode 100644 index 1046459dc3..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_maintenance.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_reminder.png b/app/src/main/res/drawable-xxxhdpi/ic_reminder.png deleted file mode 100644 index 6aa4e934d0..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_reminder.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_visibility.png b/app/src/main/res/drawable-xxxhdpi/ic_visibility.png deleted file mode 100644 index 882eacdee5..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_visibility.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/ic_warning.png b/app/src/main/res/drawable-xxxhdpi/ic_warning.png deleted file mode 100644 index 607e14b7d2..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/ic_warning.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_cancelextbolus.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_cancelextbolus.png deleted file mode 100644 index f5b57a9bc9..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_profileswitch.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_profileswitch.png deleted file mode 100644 index d5631ef3ae..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_refill.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_refill.png deleted file mode 100644 index be3a5db708..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_startextbolus.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_startextbolus.png deleted file mode 100644 index 89b44ea201..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_starttempbasal.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_starttempbasal.png deleted file mode 100644 index 7be2e32dfe..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_actions_temptarget.png b/app/src/main/res/drawable-xxxhdpi/icon_actions_temptarget.png deleted file mode 100644 index 955a19f3bc..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_bolus.png b/app/src/main/res/drawable-xxxhdpi/icon_bolus.png deleted file mode 100644 index b4c4fb8559..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_calculator.png b/app/src/main/res/drawable-xxxhdpi/icon_calculator.png deleted file mode 100644 index 90c8fab919..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_calibration.png b/app/src/main/res/drawable-xxxhdpi/icon_calibration.png deleted file mode 100644 index 82eb93205e..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cancelbasal.png b/app/src/main/res/drawable-xxxhdpi/icon_cancelbasal.png deleted file mode 100644 index cd66d14c4f..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_aaps_offline.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_aaps_offline.png deleted file mode 100644 index 3da8775fb4..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_battery.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_age_battery.png deleted file mode 100644 index dd21ad490c..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_canula.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_age_canula.png deleted file mode 100644 index 6a3585b72f..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_insulin.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_age_insulin.png deleted file mode 100644 index 3b50b616fc..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_sensor.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_age_sensor.png deleted file mode 100644 index 2dd35e6e9e..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_announcement.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_announcement.png deleted file mode 100644 index 256631f49b..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_end.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_end.png deleted file mode 100644 index a57ceb3b8a..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_start.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_start.png deleted file mode 100644 index d36b0b711c..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bgcheck.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bgcheck.png deleted file mode 100644 index fa72b549a9..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_carbs.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_carbs.png deleted file mode 100644 index 4dab75558b..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_combo.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_combo.png deleted file mode 100644 index 1418ea4994..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_correction.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_correction.png deleted file mode 100644 index ccc3d0e39c..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_meal.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_meal.png deleted file mode 100644 index aa7bdf7fe3..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_snack.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_snack.png deleted file mode 100644 index 1f9ab1697d..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_insert.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_insert.png deleted file mode 100644 index 2d7e6b4542..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_profile.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_profile.png deleted file mode 100644 index e8b4668b86..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_start.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_start.png deleted file mode 100644 index e8d0e6773e..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_target.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_target.png deleted file mode 100644 index 2bdaf7d73d..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_exercise.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_exercise.png deleted file mode 100644 index c16560e8de..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_note.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_note.png deleted file mode 100644 index dd1e04b419..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_battery.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_battery.png deleted file mode 100644 index f1d306de12..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_canula.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_canula.png deleted file mode 100644 index 465111a6ba..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_cartridge.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_cartridge.png deleted file mode 100644 index afffd90482..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_cp_question.png b/app/src/main/res/drawable-xxxhdpi/icon_cp_question.png deleted file mode 100644 index b2e19c1575..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_danar_useroptxxxhdpi.png b/app/src/main/res/drawable-xxxhdpi/icon_danar_useroptxxxhdpi.png deleted file mode 100644 index 52f952ced4..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_danar_useroptxxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_danarhistory.png b/app/src/main/res/drawable-xxxhdpi/icon_danarhistory.png deleted file mode 100644 index 1f37071514..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_danarhistory.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_danarprofile.png b/app/src/main/res/drawable-xxxhdpi/icon_danarprofile.png deleted file mode 100644 index ae1d615a33..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_danarprofile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_danarstats.png b/app/src/main/res/drawable-xxxhdpi/icon_danarstats.png deleted file mode 100644 index d147295d62..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_danarstats.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_home_loop.png b/app/src/main/res/drawable-xxxhdpi/icon_home_loop.png deleted file mode 100644 index a59d73e2b4..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_home_profile.png b/app/src/main/res/drawable-xxxhdpi/icon_home_profile.png deleted file mode 100644 index 80234a0f75..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_activate.png b/app/src/main/res/drawable-xxxhdpi/icon_local_activate.png deleted file mode 100644 index 2de9ce9d4d..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_activate.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_activatexxxhdpi.png b/app/src/main/res/drawable-xxxhdpi/icon_local_activatexxxhdpi.png deleted file mode 100644 index 2de9ce9d4d..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_activatexxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_reset.png b/app/src/main/res/drawable-xxxhdpi/icon_local_reset.png deleted file mode 100644 index ec54479149..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_reset.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png b/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png deleted file mode 100644 index ec54479149..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_resetxxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_save.png b/app/src/main/res/drawable-xxxhdpi/icon_local_save.png deleted file mode 100644 index f2ecc45ac0..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_save.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_local_savexxxhdpi.png b/app/src/main/res/drawable-xxxhdpi/icon_local_savexxxhdpi.png deleted file mode 100644 index f2ecc45ac0..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_local_savexxxhdpi.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_quickwizard.png b/app/src/main/res/drawable-xxxhdpi/icon_quickwizard.png deleted file mode 100644 index 314b8a98de..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/icon_xdrip.png b/app/src/main/res/drawable-xxxhdpi/icon_xdrip.png deleted file mode 100644 index 2b4b8323b8..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/icon_xdrip.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_closed.png b/app/src/main/res/drawable-xxxhdpi/loop_closed.png deleted file mode 100644 index bd78239462..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_closed.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_disabled.png b/app/src/main/res/drawable-xxxhdpi/loop_disabled.png deleted file mode 100644 index 824d6b9db1..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_disabled.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png b/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png deleted file mode 100644 index 9c451cca88..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_lgs.png b/app/src/main/res/drawable-xxxhdpi/loop_lgs.png deleted file mode 100644 index 80848ff60a..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_lgs.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_open.png b/app/src/main/res/drawable-xxxhdpi/loop_open.png deleted file mode 100644 index f010399a53..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_open.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_paused.png b/app/src/main/res/drawable-xxxhdpi/loop_paused.png deleted file mode 100644 index 36f9bcb5a5..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_paused.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png b/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png deleted file mode 100644 index 018bf70188..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable-xxxhdpi/soso.png b/app/src/main/res/drawable-xxxhdpi/soso.png deleted file mode 100644 index 50b8f3fa5c..0000000000 Binary files a/app/src/main/res/drawable-xxxhdpi/soso.png and /dev/null differ diff --git a/app/src/main/res/drawable/add.png b/app/src/main/res/drawable/add.png deleted file mode 100644 index b25da64672..0000000000 Binary files a/app/src/main/res/drawable/add.png and /dev/null differ diff --git a/app/src/main/res/drawable/anim_carbs.xml b/app/src/main/res/drawable/anim_carbs.xml new file mode 100644 index 0000000000..f3b7c5cc7f --- /dev/null +++ b/app/src/main/res/drawable/anim_carbs.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/app/src/main/res/drawable/as.png b/app/src/main/res/drawable/as.png deleted file mode 100644 index a37e4c3465..0000000000 Binary files a/app/src/main/res/drawable/as.png and /dev/null differ diff --git a/app/src/main/res/drawable/circle.xml b/app/src/main/res/drawable/circle.xml deleted file mode 100644 index 9f5b7f5fab..0000000000 --- a/app/src/main/res/drawable/circle.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/app/src/main/res/drawable/clone.png b/app/src/main/res/drawable/clone.png deleted file mode 100644 index 82fd90cca8..0000000000 Binary files a/app/src/main/res/drawable/clone.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_actions_cancelextbolus.xml b/app/src/main/res/drawable/ic_actions_cancelextbolus.xml new file mode 100644 index 0000000000..913b1b9aeb --- /dev/null +++ b/app/src/main/res/drawable/ic_actions_cancelextbolus.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_actions_profileswitch.xml b/app/src/main/res/drawable/ic_actions_profileswitch.xml new file mode 100644 index 0000000000..31c93c3483 --- /dev/null +++ b/app/src/main/res/drawable/ic_actions_profileswitch.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_actions_startextbolus.xml b/app/src/main/res/drawable/ic_actions_startextbolus.xml new file mode 100644 index 0000000000..6436cad1d7 --- /dev/null +++ b/app/src/main/res/drawable/ic_actions_startextbolus.xml @@ -0,0 +1,9 @@ + + + + diff --git a/app/src/main/res/drawable/ic_actions_starttempbasal.xml b/app/src/main/res/drawable/ic_actions_starttempbasal.xml new file mode 100644 index 0000000000..1b7781daed --- /dev/null +++ b/app/src/main/res/drawable/ic_actions_starttempbasal.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_actions_temptarget.xml b/app/src/main/res/drawable/ic_actions_temptarget.xml new file mode 100644 index 0000000000..5dbd5d8b0c --- /dev/null +++ b/app/src/main/res/drawable/ic_actions_temptarget.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_add.xml b/app/src/main/res/drawable/ic_add.xml new file mode 100644 index 0000000000..d9bfc40f83 --- /dev/null +++ b/app/src/main/res/drawable/ic_add.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_as.xml b/app/src/main/res/drawable/ic_as.xml new file mode 100644 index 0000000000..152a314c2d --- /dev/null +++ b/app/src/main/res/drawable/ic_as.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_auto_delta.xml b/app/src/main/res/drawable/ic_auto_delta.xml new file mode 100644 index 0000000000..9e9eaafd0e --- /dev/null +++ b/app/src/main/res/drawable/ic_auto_delta.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_bolus.xml b/app/src/main/res/drawable/ic_bolus.xml new file mode 100644 index 0000000000..752e99ce35 --- /dev/null +++ b/app/src/main/res/drawable/ic_bolus.xml @@ -0,0 +1,8 @@ + + + diff --git a/app/src/main/res/drawable/ic_calculator.xml b/app/src/main/res/drawable/ic_calculator.xml new file mode 100644 index 0000000000..300e971bf4 --- /dev/null +++ b/app/src/main/res/drawable/ic_calculator.xml @@ -0,0 +1,14 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_calibration.xml b/app/src/main/res/drawable/ic_calibration.xml new file mode 100644 index 0000000000..26511d7cbf --- /dev/null +++ b/app/src/main/res/drawable/ic_calibration.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cancelbasal.xml b/app/src/main/res/drawable/ic_cancelbasal.xml new file mode 100644 index 0000000000..76640a4534 --- /dev/null +++ b/app/src/main/res/drawable/ic_cancelbasal.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_clone.xml b/app/src/main/res/drawable/ic_clone.xml new file mode 100644 index 0000000000..fa8c8e0c51 --- /dev/null +++ b/app/src/main/res/drawable/ic_clone.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_clone_48.xml b/app/src/main/res/drawable/ic_clone_48.xml new file mode 100644 index 0000000000..5156d7525e --- /dev/null +++ b/app/src/main/res/drawable/ic_clone_48.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_aaps_offline.xml b/app/src/main/res/drawable/ic_cp_aaps_offline.xml new file mode 100644 index 0000000000..0b267a6d88 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_aaps_offline.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_cp_age_battery.xml b/app/src/main/res/drawable/ic_cp_age_battery.xml new file mode 100644 index 0000000000..cc36e585a0 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_age_battery.xml @@ -0,0 +1,16 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_age_canula.xml b/app/src/main/res/drawable/ic_cp_age_canula.xml new file mode 100644 index 0000000000..f2578fa72b --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_age_canula.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_age_insulin.xml b/app/src/main/res/drawable/ic_cp_age_insulin.xml new file mode 100644 index 0000000000..701e31cee3 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_age_insulin.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_age_sensor.xml b/app/src/main/res/drawable/ic_cp_age_sensor.xml new file mode 100644 index 0000000000..08134cc20b --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_age_sensor.xml @@ -0,0 +1,21 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cp_announcement.xml b/app/src/main/res/drawable/ic_cp_announcement.xml new file mode 100644 index 0000000000..3799ad551c --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_announcement.xml @@ -0,0 +1,21 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_cp_basal_end.xml b/app/src/main/res/drawable/ic_cp_basal_end.xml new file mode 100644 index 0000000000..76640a4534 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_basal_end.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cp_basal_no_tbr.xml b/app/src/main/res/drawable/ic_cp_basal_no_tbr.xml new file mode 100644 index 0000000000..840a639f9c --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_basal_no_tbr.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_basal_start.xml b/app/src/main/res/drawable/ic_cp_basal_start.xml new file mode 100644 index 0000000000..1b7781daed --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_basal_start.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_basal_tbr_high.xml b/app/src/main/res/drawable/ic_cp_basal_tbr_high.xml new file mode 100644 index 0000000000..1b7781daed --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_basal_tbr_high.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_basal_tbr_low.xml b/app/src/main/res/drawable/ic_cp_basal_tbr_low.xml new file mode 100644 index 0000000000..9f3d94563f --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_basal_tbr_low.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_bgcheck.xml b/app/src/main/res/drawable/ic_cp_bgcheck.xml new file mode 100644 index 0000000000..ecde2d118b --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bgcheck.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cp_bgcheck2.xml b/app/src/main/res/drawable/ic_cp_bgcheck2.xml new file mode 100644 index 0000000000..effce450c8 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bgcheck2.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_carbs.xml b/app/src/main/res/drawable/ic_cp_bolus_carbs.xml new file mode 100644 index 0000000000..e21b236b4e --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_carbs.xml @@ -0,0 +1,8 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_carbs_red.xml b/app/src/main/res/drawable/ic_cp_bolus_carbs_red.xml new file mode 100644 index 0000000000..c6206204cf --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_carbs_red.xml @@ -0,0 +1,8 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_combo.xml b/app/src/main/res/drawable/ic_cp_bolus_combo.xml new file mode 100644 index 0000000000..bc26e74837 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_combo.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_correction.xml b/app/src/main/res/drawable/ic_cp_bolus_correction.xml new file mode 100644 index 0000000000..e14bb7c14f --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_correction.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_meal.xml b/app/src/main/res/drawable/ic_cp_bolus_meal.xml new file mode 100644 index 0000000000..7612513c07 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_meal.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cp_bolus_snack.xml b/app/src/main/res/drawable/ic_cp_bolus_snack.xml new file mode 100644 index 0000000000..7d77c384dd --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_bolus_snack.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_cp_cgm_insert.xml b/app/src/main/res/drawable/ic_cp_cgm_insert.xml new file mode 100644 index 0000000000..30107ac8fe --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_cgm_insert.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_cgm_profile.xml b/app/src/main/res/drawable/ic_cp_cgm_profile.xml new file mode 100644 index 0000000000..31c93c3483 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_cgm_profile.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_cgm_start.xml b/app/src/main/res/drawable/ic_cp_cgm_start.xml new file mode 100644 index 0000000000..df714c4fca --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_cgm_start.xml @@ -0,0 +1,18 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_cp_cgm_target.xml b/app/src/main/res/drawable/ic_cp_cgm_target.xml new file mode 100644 index 0000000000..e708ea5bdd --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_cgm_target.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_exercise.xml b/app/src/main/res/drawable/ic_cp_exercise.xml new file mode 100644 index 0000000000..de04c4ecce --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_exercise.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_note.xml b/app/src/main/res/drawable/ic_cp_note.xml new file mode 100644 index 0000000000..8308aabedf --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_note.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_pump_battery.xml b/app/src/main/res/drawable/ic_cp_pump_battery.xml new file mode 100644 index 0000000000..e83067fded --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_pump_battery.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_pump_canula.xml b/app/src/main/res/drawable/ic_cp_pump_canula.xml new file mode 100644 index 0000000000..b43de7ceaa --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_pump_canula.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_cp_pump_cartridge.xml b/app/src/main/res/drawable/ic_cp_pump_cartridge.xml new file mode 100644 index 0000000000..7ebcbccce6 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_pump_cartridge.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_question.xml b/app/src/main/res/drawable/ic_cp_question.xml new file mode 100644 index 0000000000..fc6d14c656 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_question.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_cp_stats.xml b/app/src/main/res/drawable/ic_cp_stats.xml new file mode 100644 index 0000000000..81b3952eb4 --- /dev/null +++ b/app/src/main/res/drawable/ic_cp_stats.xml @@ -0,0 +1,30 @@ + + + + + + diff --git a/app/src/main/res/drawable/ic_error.xml b/app/src/main/res/drawable/ic_error.xml new file mode 100644 index 0000000000..fe665ee185 --- /dev/null +++ b/app/src/main/res/drawable/ic_error.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_exit_to_app.xml b/app/src/main/res/drawable/ic_exit_to_app.xml new file mode 100644 index 0000000000..37a6c7d058 --- /dev/null +++ b/app/src/main/res/drawable/ic_exit_to_app.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable-anydpi/ic_keyboard_capslock.xml b/app/src/main/res/drawable/ic_keyboard_capslock.xml similarity index 100% rename from app/src/main/res/drawable-anydpi/ic_keyboard_capslock.xml rename to app/src/main/res/drawable/ic_keyboard_capslock.xml diff --git a/app/src/main/res/drawable-anydpi/ic_keyboard_tab.xml b/app/src/main/res/drawable/ic_keyboard_tab.xml similarity index 100% rename from app/src/main/res/drawable-anydpi/ic_keyboard_tab.xml rename to app/src/main/res/drawable/ic_keyboard_tab.xml diff --git a/app/src/main/res/drawable/ic_local_activate.xml b/app/src/main/res/drawable/ic_local_activate.xml new file mode 100644 index 0000000000..905ade57d3 --- /dev/null +++ b/app/src/main/res/drawable/ic_local_activate.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_local_reset.xml b/app/src/main/res/drawable/ic_local_reset.xml new file mode 100644 index 0000000000..07faa6ee4d --- /dev/null +++ b/app/src/main/res/drawable/ic_local_reset.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-anydpi/ic_location_on.xml b/app/src/main/res/drawable/ic_location_on.xml similarity index 100% rename from app/src/main/res/drawable-anydpi/ic_location_on.xml rename to app/src/main/res/drawable/ic_location_on.xml diff --git a/app/src/main/res/drawable/ic_loop_closed.xml b/app/src/main/res/drawable/ic_loop_closed.xml new file mode 100644 index 0000000000..1cb9278a1a --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_closed.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_loop_disabled.xml b/app/src/main/res/drawable/ic_loop_disabled.xml new file mode 100644 index 0000000000..ed79c96429 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_disabled.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_loop_disconnected.xml b/app/src/main/res/drawable/ic_loop_disconnected.xml new file mode 100644 index 0000000000..81450ade17 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_disconnected.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_loop_lgs.xml b/app/src/main/res/drawable/ic_loop_lgs.xml new file mode 100644 index 0000000000..c7b5dcd0b8 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_lgs.xml @@ -0,0 +1,24 @@ + + + + + + + + diff --git a/app/src/main/res/drawable/ic_loop_open.xml b/app/src/main/res/drawable/ic_loop_open.xml new file mode 100644 index 0000000000..3f00a12c23 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_open.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_loop_paused.xml b/app/src/main/res/drawable/ic_loop_paused.xml new file mode 100644 index 0000000000..4b7951d4d0 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_paused.xml @@ -0,0 +1,15 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_loop_superbolus.xml b/app/src/main/res/drawable/ic_loop_superbolus.xml new file mode 100644 index 0000000000..2f94edf2c4 --- /dev/null +++ b/app/src/main/res/drawable/ic_loop_superbolus.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_maintenance.xml b/app/src/main/res/drawable/ic_maintenance.xml new file mode 100644 index 0000000000..7f606d8b44 --- /dev/null +++ b/app/src/main/res/drawable/ic_maintenance.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable-anydpi/ic_network_wifi.xml b/app/src/main/res/drawable/ic_network_wifi.xml similarity index 100% rename from app/src/main/res/drawable-anydpi/ic_network_wifi.xml rename to app/src/main/res/drawable/ic_network_wifi.xml diff --git a/app/src/main/res/drawable/ic_notif_aaps.png b/app/src/main/res/drawable/ic_notif_aaps.png deleted file mode 100644 index 453ed7b382..0000000000 Binary files a/app/src/main/res/drawable/ic_notif_aaps.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_notif_aaps.xml b/app/src/main/res/drawable/ic_notif_aaps.xml new file mode 100644 index 0000000000..a9b241c1f6 --- /dev/null +++ b/app/src/main/res/drawable/ic_notif_aaps.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_notif_nsclient.xml b/app/src/main/res/drawable/ic_notif_nsclient.xml new file mode 100644 index 0000000000..e51e9152c8 --- /dev/null +++ b/app/src/main/res/drawable/ic_notif_nsclient.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable/ic_notif_pumpcontrol.png b/app/src/main/res/drawable/ic_notif_pumpcontrol.png deleted file mode 100644 index 5562fef378..0000000000 Binary files a/app/src/main/res/drawable/ic_notif_pumpcontrol.png and /dev/null differ diff --git a/app/src/main/res/drawable/ic_notif_pumpcontrol.xml b/app/src/main/res/drawable/ic_notif_pumpcontrol.xml new file mode 100644 index 0000000000..db51861565 --- /dev/null +++ b/app/src/main/res/drawable/ic_notif_pumpcontrol.xml @@ -0,0 +1,27 @@ + + + + + + + + + diff --git a/app/src/main/res/drawable-anydpi/ic_notifications.xml b/app/src/main/res/drawable/ic_notifications.xml similarity index 71% rename from app/src/main/res/drawable-anydpi/ic_notifications.xml rename to app/src/main/res/drawable/ic_notifications.xml index b655d741e6..5c8da5df78 100644 --- a/app/src/main/res/drawable-anydpi/ic_notifications.xml +++ b/app/src/main/res/drawable/ic_notifications.xml @@ -1,8 +1,8 @@ + android:width="24dp" + android:height="24dp" + android:viewportWidth="24.0" + android:viewportHeight="24.0"> diff --git a/app/src/main/res/drawable/ic_quickwizard.xml b/app/src/main/res/drawable/ic_quickwizard.xml new file mode 100644 index 0000000000..b2d1f2569b --- /dev/null +++ b/app/src/main/res/drawable/ic_quickwizard.xml @@ -0,0 +1,12 @@ + + + + + + + diff --git a/app/src/main/res/drawable/ic_reminder.xml b/app/src/main/res/drawable/ic_reminder.xml new file mode 100644 index 0000000000..b2d8e7ee7a --- /dev/null +++ b/app/src/main/res/drawable/ic_reminder.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_remove.xml b/app/src/main/res/drawable/ic_remove.xml new file mode 100644 index 0000000000..e5b9715945 --- /dev/null +++ b/app/src/main/res/drawable/ic_remove.xml @@ -0,0 +1,10 @@ + + + diff --git a/app/src/main/res/drawable/ic_settings.xml b/app/src/main/res/drawable/ic_settings.xml new file mode 100644 index 0000000000..8b7d553260 --- /dev/null +++ b/app/src/main/res/drawable/ic_settings.xml @@ -0,0 +1,11 @@ + + + diff --git a/app/src/main/res/drawable/ic_visibility.xml b/app/src/main/res/drawable/ic_visibility.xml new file mode 100644 index 0000000000..de67f3ee84 --- /dev/null +++ b/app/src/main/res/drawable/ic_visibility.xml @@ -0,0 +1,12 @@ + + + + diff --git a/app/src/main/res/drawable/ic_warning.xml b/app/src/main/res/drawable/ic_warning.xml new file mode 100644 index 0000000000..484c065ece --- /dev/null +++ b/app/src/main/res/drawable/ic_warning.xml @@ -0,0 +1,9 @@ + + + diff --git a/app/src/main/res/drawable/ic_x_swap_vert.xml b/app/src/main/res/drawable/ic_x_swap_vert.xml new file mode 100644 index 0000000000..f5182fe7b4 --- /dev/null +++ b/app/src/main/res/drawable/ic_x_swap_vert.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/app/src/main/res/drawable/ic_xdrip.xml b/app/src/main/res/drawable/ic_xdrip.xml new file mode 100644 index 0000000000..54f88823ba --- /dev/null +++ b/app/src/main/res/drawable/ic_xdrip.xml @@ -0,0 +1,8 @@ + + + diff --git a/app/src/main/res/drawable/icon_actions_cancelextbolus.png b/app/src/main/res/drawable/icon_actions_cancelextbolus.png deleted file mode 100644 index 4ad378e374..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_cancelextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_actions_profileswitch.png b/app/src/main/res/drawable/icon_actions_profileswitch.png deleted file mode 100644 index eeae6ccfdb..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_profileswitch.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_actions_refill.png b/app/src/main/res/drawable/icon_actions_refill.png deleted file mode 100644 index 737cca8b00..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_refill.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_actions_startextbolus.png b/app/src/main/res/drawable/icon_actions_startextbolus.png deleted file mode 100644 index 338df773c2..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_startextbolus.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_actions_starttempbasal.png b/app/src/main/res/drawable/icon_actions_starttempbasal.png deleted file mode 100644 index 18fbd8c111..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_starttempbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_actions_temptarget.png b/app/src/main/res/drawable/icon_actions_temptarget.png deleted file mode 100644 index 39170bab37..0000000000 Binary files a/app/src/main/res/drawable/icon_actions_temptarget.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_auto_delta.png b/app/src/main/res/drawable/icon_auto_delta.png deleted file mode 100644 index ddb0930b0b..0000000000 Binary files a/app/src/main/res/drawable/icon_auto_delta.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_bolus.png b/app/src/main/res/drawable/icon_bolus.png deleted file mode 100644 index c083219b45..0000000000 Binary files a/app/src/main/res/drawable/icon_bolus.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_calculator.png b/app/src/main/res/drawable/icon_calculator.png deleted file mode 100644 index 056722a440..0000000000 Binary files a/app/src/main/res/drawable/icon_calculator.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_calibration.png b/app/src/main/res/drawable/icon_calibration.png deleted file mode 100644 index 0929d3690d..0000000000 Binary files a/app/src/main/res/drawable/icon_calibration.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cancelbasal.png b/app/src/main/res/drawable/icon_cancelbasal.png deleted file mode 100644 index c48a20792d..0000000000 Binary files a/app/src/main/res/drawable/icon_cancelbasal.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_aaps_offline.png b/app/src/main/res/drawable/icon_cp_aaps_offline.png deleted file mode 100644 index dc50653883..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_aaps_offline.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_age_battery.png b/app/src/main/res/drawable/icon_cp_age_battery.png deleted file mode 100644 index 6c7fc56139..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_age_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_age_canula.png b/app/src/main/res/drawable/icon_cp_age_canula.png deleted file mode 100644 index 303ad946cd..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_age_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_age_insulin.png b/app/src/main/res/drawable/icon_cp_age_insulin.png deleted file mode 100644 index 5cd8598faa..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_age_insulin.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_age_sensor.png b/app/src/main/res/drawable/icon_cp_age_sensor.png deleted file mode 100644 index d312b6c572..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_age_sensor.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_announcement.png b/app/src/main/res/drawable/icon_cp_announcement.png deleted file mode 100644 index 6e1338ac24..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_announcement.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_basal_end.png b/app/src/main/res/drawable/icon_cp_basal_end.png deleted file mode 100644 index be8474f002..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_basal_end.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_basal_start.png b/app/src/main/res/drawable/icon_cp_basal_start.png deleted file mode 100644 index 34cd31f14b..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_basal_start.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bgcheck.png b/app/src/main/res/drawable/icon_cp_bgcheck.png deleted file mode 100644 index 0cb14c2f57..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bgcheck.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bolus_carbs.png b/app/src/main/res/drawable/icon_cp_bolus_carbs.png deleted file mode 100644 index 561703fb06..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bolus_carbs.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bolus_combo.png b/app/src/main/res/drawable/icon_cp_bolus_combo.png deleted file mode 100644 index ce4d8fb9d3..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bolus_combo.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bolus_correction.png b/app/src/main/res/drawable/icon_cp_bolus_correction.png deleted file mode 100644 index 582472dc92..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bolus_correction.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bolus_meal.png b/app/src/main/res/drawable/icon_cp_bolus_meal.png deleted file mode 100644 index 54b51e126e..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bolus_meal.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_bolus_snack.png b/app/src/main/res/drawable/icon_cp_bolus_snack.png deleted file mode 100644 index b2ba41c27d..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_bolus_snack.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_cgm_insert.png b/app/src/main/res/drawable/icon_cp_cgm_insert.png deleted file mode 100644 index 67c0fb1ba2..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_cgm_insert.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_cgm_profile.png b/app/src/main/res/drawable/icon_cp_cgm_profile.png deleted file mode 100644 index e0f0a15cc8..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_cgm_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_cgm_start.png b/app/src/main/res/drawable/icon_cp_cgm_start.png deleted file mode 100644 index 14a44bc852..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_cgm_start.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_cgm_target.png b/app/src/main/res/drawable/icon_cp_cgm_target.png deleted file mode 100644 index 86ce00442c..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_cgm_target.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_exercise.png b/app/src/main/res/drawable/icon_cp_exercise.png deleted file mode 100644 index 1c92c0ebb5..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_exercise.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_note.png b/app/src/main/res/drawable/icon_cp_note.png deleted file mode 100644 index 7c8663a4fe..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_note.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_pump_battery.png b/app/src/main/res/drawable/icon_cp_pump_battery.png deleted file mode 100644 index f4dab169a8..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_pump_battery.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_pump_canula.png b/app/src/main/res/drawable/icon_cp_pump_canula.png deleted file mode 100644 index ee512c5fef..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_pump_canula.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_pump_cartridge.png b/app/src/main/res/drawable/icon_cp_pump_cartridge.png deleted file mode 100644 index 70a90c596f..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_pump_cartridge.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_cp_question.png b/app/src/main/res/drawable/icon_cp_question.png deleted file mode 100644 index 5d430d9164..0000000000 Binary files a/app/src/main/res/drawable/icon_cp_question.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_danar_useropt.png b/app/src/main/res/drawable/icon_danar_useropt.png deleted file mode 100644 index 1fadcd446b..0000000000 Binary files a/app/src/main/res/drawable/icon_danar_useropt.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_home_loop.png b/app/src/main/res/drawable/icon_home_loop.png deleted file mode 100644 index 5240cc85db..0000000000 Binary files a/app/src/main/res/drawable/icon_home_loop.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_home_profile.png b/app/src/main/res/drawable/icon_home_profile.png deleted file mode 100644 index f689df10c6..0000000000 Binary files a/app/src/main/res/drawable/icon_home_profile.png and /dev/null differ diff --git a/app/src/main/res/drawable/icon_insulin_carbs.xml b/app/src/main/res/drawable/icon_insulin_carbs.xml index 6dcd511598..5268a2eb70 100644 --- a/app/src/main/res/drawable/icon_insulin_carbs.xml +++ b/app/src/main/res/drawable/icon_insulin_carbs.xml @@ -1,5 +1,5 @@ - - + + \ No newline at end of file diff --git a/app/src/main/res/drawable/icon_quickwizard.png b/app/src/main/res/drawable/icon_quickwizard.png deleted file mode 100644 index d65347f235..0000000000 Binary files a/app/src/main/res/drawable/icon_quickwizard.png and /dev/null differ diff --git a/app/src/main/res/drawable/notif_icon2.xml b/app/src/main/res/drawable/notif_icon2.xml new file mode 100644 index 0000000000..c36ee9e75c --- /dev/null +++ b/app/src/main/res/drawable/notif_icon2.xml @@ -0,0 +1,13 @@ + + + + diff --git a/app/src/main/res/drawable/remove.png b/app/src/main/res/drawable/remove.png deleted file mode 100644 index 835575cea2..0000000000 Binary files a/app/src/main/res/drawable/remove.png and /dev/null differ diff --git a/app/src/main/res/layout/actions_fragment.xml b/app/src/main/res/layout/actions_fragment.xml index 77a5ab00dd..ebb517dcb7 100644 --- a/app/src/main/res/layout/actions_fragment.xml +++ b/app/src/main/res/layout/actions_fragment.xml @@ -30,7 +30,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_actions_profileswitch" + android:drawableTop="@drawable/ic_actions_profileswitch" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/careportal_profileswitch" @@ -45,7 +45,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_actions_temptarget" + android:drawableTop="@drawable/ic_actions_temptarget" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/careportal_temporarytarget" @@ -60,7 +60,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_actions_starttempbasal" + android:drawableTop="@drawable/ic_actions_starttempbasal" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/overview_tempbasal_button" @@ -75,7 +75,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_cancelbasal" + android:drawableTop="@drawable/ic_cancelbasal" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/canceltemp" @@ -91,7 +91,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_actions_startextbolus" + android:drawableTop="@drawable/ic_actions_startextbolus" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/overview_extendedbolus_button" @@ -106,7 +106,7 @@ style="@style/ButtonSmallFontStyle" android:layout_width="0dp" android:layout_height="wrap_content" - android:drawableTop="@drawable/icon_actions_cancelextbolus" + android:drawableTop="@drawable/ic_actions_cancelextbolus" android:paddingLeft="0dp" android:paddingRight="0dp" android:text="@string/overview_extendedbolus_cancel_button" @@ -126,6 +126,13 @@ android:paddingEnd="15dp" android:text="@string/careportal" /> + + - + - + + + + app:layout_row="6" /> + app:layout_row="6" /> diff --git a/app/src/main/res/layout/activity_profilehelper.xml b/app/src/main/res/layout/activity_profilehelper.xml new file mode 100644 index 0000000000..310a4c566d --- /dev/null +++ b/app/src/main/res/layout/activity_profilehelper.xml @@ -0,0 +1,262 @@ + + + + + +