diff --git a/app/build.gradle b/app/build.gradle index fe6ce65442..20c70ab9b6 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -25,12 +25,10 @@ jacoco { } ext { - ormLiteVersion = "4.46" powermockVersion = "1.7.3" dexmakerVersion = "1.2" retrofit2Version = '2.8.1' - okhttp3Version = '4.5.0' - coroutinesVersion = '1.3.5' + okhttp3Version = '4.6.0' } @@ -160,6 +158,7 @@ android { } firebaseDisable { System.setProperty("disableFirebase", "true") + ext.enableCrashlytics = false } } productFlavors { @@ -242,12 +241,14 @@ allprojects { dependencies { wearApp project(':wear') + implementation project(':core') + 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.3.0' - implementation 'com.google.firebase:firebase-auth:19.3.0' - implementation 'com.google.firebase:firebase-database:19.2.1' + implementation 'com.google.firebase:firebase-core:17.4.0' + 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; } @@ -260,7 +261,10 @@ dependencies { implementation 'androidx.recyclerview:recyclerview:1.1.0' implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'androidx.percentlayout:percentlayout:1.0.0' - implementation "androidx.preference:preference-ktx:1.1.0" + implementation "androidx.preference:preference-ktx:1.1.1" + implementation "androidx.activity:activity:${activityVersion}" + implementation "androidx.activity:activity-ktx:${activityVersion}" + implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.android.material:material:1.1.0' implementation 'com.wdullaer:materialdatetimepicker:4.2.3' @@ -271,12 +275,11 @@ dependencies { implementation("com.github.tony19:logback-android-classic:1.1.1-6") { exclude group: "com.google.android", module: "android" } - implementation "org.apache.commons:commons-lang3:3.9" + implementation 'org.apache.commons:commons-lang3:3.10' implementation 'org.slf4j:slf4j-api:1.7.30' // Graphview cannot be upgraded implementation "com.jjoe64:graphview:4.0.1" implementation "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2" - implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.madgag.spongycastle:core:1.58.0.0' implementation(name: "com.atech-software.android.library.wizardpager-1.1.1", ext: "aar") @@ -288,28 +291,28 @@ dependencies { exclude group: "org.json", module: "json" } implementation "com.google.code.gson:gson:2.8.6" - implementation ("com.google.guava:guava:24.1-jre") { + implementation('com.google.guava:guava:29.0-jre') { exclude group: "com.google.code.findbugs", module: "jsr305" } implementation 'com.google.code.findbugs:jsr305:3.0.2' - implementation "net.danlew:android.joda:2.10.3" + implementation 'net.danlew:android.joda:2.10.6' - implementation 'org.mozilla:rhino:1.7.11' + implementation 'org.mozilla:rhino:1.7.12' implementation 'com.github.DavidProdinger:weekdays-selector:1.1.0' implementation 'com.github.kenglxn.QRGen:android:2.6.0' implementation 'com.eatthepath:java-otp:0.2.0' - testImplementation "junit:junit:4.12" + testImplementation "junit:junit:4.13" testImplementation "org.json:json:20190722" testImplementation "org.mockito:mockito-core:2.8.47" testImplementation "org.powermock:powermock-api-mockito2:${powermockVersion}" testImplementation "org.powermock:powermock-module-junit4-rule-agent:${powermockVersion}" testImplementation "org.powermock:powermock-module-junit4-rule:${powermockVersion}" testImplementation "org.powermock:powermock-module-junit4:${powermockVersion}" - testImplementation "joda-time:joda-time:2.10.5" + testImplementation 'joda-time:joda-time:2.10.6' testImplementation('com.google.truth:truth:1.0.1') { exclude group: "com.google.guava", module: "guava" exclude group: "com.google.code.findbugs", module: "jsr305" @@ -330,24 +333,24 @@ dependencies { implementation "com.squareup.retrofit2:converter-gson:$retrofit2Version" // Phone checker - implementation 'com.scottyab:rootbeer-lib:0.0.7' + 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-alpha03' + androidTestImplementation 'androidx.test:rules:1.3.0-beta01' androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.2' /* Dagger2 - We are going to use dagger.android which includes * support for Activity and fragment injection so we need to include * the following dependencies */ - implementation 'com.google.dagger:dagger-android:2.25.2' - implementation 'com.google.dagger:dagger-android-support:2.25.2' - annotationProcessor 'com.google.dagger:dagger-compiler:2.25.2' - annotationProcessor 'com.google.dagger:dagger-android-processor:2.25.2' - kapt 'com.google.dagger:dagger-android-processor:2.25.2' + implementation "com.google.dagger:dagger-android:$dagger_version" + implementation "com.google.dagger:dagger-android-support:$dagger_version" + annotationProcessor "com.google.dagger:dagger-compiler:$dagger_version" + annotationProcessor "com.google.dagger:dagger-android-processor:$dagger_version" + kapt "com.google.dagger:dagger-android-processor:$dagger_version" /* Dagger2 - default dependency */ - kapt 'com.google.dagger:dagger-compiler:2.25.2' + kapt "com.google.dagger:dagger-compiler:$dagger_version" androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0' } diff --git a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt index a327989975..9158c5f119 100644 --- a/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt +++ b/app/src/androidTest/java/info/nightscout/androidaps/RealPumpTest.kt @@ -8,11 +8,10 @@ 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 @@ -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 diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index c2724241a1..d2d419b0c0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -82,6 +82,7 @@ + @@ -302,6 +303,17 @@ + + + + + + + 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 778d2cf985..c78aaedaf5 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/MainActivity.kt @@ -41,11 +41,12 @@ 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.ConstraintChecker +import info.nightscout.androidaps.plugins.constraints.signatureVerifier.SignatureVerifierPlugin import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils import info.nightscout.androidaps.plugins.general.nsclient.data.NSSettingsStatus import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.setupwizard.SetupWizardActivity -import info.nightscout.androidaps.utils.tabs.TabPageAdapter import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.LocaleHelper @@ -53,11 +54,15 @@ 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.protection.ProtectionCheck +import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.tabs.TabPageAdapter +import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.activity_main.* +import java.util.* import javax.inject.Inject import kotlin.system.exitProcess @@ -77,6 +82,10 @@ class MainActivity : NoSplashAppCompatActivity() { @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var protectionCheck: ProtectionCheck + @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 @@ -107,7 +116,7 @@ class MainActivity : NoSplashAppCompatActivity() { //Check here if loop plugin is disabled. Else check via constraints if (!loopPlugin.isEnabled(PluginType.LOOP)) versionCheckerUtils.triggerCheckVersion() - fabricPrivacy.setUserStats() + setUserStats() setupViews() disposable.add(rxBus .toObservable(EventRebuildTabs::class.java) @@ -129,7 +138,7 @@ class MainActivity : NoSplashAppCompatActivity() { } androidPermission.notifyForStoragePermission(this) androidPermission.notifyForBatteryOptimizationPermission(this) - if (Config.PUMPDRIVERS) { + if (config.PUMPDRIVERS) { androidPermission.notifyForLocationPermissions(this) androidPermission.notifyForSMSPermissions(this, smsCommunicatorPlugin) androidPermission.notifyForSystemWindowPermissions(this) @@ -153,12 +162,9 @@ class MainActivity : NoSplashAppCompatActivity() { override fun onResume() { super.onResume() protectionCheck.queryProtection(this, ProtectionCheck.Protection.APPLICATION, null, - Runnable { - OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) - }, - Runnable { - OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) - }) + UIRunnable(Runnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) }), + UIRunnable(Runnable { OKDialog.show(this, "", resourceHelper.gs(R.string.authorizationfailed), Runnable { finish() }) }) + ) } private fun setWakeLock() { @@ -190,6 +196,7 @@ class MainActivity : NoSplashAppCompatActivity() { } } main_pager.adapter = pageAdapter + main_pager.offscreenPageLimit = 8 // This may cause more memory consumption checkPluginPreferences(main_pager) // Tabs @@ -283,7 +290,7 @@ class MainActivity : NoSplashAppCompatActivity() { Linkify.addLinks(messageSpanned, Linkify.WEB_URLS) AlertDialog.Builder(this) .setTitle(resourceHelper.gs(R.string.app_name) + " " + BuildConfig.VERSION) - .setIcon(resourceHelper.getIcon()) + .setIcon(iconsProvider.getIcon()) .setMessage(messageSpanned) .setPositiveButton(resourceHelper.gs(R.string.ok), null) .create().also { @@ -323,4 +330,35 @@ class MainActivity : NoSplashAppCompatActivity() { } return actionBarDrawerToggle.onOptionsItemSelected(item) } + + // Correct place for calling setUserStats() would be probably MainApp + // but we need to have it called at least once a day. Thus this location + + private fun setUserStats() { + if (!fabricPrivacy.fabricEnabled()) return + val closedLoopEnabled = if (constraintChecker.isClosedLoopAllowed().value()) "CLOSED_LOOP_ENABLED" else "CLOSED_LOOP_DISABLED" + // Size is limited to 36 chars + val remote = BuildConfig.REMOTE.toLowerCase(Locale.getDefault()) + .replace("https://", "") + .replace("http://", "") + .replace(".git", "") + .replace(".com/", ":") + .replace(".org/", ":") + .replace(".net/", ":") + fabricPrivacy.firebaseAnalytics.setUserProperty("Mode", BuildConfig.APPLICATION_ID + "-" + closedLoopEnabled) + fabricPrivacy.firebaseAnalytics.setUserProperty("Language", sp.getString(R.string.key_language, Locale.getDefault().language)) + fabricPrivacy.firebaseAnalytics.setUserProperty("Version", BuildConfig.VERSION) + fabricPrivacy.firebaseAnalytics.setUserProperty("HEAD", BuildConfig.HEAD) + fabricPrivacy.firebaseAnalytics.setUserProperty("Remote", remote) + 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) + 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) + activePlugin.activeSensitivity.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Sensitivity", it::class.java.simpleName) } + activePlugin.activeInsulin.let { fabricPrivacy.firebaseAnalytics.setUserProperty("Insulin", it::class.java.simpleName) } + } + } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/MainApp.java b/app/src/main/java/info/nightscout/androidaps/MainApp.java index 66acee4016..85d8f83ed7 100644 --- a/app/src/main/java/info/nightscout/androidaps/MainApp.java +++ b/app/src/main/java/info/nightscout/androidaps/MainApp.java @@ -14,14 +14,19 @@ import com.j256.ormlite.android.apptools.OpenHelperManager; import net.danlew.android.joda.JodaTimeAndroid; +import org.jetbrains.annotations.NotNull; + import java.util.List; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DaggerApplication; +import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.DatabaseHelper; +import info.nightscout.androidaps.db.StaticInjector; import info.nightscout.androidaps.dependencyInjection.DaggerAppComponent; +import info.nightscout.androidaps.interfaces.DatabaseHelperInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -40,7 +45,7 @@ import info.nightscout.androidaps.utils.ActivityMonitor; import info.nightscout.androidaps.utils.LocaleHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -public class MainApp extends DaggerApplication { +public class MainApp extends DaggerApplication implements DatabaseHelperInterface { static MainApp sInstance; private static Resources sResources; @@ -57,6 +62,8 @@ public class MainApp extends DaggerApplication { @Inject KeepAliveReceiver.KeepAliveManager keepAliveManager; @Inject List plugins; + @Inject StaticInjector staticInjector; // TODO remove , fake only to initialize + @Override public void onCreate() { super.onCreate(); @@ -166,4 +173,8 @@ public class MainApp extends DaggerApplication { keepAliveManager.cancelAlarm(this); super.onTerminate(); } + + @NotNull @Override public List getAllBgreadingsDataFromTime(long mills, boolean ascending) { + return getDbHelper().getAllBgreadingsDataFromTime(mills, ascending); + } } 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 b06276114d..0b8fc440ca 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/MyPreferenceFragment.kt @@ -22,7 +22,7 @@ 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.interfaces.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 @@ -41,6 +41,7 @@ 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 @@ -66,6 +67,7 @@ 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 @@ -100,6 +102,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 @@ -160,20 +163,20 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang 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(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) @@ -279,7 +282,7 @@ class MyPreferenceFragment : PreferenceFragmentCompat(), OnSharedPreferenceChang } for (plugin in pluginStore.plugins) { - pref?.let { pref-> pref.getKey()?.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/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..ff3e361a9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/SurveyActivity.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.dialogs.ProfileViewerDialog import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.ActivityMonitor import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.InstanceId diff --git a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java index ae337b8e59..1cf80ed1ca 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java +++ b/app/src/main/java/info/nightscout/androidaps/activities/TDDStatsActivity.java @@ -39,7 +39,7 @@ 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.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus; import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; 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 d1c63d284c..abc6df92c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java +++ b/app/src/main/java/info/nightscout/androidaps/db/DatabaseHelper.java @@ -33,7 +33,7 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.data.NonOverlappingIntervals; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.events.EventCareportalEventChange; import info.nightscout.androidaps.events.EventExtendedBolusChange; import info.nightscout.androidaps.events.EventNewBG; @@ -47,10 +47,9 @@ 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.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.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHistoryData; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; @@ -61,6 +60,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.T; import info.nightscout.androidaps.utils.ToastUtils; /** @@ -72,7 +72,7 @@ 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(L.DATABASE); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATABASE); public static final String DATABASE_NAME = "AndroidAPSDb"; public static final String DATABASE_BGREADINGS = "BgReadings"; @@ -82,7 +82,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"; @@ -123,7 +122,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { @Override public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { try { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.info("onCreate"); TableUtils.createTableIfNotExists(connectionSource, TempTarget.class); TableUtils.createTableIfNotExists(connectionSource, BgReading.class); @@ -366,7 +365,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public static long roundDateToSec(long date) { long rounded = date - date % 1000; if (rounded != date) - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Rounding " + date + " to " + rounded); return rounded; } @@ -378,17 +377,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { BgReading old = getDaoBgReadings().queryForId(bgReading.date); if (old == null) { getDaoBgReadings().create(bgReading); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("BG: New record from: " + from + " " + bgReading.toString()); scheduleBgChange(bgReading); return true; } if (!old.isEqual(bgReading)) { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("BG: Similiar found: " + old.toString()); old.copyFrom(bgReading); getDaoBgReadings().update(old); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("BG: Updating record from: " + from + " New data: " + old.toString()); scheduleBgChange(bgReading); return false; @@ -411,7 +410,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleBgChange(@Nullable final BgReading bgReading) { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing EventNewBg"); RxBus.Companion.getINSTANCE().send(new EventNewBG(bgReading)); scheduledBgPost = null; @@ -640,7 +639,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPTARGET: Updating record by date from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; @@ -660,7 +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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPTARGET: Updating record by _id from: " + Source.getString(tempTarget.source) + " " + old.toString()); scheduleTemporaryTargetChange(); return true; @@ -668,14 +667,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoTempTargets().create(tempTarget); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; } if (tempTarget.source == Source.USER) { getDaoTempTargets().create(tempTarget); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPTARGET: New record from: " + Source.getString(tempTarget.source) + " " + tempTarget.toString()); scheduleTemporaryTargetChange(); return true; @@ -698,7 +697,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleTemporaryTargetChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing EventTempTargetChange"); RxBus.Companion.getINSTANCE().send(new EventTempTargetChange()); scheduledTemTargetPost = null; @@ -824,7 +823,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: Already exists from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); return false; } @@ -842,7 +841,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { old.copyFromPump(tempBasal); old.source = Source.PUMP; - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: Updated record with Pump Data : " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); getDaoTemporaryBasal().update(old); @@ -854,7 +853,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); @@ -872,7 +871,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: Updating record by date from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); @@ -895,7 +894,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: Updating record by _id from: " + Source.getString(tempBasal.source) + " " + old.toString()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); @@ -905,7 +904,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); @@ -913,7 +912,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } if (tempBasal.source == Source.USER) { getDaoTemporaryBasal().create(tempBasal); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: New record from: " + Source.getString(tempBasal.source) + " " + tempBasal.toString()); updateEarliestDataChange(tempBasal.date); scheduleTemporaryBasalChange(); @@ -970,7 +969,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleTemporaryBasalChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing EventTempBasalChange"); RxBus.Companion.getINSTANCE().send(new EventReloadTempBasalData()); RxBus.Companion.getINSTANCE().send(new EventTempBasalChange()); @@ -1065,7 +1064,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteTempBasalById(String _id) { TemporaryBasal stored = findTempBasalById(_id); if (stored != null) { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("TEMPBASAL: Removing TempBasal record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); @@ -1120,7 +1119,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public boolean createOrUpdate(ExtendedBolus extendedBolus) { try { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: createOrUpdate: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); ExtendedBolus old; @@ -1145,7 +1144,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } getDaoExtendedBolus().createOrUpdate(extendedBolus); } - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); @@ -1159,7 +1158,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: Updating record by date from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); @@ -1182,7 +1181,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: Updating record by _id from: " + Source.getString(extendedBolus.source) + " " + old.log()); updateEarliestDataChange(oldDate); updateEarliestDataChange(old.date); @@ -1192,7 +1191,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } } getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); @@ -1200,7 +1199,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { } if (extendedBolus.source == Source.USER) { getDaoExtendedBolus().create(extendedBolus); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: New record from: " + Source.getString(extendedBolus.source) + " " + extendedBolus.log()); updateEarliestDataChange(extendedBolus.date); scheduleExtendedBolusChange(); @@ -1249,10 +1248,26 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { return new ArrayList(); } + public List getExtendedBolusDataFromTime(long from, long to, boolean ascending) { + try { + List extendedBoluses; + QueryBuilder queryBuilder = getDaoExtendedBolus().queryBuilder(); + queryBuilder.orderBy("date", ascending); + Where where = queryBuilder.where(); + where.between("date", from, to); + PreparedQuery preparedQuery = queryBuilder.prepare(); + extendedBoluses = getDaoExtendedBolus().query(preparedQuery); + return extendedBoluses; + } catch (SQLException e) { + log.error("Unhandled exception", e); + } + return new ArrayList(); + } + public void deleteExtendedBolusById(String _id) { ExtendedBolus stored = findExtendedBolusById(_id); if (stored != null) { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("EXTENDEDBOLUS: Removing ExtendedBolus record from database: " + stored.toString()); delete(stored); updateEarliestDataChange(stored.date); @@ -1306,7 +1321,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleExtendedBolusChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing EventExtendedBolusChange"); RxBus.Companion.getINSTANCE().send(new EventReloadTreatmentData(new EventExtendedBolusChange())); if (earliestDataChange != null) @@ -1468,11 +1483,11 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 1) { CareportalEvent record = list.get(0); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Removing CareportalEvent record from database: " + record.toString()); delete(record); } else { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("CareportalEvent not found database: " + _id); } } catch (SQLException e) { @@ -1492,12 +1507,12 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { if (list.size() == 0) { careportalEvent = new CareportalEvent(MainApp.instance()); careportalEvent.source = Source.NIGHTSCOUT; - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Adding CareportalEvent record to database: " + trJson.toString()); // Record does not exists. add } else if (list.size() == 1) { careportalEvent = list.get(0); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Updating CareportalEvent record in database: " + trJson.toString()); } else { log.error("Something went wrong"); @@ -1516,7 +1531,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleCareportalEventChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing scheduleCareportalEventChange"); RxBus.Companion.getINSTANCE().send(new EventCareportalEventChange()); scheduledCareportalEventPost = null; @@ -1629,7 +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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("PROFILESWITCH: Updating record by date from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; @@ -1649,7 +1664,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(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("PROFILESWITCH: Updating record by _id from: " + Source.getString(profileSwitch.source) + " " + old.toString()); scheduleProfileSwitchChange(); return true; @@ -1659,14 +1674,14 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // look for already added percentage from NS profileSwitch.profileName = PercentageSplitter.pureName(profileSwitch.profileName); getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; } if (profileSwitch.source == Source.USER) { getDaoProfileSwitch().create(profileSwitch); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("PROFILESWITCH: New record from: " + Source.getString(profileSwitch.source) + " " + profileSwitch.toString()); scheduleProfileSwitchChange(); return true; @@ -1689,7 +1704,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { private static void scheduleProfileSwitchChange() { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Firing EventProfileNeedsUpdate"); RxBus.Companion.getINSTANCE().send(new EventReloadProfileSwitchData()); RxBus.Companion.getINSTANCE().send(new EventProfileNeedsUpdate()); @@ -1741,17 +1756,17 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { Profile profile = store.getSpecificProfile(profileSwitch.profileName); if (profile != null) { profileSwitch.profileJson = profile.getData().toString(); - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Profile switch prefilled with JSON from local store"); // Update data in NS NSUpload.updateProfileSwitch(profileSwitch); } else { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("JSON for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } } else { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("Store for profile switch doesn't exist. Ignoring: " + trJson.toString()); return; } @@ -1767,7 +1782,7 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { public void deleteProfileSwitchById(String _id) { ProfileSwitch stored = findProfileSwitchById(_id); if (stored != null) { - if (L.isEnabled(L.DATABASE)) + if (L.isEnabled(LTag.DATABASE)) log.debug("PROFILESWITCH: Removing ProfileSwitch record from database: " + stored.toString()); delete(stored); scheduleTemporaryTargetChange(); @@ -1886,4 +1901,52 @@ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { 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/dependencyInjection/APSModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/APSModule.kt index d3fef14166..7315329ab2 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 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 e7411ad56b..2f6d515b0e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ActivitiesModule.kt @@ -6,6 +6,7 @@ import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.activities.* import info.nightscout.androidaps.historyBrowser.HistoryBrowseActivity import info.nightscout.androidaps.plugins.general.maintenance.activities.LogSettingActivity +import info.nightscout.androidaps.plugins.general.maintenance.activities.PrefImportListActivity import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizardListActivity import info.nightscout.androidaps.plugins.general.smsCommunicator.activities.SmsCommunicatorOtpActivity import info.nightscout.androidaps.plugins.pump.common.dialog.RileyLinkBLEScanActivity @@ -48,4 +49,5 @@ abstract class ActivitiesModule { @ContributesAndroidInjector abstract fun contributesStatsActivity(): StatsActivity @ContributesAndroidInjector abstract fun contributesSurveyActivity(): SurveyActivity @ContributesAndroidInjector abstract fun contributesTDDStatsActivity(): TDDStatsActivity + @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 91153bd867..1dec3bf9bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppComponent.kt @@ -5,54 +5,14 @@ import dagger.Component import dagger.android.AndroidInjectionModule import dagger.android.AndroidInjector import info.nightscout.androidaps.MainApp -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.dependencyInjection.CoreModule import javax.inject.Singleton @Singleton @Component( modules = [ AndroidInjectionModule::class, + CoreModule::class, ActivitiesModule::class, FragmentsModule::class, AppModule::class, @@ -67,7 +27,8 @@ import javax.inject.Singleton PreferencesModule::class, OverviewModule::class, DataClassesModule::class, - SMSModule::class + SMSModule::class, + UIModule::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 871f88a503..e405ab91fd 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/AppModule.kt @@ -1,88 +1,33 @@ package info.nightscout.androidaps.dependencyInjection import android.content.Context -import androidx.preference.PreferenceManager import dagger.Binds import dagger.Lazy import dagger.Module import dagger.Provides -import dagger.android.ContributesAndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Config import info.nightscout.androidaps.MainApp -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.interfaces.ActivePluginProvider -import info.nightscout.androidaps.interfaces.CommandQueueProvider -import info.nightscout.androidaps.interfaces.PluginBase +import info.nightscout.androidaps.interfaces.* import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.AAPSLoggerProduction -import info.nightscout.androidaps.plugins.aps.loop.APSResult -import info.nightscout.androidaps.plugins.aps.openAPSAMA.DetermineBasalResultAMA -import info.nightscout.androidaps.plugins.aps.logger.LoggerCallback -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalAdapterSMBJS -import info.nightscout.androidaps.plugins.aps.openAPSSMB.DetermineBasalResultSMB 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.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.maintenance.ImportExportPrefs -import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat -import info.nightscout.androidaps.plugins.general.maintenance.formats.EncryptedPrefsFormat -import info.nightscout.androidaps.plugins.general.nsclient.NSUpload -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.plugins.treatments.TreatmentsPlugin 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.CryptoUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import info.nightscout.androidaps.utils.sharedPreferences.SP -import info.nightscout.androidaps.utils.sharedPreferences.SPImplementation import info.nightscout.androidaps.utils.storage.FileStorage import info.nightscout.androidaps.utils.storage.Storage -import info.nightscout.androidaps.utils.wizard.BolusWizard -import info.nightscout.androidaps.utils.wizard.QuickWizardEntry import javax.inject.Singleton -@Module(includes = [AppModule.AppBindings::class, PluginsModule::class]) +@Module(includes = [ + AppModule.AppBindings::class, + PluginsModule::class, + SkinsModule::class +]) open class AppModule { - @Provides - @Singleton - fun provideSharedPreferences(context: Context, resourceHelper: ResourceHelper): SP { - return SPImplementation(PreferenceManager.getDefaultSharedPreferences(context), resourceHelper) - } - @Provides @Singleton fun provideProfileFunction(injector: HasAndroidInjector, aapsLogger: AAPSLogger, sp: SP, resourceHelper: ResourceHelper, activePlugin: ActivePluginProvider, fabricPrivacy: FabricPrivacy): ProfileFunction { @@ -90,35 +35,18 @@ open class AppModule { } @Provides - @Singleton - fun provideResources(mainApp: MainApp): ResourceHelper { - return ResourceHelperImplementation(mainApp) - } - - @Provides - @Singleton - fun provideAAPSLogger(): AAPSLogger { - return AAPSLoggerProduction() -/* if (BuildConfig.DEBUG) { - AAPSLoggerDebug() - } else { - AAPSLoggerProduction() - } - */ - } - - @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() + if (configInterface.NSCLIENT) plugins += nsClient.get() return plugins.toList().sortedBy { it.first }.map { it.second } } @@ -133,11 +61,11 @@ open class AppModule { @Binds fun bindContext(mainApp: MainApp): Context @Binds fun bindInjector(mainApp: MainApp): HasAndroidInjector - - @Binds - fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider - + @Binds fun bindDatabaseHelperInterface(mainApp: MainApp): DatabaseHelperInterface + @Binds fun bindActivePluginProvider(pluginStore: PluginStore): ActivePluginProvider @Binds fun commandQueueProvider(commandQueue: CommandQueue): CommandQueueProvider + @Binds fun configInterfaceProvider(config: Config): ConfigInterface + @Binds fun treatmentInterfaceProvider(treatmentsPlugin: TreatmentsPlugin): TreatmentsInterface } } 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..536454413c 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,14 @@ 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.interfaces.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.plugins.iob.iobCobCalculator.GlucoseStatus -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.plugins.treatments.TreatmentService import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.androidaps.utils.wizard.QuickWizardEntry @@ -23,6 +23,7 @@ abstract class DataClassesModule { @ContributesAndroidInjector abstract fun glucoseStatusInjector(): GlucoseStatus @ContributesAndroidInjector abstract fun profileStoreInjector(): ProfileStore + // TODO move to Core @ContributesAndroidInjector abstract fun bgReadingInjector(): BgReading @ContributesAndroidInjector abstract fun treatmentInjector(): Treatment @ContributesAndroidInjector abstract fun profileSwitchInjector(): ProfileSwitch 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 87129bbb37..f9753fda61 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/FragmentsModule.kt @@ -38,6 +38,7 @@ 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 +import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodFragment import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpFragment import info.nightscout.androidaps.plugins.source.BGSourceFragment import info.nightscout.androidaps.plugins.treatments.TreatmentsFragment @@ -71,6 +72,7 @@ abstract class FragmentsModule { @ContributesAndroidInjector abstract fun contributesLoopFragment(): LoopFragment @ContributesAndroidInjector abstract fun contributesMaintenanceFragment(): MaintenanceFragment @ContributesAndroidInjector abstract fun contributesMedtronicFragment(): MedtronicFragment + @ContributesAndroidInjector abstract fun contributesOmnipodFragment(): OmnipodFragment @ContributesAndroidInjector abstract fun contributesNSProfileFragment(): NSProfileFragment @ContributesAndroidInjector abstract fun contributesNSClientFragment(): NSClientFragment @ContributesAndroidInjector abstract fun contributesSmsCommunicatorFragment(): SmsCommunicatorFragment diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt new file mode 100644 index 0000000000..ccb538dfbd --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/OmnipodModule.kt @@ -0,0 +1,28 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager +import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState +import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodHistoryActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.PodManagementActivity +import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.pages.InitPodRefreshAction +import info.nightscout.androidaps.plugins.pump.omnipod.driver.comm.AapsOmnipodManager +import info.nightscout.androidaps.plugins.pump.omnipod.driver.ui.OmnipodUITask + +@Module +@Suppress("unused") +abstract class OmnipodModule { + + // Activities + @ContributesAndroidInjector abstract fun contributesPodManagementActivity(): PodManagementActivity + @ContributesAndroidInjector abstract fun contributesPodHistoryActivity(): PodHistoryActivity + + @ContributesAndroidInjector abstract fun omnipodCommunicationManagerProvider(): OmnipodCommunicationManager + @ContributesAndroidInjector abstract fun omnipodUITaskProvider(): OmnipodUITask + @ContributesAndroidInjector abstract fun aapsOmnipodManagerProvider(): AapsOmnipodManager + @ContributesAndroidInjector abstract fun initPodRefreshAction(): InitPodRefreshAction + @ContributesAndroidInjector abstract fun podSessionState(): PodSessionState + + +} 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 2861829d7f..de00d631e4 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,9 @@ 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.interfaces.PluginBase import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin import info.nightscout.androidaps.plugins.aps.openAPSAMA.OpenAPSAMAPlugin @@ -45,6 +41,7 @@ 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 +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 diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt index fa2df68ef0..39fb959c15 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/PreferencesModule.kt @@ -3,6 +3,7 @@ package info.nightscout.androidaps.dependencyInjection import dagger.Module import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.general.maintenance.ImportExportPrefs +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider import info.nightscout.androidaps.plugins.general.maintenance.formats.ClassicPrefsFormat import info.nightscout.androidaps.plugins.general.maintenance.formats.EncryptedPrefsFormat import info.nightscout.androidaps.utils.CryptoUtil @@ -15,4 +16,5 @@ abstract class PreferencesModule { @ContributesAndroidInjector abstract fun importExportPrefsInjector(): ImportExportPrefs @ContributesAndroidInjector abstract fun encryptedPrefsFormatInjector(): EncryptedPrefsFormat @ContributesAndroidInjector abstract fun classicPrefsFormatInjector(): ClassicPrefsFormat + @ContributesAndroidInjector abstract fun prefImportListProviderInjector(): PrefFileListProvider } \ 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 c43a8dfb7d..25d102e3ef 100644 --- a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/ServicesModule.kt @@ -15,6 +15,7 @@ import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2Execution 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 +import info.nightscout.androidaps.plugins.pump.omnipod.service.RileyLinkOmnipodService import info.nightscout.androidaps.services.AlarmSoundService import info.nightscout.androidaps.services.DataService import info.nightscout.androidaps.services.LocationService @@ -39,4 +40,5 @@ abstract class ServicesModule { @ContributesAndroidInjector abstract fun contributesInsightConnectionService(): InsightConnectionService @ContributesAndroidInjector abstract fun contributesRileyLinkService(): RileyLinkService @ContributesAndroidInjector abstract fun contributesRileyLinkMedtronicService(): RileyLinkMedtronicService + @ContributesAndroidInjector abstract fun contributesRileyLinkOmnipodService(): RileyLinkOmnipodService } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt new file mode 100644 index 0000000000..ebd4691f38 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/SkinsModule.kt @@ -0,0 +1,30 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Binds +import dagger.Module +import dagger.Provides +import dagger.multibindings.IntKey +import dagger.multibindings.IntoMap +import info.nightscout.androidaps.skins.SkinButtonsOn +import info.nightscout.androidaps.skins.SkinClassic +import info.nightscout.androidaps.skins.SkinInterface +import javax.inject.Qualifier + +@Module +open class SkinsModule { + + @Provides + @Skin + @IntoMap + @IntKey(0) + fun bindsSkinClassic(skinClassic: SkinClassic): SkinInterface = skinClassic + + @Provides + @Skin + @IntoMap + @IntKey(10) + fun bindsSkinButtonsOn(skinButtonsOn: SkinButtonsOn): SkinInterface = skinButtonsOn + + @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 new file mode 100644 index 0000000000..193b46957a --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/dependencyInjection/UIModule.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.dependencyInjection + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.skins.SkinListPreference + +@Module +@Suppress("unused") +abstract class UIModule { + @ContributesAndroidInjector abstract fun skinListPreferenceInjector(): SkinListPreference +} \ 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..28abd8eb60 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 @@ -170,7 +170,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 +184,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 -> 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..1eda2e060e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -15,7 +15,7 @@ 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 @@ -167,7 +167,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) 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/FillDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt index 135eeb0e09..1300ee1612 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -112,7 +112,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 -> 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..f06f563874 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -21,7 +21,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 @@ -145,7 +145,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..72daeb1ad1 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 @@ -98,7 +98,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 index 382e6359a5..9536da6928 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -23,6 +23,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var treatmentsPlugin: TreatmentsPlugin + @Inject lateinit var dateUtil: DateUtil private var time: Long = 0 @@ -67,7 +68,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { Mode.RUNNING_PROFILE -> { profile = treatmentsPlugin.getProfileSwitchFromHistory(time)?.profileObject profileName = treatmentsPlugin.getProfileSwitchFromHistory(time)?.customizedName - date = DateUtil.dateAndTimeString(treatmentsPlugin.getProfileSwitchFromHistory(time)?.date + date = dateUtil.dateAndTimeString(treatmentsPlugin.getProfileSwitchFromHistory(time)?.date ?: 0) profileview_datelayout.visibility = View.VISIBLE } 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..3e6a2c374e 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 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..d2e9c0454f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -14,7 +14,7 @@ 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 @@ -129,7 +129,7 @@ class TempTargetDialog : DialogFragmentWithDate() { 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/WizardDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt index cc3c6c7a98..23ddfcabd1 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 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/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..f59a38d770 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/HistoryBrowseActivity.kt @@ -18,7 +18,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.overview.OverviewMenus import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventAutosensCalculationFinished @@ -54,6 +54,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var overviewMenus: OverviewMenus + @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() @@ -117,7 +118,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { cal.set(Calendar.MONTH, monthOfYear) cal.set(Calendar.DAY_OF_MONTH, dayOfMonth) start = cal.timeInMillis - historybrowse_date?.text = DateUtil.dateAndTimeString(start) + historybrowse_date?.text = dateUtil.dateAndTimeString(start) updateGUI("onClickDate") runCalculation("onClickDate") } @@ -236,7 +237,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { val lowLine = defaultValueHelper.determineLowLine() val highLine = defaultValueHelper.determineHighLine() - historybrowse_date?.text = DateUtil.dateAndTimeString(start) + historybrowse_date?.text = dateUtil.dateAndTimeString(start) historybrowse_zoom?.text = rangeToDisplay.toString() GlobalScope.launch(Dispatchers.Main) { @@ -248,7 +249,7 @@ class HistoryBrowseActivity : NoSplashAppCompatActivity() { 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)) + aapsLogger.debug(LTag.UI, "Period: " + dateUtil.dateAndTimeString(fromTime) + " - " + dateUtil.dateAndTimeString(toTime)) val pointer = System.currentTimeMillis() // **** In range Area **** diff --git a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt index 87276a50a9..4a81820fd7 100644 --- a/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/historyBrowser/IobCobStaticCalculatorPlugin.kt @@ -4,12 +4,13 @@ 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.ProfileFunction +import info.nightscout.androidaps.interfaces.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 @@ -27,9 +28,10 @@ class IobCobStaticCalculatorPlugin @Inject constructor( 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, treatmentsPlugin, sensitivityOref1Plugin, sensitivityAAPSPlugin, sensitivityWeightedAveragePlugin, fabricPrivacy, dateUtil) { override fun onStart() { // do not attach to rxbus } diff --git a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt b/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt deleted file mode 100644 index ba7f88712d..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/logging/AAPSLoggerDebug.kt +++ /dev/null @@ -1,68 +0,0 @@ -package info.nightscout.androidaps.logging - -import android.util.Log - -/** - * Created by adrian on 2019-12-27. - */ - -class AAPSLoggerDebug : AAPSLogger { - - override fun debug(message: String) { - Log.d(LTag.CORE.tag, message) - } - - override fun debug(enable: Boolean, tag: LTag, message: String) { - if (enable) Log.d(LTag.CORE.tag, message) - } - - override fun debug(tag: LTag, message: String) { - Log.d(tag.tag, message) - } - - override fun debug(tag: LTag, format: String, vararg arguments: Any?) { - Log.d(tag.tag, String.format(format, arguments)) - } - - override fun warn(tag: LTag, message: String) { - Log.w(tag.tag, message) - } - - override fun warn(tag: LTag, format: String, vararg arguments: Any?) { - Log.w(tag.tag, String.format(format, arguments)) - } - - override fun info(tag: LTag, message: String) { - Log.i(tag.tag, message) - } - - override fun info(tag: LTag, format: String, vararg arguments: Any?) { - Log.i(tag.tag, String.format(format, arguments)) - } - - override fun error(tag: LTag, message: String) { - Log.e(tag.tag, message) - - } - - override fun error(message: String) { - Log.e(LTag.CORE.tag, message) - } - - override fun error(message: String, throwable: Throwable) { - Log.e(LTag.CORE.tag, message, throwable) - } - - override fun error(format: String, vararg arguments: Any?) { - Log.e(LTag.CORE.tag, String.format(format, arguments)) - } - - override fun error(tag: LTag, message: String, throwable: Throwable) { - Log.e(tag.tag, message, throwable) - - } - - override fun error(tag: LTag, format: String, vararg arguments: Any?) { - Log.e(tag.tag, String.format(format, arguments)) - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/logging/L.kt b/app/src/main/java/info/nightscout/androidaps/logging/L.kt deleted file mode 100644 index 2411e76c5e..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/logging/L.kt +++ /dev/null @@ -1,80 +0,0 @@ -package info.nightscout.androidaps.logging - -import androidx.preference.PreferenceManager -import info.nightscout.androidaps.MainApp -import java.util.* - -object L { - private var logElements: MutableList = ArrayList() - - const val CORE = "CORE" - const val BGSOURCE = "BGSOURCE" - const val DATASERVICE = "DATASERVICE" - const val DATABASE = "DATABASE" - const val DATAFOOD = "DATAFOOD" - const val DATATREATMENTS = "DATATREATMENTS" - const val NSCLIENT = "NSCLIENT" - const val PUMP = "PUMP" - const val PUMPCOMM = "PUMPCOMM" - const val PUMPBTCOMM = "PUMPBTCOMM" - - init { - LTag.values().forEach { logElements.add(LogElement(it)) } - } - - private fun findByName(name: String): LogElement { - for (element in logElements) { - if (element.name == name) return element - } - return LogElement(false) - } - - @JvmStatic - fun isEnabled(name: String): Boolean { - return findByName(name).enabled - } - - fun getLogElements(): List { - return logElements - } - - fun resetToDefaults() { - for (element in logElements) { - element.resetToDefault() - } - } - - class LogElement { - var name: String - var defaultValue: Boolean - var enabled: Boolean - private var requiresRestart = false - - internal constructor(tag: LTag) { - this.name = tag.tag - this.defaultValue = tag.defaultValue - this.requiresRestart = tag.requiresRestart - //TODO: remove after getting rid of old logging style "if (L.isEnabled(...))" - @Suppress("DEPRECATION") - enabled = PreferenceManager.getDefaultSharedPreferences(MainApp.instance()).getBoolean(getSPName(), defaultValue) - } - - internal constructor(defaultValue: Boolean) { - name = "NONEXISTING" - this.defaultValue = defaultValue - enabled = defaultValue - } - - private fun getSPName(): String = "log_$name" - - fun enable(enabled: Boolean) { - this.enabled = enabled - @Suppress("DEPRECATION") - PreferenceManager.getDefaultSharedPreferences(MainApp.instance()).edit().putBoolean(getSPName(), enabled).apply() - } - - fun resetToDefault() { - enable(defaultValue) - } - } -} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java index 42f25cce8f..c8e49d013a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/DeviceStatus.java @@ -3,9 +3,8 @@ package info.nightscout.androidaps.plugins.aps.loop; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; /* @@ -366,7 +365,7 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; */ public class DeviceStatus { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); public String device = null; public JSONObject pump = null; 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 c37c812a98..59a65f4a2c 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 @@ -53,7 +53,7 @@ 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.interfaces.ProfileFunction; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.wear.ActionStringHandler; import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin; 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..6b5f5363b0 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 @@ -31,7 +31,7 @@ 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.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; 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..6da05d9075 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 @@ -30,8 +30,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/configBuilder/PluginStore.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/PluginStore.kt index 35ba1db642..5166248e7d 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) { 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 d891a89dda..1e01d814f6 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 @@ -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()) @@ -212,7 +214,7 @@ class ObjectivesFragment : DaggerFragment() { bundle.putInt("currentTask", taskPosition) dialog.arguments = bundle ObjectivesExamDialog.objective = objective - fragmentManager?.let { dialog.show(it, "ObjectivesFragment") } + dialog.show(childFragmentManager, "ObjectivesFragment") } } // horizontal line @@ -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/phoneChecker/PhoneCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt index 749f7f795c..4ea2d78989 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/phoneChecker/PhoneCheckerPlugin.kt @@ -41,7 +41,7 @@ class PhoneCheckerPlugin @Inject constructor( override fun onStart() { super.onStart() - phoneRooted = RootBeer(context).isRootedWithoutBusyBoxCheck() + phoneRooted = RootBeer(context).isRooted() devMode = isDevModeEnabled() } } \ No newline at end of file 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/constraints/versionChecker/VersionCheckerUtils.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt index d1ce90fc72..636d623bd0 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt @@ -116,6 +116,14 @@ class VersionCheckerUtils @Inject constructor( private fun String?.toNumberList() = this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() } + fun versionDigits(versionString: String?): IntArray { + val digits = mutableListOf() + versionString?.numericVersionPart().toNumberList()?.let { + digits.addAll(it.take(4)) + } + return digits.toIntArray() + } + fun findVersion(file: String?): String? { val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex() return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull() 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 9e80d9d331..f14f7732dd 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 @@ -20,19 +20,20 @@ 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.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction import info.nightscout.androidaps.plugins.general.overview.StatusLightHandler import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.SingleClickButton +import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.extensions.plusAssign -import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.sharedPreferences.SP 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.sharedPreferences.SP +import info.nightscout.androidaps.utils.ui.UIRunnable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.actions_fragment.* @@ -53,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() @@ -68,19 +70,19 @@ class ActionsFragment : DaggerFragment() { super.onViewCreated(view, savedInstanceState) actions_profileswitch.setOnClickListener { - fragmentManager?.let { ProfileSwitchDialog().show(it, "Actions") } + ProfileSwitchDialog().show(childFragmentManager, "Actions") } actions_temptarget.setOnClickListener { - fragmentManager?.let { TempTargetDialog().show(it, "Actions") } + TempTargetDialog().show(childFragmentManager, "Actions") } actions_extendedbolus.setOnClickListener { activity?.let { activity -> - protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { + protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.extended_bolus), resourceHelper.gs(R.string.ebstopsloop), Runnable { - fragmentManager?.let { ExtendedBolusDialog().show(it, "Actions") } + ExtendedBolusDialog().show(childFragmentManager, "Actions") }, null) - }) + })) } } actions_extendedbolus_cancel.setOnClickListener { @@ -101,7 +103,7 @@ class ActionsFragment : DaggerFragment() { } } actions_settempbasal.setOnClickListener { - fragmentManager?.let { TempBasalDialog().show(it, "Actions") } + TempBasalDialog().show(childFragmentManager, "Actions") } actions_canceltempbasal.setOnClickListener { if (activePlugin.activeTreatments.isTempBasalInProgress) { @@ -122,25 +124,25 @@ class ActionsFragment : DaggerFragment() { } actions_fill.setOnClickListener { activity?.let { activity -> - protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { fragmentManager?.let { FillDialog().show(it, "FillDialog") } }) + protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, UIRunnable(Runnable { FillDialog().show(childFragmentManager, "FillDialog") })) } } actions_historybrowser.setOnClickListener { startActivity(Intent(context, HistoryBrowseActivity::class.java)) } actions_tddstats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } actions_bgcheck.setOnClickListener { - fragmentManager?.let { CareDialog().setOptions(CareDialog.EventType.BGCHECK, R.string.careportal_bgcheck).show(it, "Actions") } + CareDialog().setOptions(CareDialog.EventType.BGCHECK, R.string.careportal_bgcheck).show(childFragmentManager, "Actions") } actions_cgmsensorinsert.setOnClickListener { - fragmentManager?.let { CareDialog().setOptions(CareDialog.EventType.SENSOR_INSERT, R.string.careportal_cgmsensorinsert).show(it, "Actions") } + CareDialog().setOptions(CareDialog.EventType.SENSOR_INSERT, R.string.careportal_cgmsensorinsert).show(childFragmentManager, "Actions") } actions_pumpbatterychange.setOnClickListener { - fragmentManager?.let { CareDialog().setOptions(CareDialog.EventType.BATTERY_CHANGE, R.string.careportal_pumpbatterychange).show(it, "Actions") } + CareDialog().setOptions(CareDialog.EventType.BATTERY_CHANGE, R.string.careportal_pumpbatterychange).show(childFragmentManager, "Actions") } actions_note.setOnClickListener { - fragmentManager?.let { CareDialog().setOptions(CareDialog.EventType.NOTE, R.string.careportal_note).show(it, "Actions") } + CareDialog().setOptions(CareDialog.EventType.NOTE, R.string.careportal_note).show(childFragmentManager, "Actions") } actions_exercise.setOnClickListener { - fragmentManager?.let { CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(it, "Actions") } + CareDialog().setOptions(CareDialog.EventType.EXERCISE, R.string.careportal_exercise).show(childFragmentManager, "Actions") } sp.putBoolean(R.string.key_objectiveuseactions, true) @@ -238,7 +240,7 @@ class ActionsFragment : DaggerFragment() { if (!pump.pumpDescription.isRefillingCapable || !pump.isInitialized || pump.isSuspended) View.GONE else View.VISIBLE - actions_temptarget?.visibility = Config.APS.toVisibility() + actions_temptarget?.visibility = 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/AutomationFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt index 4cf73af02f..3e472a9ce9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt @@ -72,7 +72,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { args.putString("event", AutomationEvent(mainApp).toJSON()) args.putInt("position", -1) // New event dialog.arguments = args - fragmentManager?.let { dialog.show(it, "EditEventDialog") } + dialog.show(childFragmentManager, "EditEventDialog") } val callback: ItemTouchHelper.Callback = SimpleItemTouchHelperCallback(eventListAdapter) @@ -182,7 +182,7 @@ class AutomationFragment : DaggerFragment(), OnStartDragListener { args.putString("event", event.toJSON()) args.putInt("position", position) dialog.arguments = args - fragmentManager?.let { dialog.show(it, "EditEventDialog") } + dialog.show(childFragmentManager, "EditEventDialog") } // Start a drag whenever the handle view it touched holder.iconSort.setOnTouchListener { v: View, motionEvent: MotionEvent -> 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..b4f9ec425e 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 @@ -37,7 +37,6 @@ 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 @@ -52,7 +51,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) @@ -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(" ") 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..7a730585c1 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 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..a46796b59d 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 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt index 21a62bc0a5..44929a9dee 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/EditEventDialog.kt @@ -66,15 +66,15 @@ class EditEventDialog : DialogFragmentWithDate() { args.putString("trigger", event.trigger.toJSON()) val dialog = EditTriggerDialog() dialog.arguments = args - fragmentManager?.let { dialog.show(it, "EditTriggerDialog") } + dialog.show(childFragmentManager, "EditTriggerDialog") } // setup action list view - fragmentManager?.let { actionListAdapter = ActionListAdapter() } + actionListAdapter = ActionListAdapter() automation_actionListView.layoutManager = LinearLayoutManager(context) automation_actionListView.adapter = actionListAdapter - automation_addAction.setOnClickListener { fragmentManager?.let { ChooseActionDialog().show(it, "ChooseActionDialog") } } + automation_addAction.setOnClickListener { ChooseActionDialog().show(childFragmentManager, "ChooseActionDialog") } showPreconditions() @@ -187,9 +187,7 @@ class EditEventDialog : DialogFragmentWithDate() { args.putString("action", action.toJSON()) val dialog = EditActionDialog() dialog.arguments = args - fragmentManager?.let { - dialog.show(it, "EditActionDialog") - } + dialog.show(childFragmentManager, "EditActionDialog") } } view.findViewById(R.id.automation_iconTrash).setOnClickListener { 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..f81ef07bb8 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,7 +4,7 @@ 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.interfaces.ProfileFunction import info.nightscout.androidaps.utils.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/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..357e4b462d 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 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..08343a3c94 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,9 +29,9 @@ 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 { @@ -85,7 +87,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..49aeec14ed 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 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 index 613dfeab32..4007e43b45 100644 --- 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 @@ -125,9 +125,7 @@ class CareportalFragment : DaggerFragment(), View.OnClickListener { R.id.careportal_openapsoffline -> newDialog.setOptions(OPENAPSOFFLINE, R.string.careportal_openapsoffline) R.id.careportal_temporarytarget -> newDialog.setOptions(TEMPTARGET, R.string.careportal_temporarytarget) } - fragmentManager?.let { - NewNSTreatmentDialog().show(it, "CareportalFragment") - } + NewNSTreatmentDialog().show(childFragmentManager, "CareportalFragment") } private fun updateGUI() { 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 index e3328aefc9..897f28b0ae 100644 --- 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 @@ -15,14 +15,15 @@ import javax.inject.Singleton class CareportalPlugin @Inject constructor( injector: HasAndroidInjector, aapsLogger: AAPSLogger, - resourceHelper: ResourceHelper + resourceHelper: ResourceHelper, + config: Config ) : 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) + .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 index 0c7dd11e83..8fe577ced3 100644 --- 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 @@ -44,14 +44,14 @@ 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.interfaces.ProfileFunction; +import info.nightscout.androidaps.interfaces.ProfileStore; 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; @@ -61,9 +61,9 @@ 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.alertDialogs.OKDialog; import info.nightscout.androidaps.utils.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; @@ -79,6 +79,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O @Inject TreatmentsPlugin treatmentsPlugin; @Inject HardLimits hardLimits; @Inject Translator translator; + @Inject DateUtil dateUtil; private static OptionsToShow options; private static @StringRes int event; @@ -168,7 +169,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O 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)); + timeButton.setText(dateUtil.timeString(eventTime)); dateButton.setOnClickListener(this); timeButton.setOnClickListener(this); @@ -484,7 +485,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O 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)); + timeButton.setText(dateUtil.timeString(eventTime)); updateBGforDateTime(); } @@ -698,7 +699,7 @@ public class NewNSTreatmentDialog extends DaggerDialogFragment implements View.O if (data.has("created_at")) { ret += resourceHelper.gs(R.string.event_time_label); ret += ": "; - ret += DateUtil.dateAndTimeString(eventTime); + ret += dateUtil.dateAndTimeString(eventTime); ret += "\n"; } if (data.has("enteredBy")) { 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/FoodService.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodService.java index 19ceb73ca6..405fc22b50 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 @@ -16,7 +16,6 @@ import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.sql.SQLException; import java.util.ArrayList; @@ -32,6 +31,7 @@ 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.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -43,7 +43,7 @@ import io.reactivex.schedulers.Schedulers; */ public class FoodService extends OrmLiteBaseService { - private Logger log = StacktraceLoggerWrapper.getLogger(L.DATAFOOD); + private Logger log = StacktraceLoggerWrapper.getLogger(LTag.DATAFOOD); private CompositeDisposable disposable = new CompositeDisposable(); private static final ScheduledExecutorService foodEventWorker = Executors.newSingleThreadScheduledExecutor(); @@ -98,7 +98,7 @@ public class FoodService extends OrmLiteBaseService { public void onCreate() { super.onCreate(); try { - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.info("onCreate"); TableUtils.createTableIfNotExists(this.getConnectionSource(), Food.class); } catch (SQLException e) { @@ -108,7 +108,7 @@ public class FoodService extends OrmLiteBaseService { } public void onUpgrade(ConnectionSource connectionSource, int oldVersion, int newVersion) { - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.info("onUpgrade"); // this.resetFood(); } @@ -147,7 +147,7 @@ public class FoodService extends OrmLiteBaseService { class PostRunnable implements Runnable { public void run() { - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.debug("Firing EventFoodChange"); RxBus.Companion.getINSTANCE().send(event); callback.setPost(null); @@ -258,7 +258,7 @@ public class FoodService extends OrmLiteBaseService { public void deleteByNSId(String _id) throws SQLException { Food stored = this.findByNSId(_id); if (stored != null) { - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.debug("Removing Food record from database: " + stored.toString()); this.delete(stored); } @@ -312,7 +312,7 @@ public class FoodService extends OrmLiteBaseService { public void createOrUpdate(Food food) { try { this.getDao().createOrUpdate(food); - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.debug("Created or Updated: " + food.toString()); } catch (SQLException e) { log.error("Unable to createOrUpdate Food", e); @@ -323,7 +323,7 @@ public class FoodService extends OrmLiteBaseService { public void create(Food food) { try { this.getDao().create(food); - if (L.isEnabled(L.DATAFOOD)) + if (L.isEnabled(LTag.DATAFOOD)) log.debug("New record: " + food.toString()); } catch (SQLException e) { log.error("Unable to create Food", e); 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 1d72212fb3..4d9021bb71 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 @@ -6,12 +6,12 @@ import android.bluetooth.BluetoothAdapter import android.content.Context import android.content.Intent import android.content.pm.PackageManager -import android.os.Build -import android.os.Environment import android.provider.Settings +import androidx.activity.invoke import androidx.annotation.StringRes import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment +import androidx.fragment.app.FragmentActivity import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.PreferencesActivity @@ -22,9 +22,9 @@ 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 import info.nightscout.androidaps.utils.alertDialogs.OKDialog.show -import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.PrefImportSummaryDialog import info.nightscout.androidaps.utils.alertDialogs.TwoMessagesAlertDialog import info.nightscout.androidaps.utils.alertDialogs.WarningDialog @@ -32,8 +32,6 @@ import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.protection.PasswordCheck import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP -import org.joda.time.DateTime -import org.joda.time.Days import java.io.File import java.io.FileNotFoundException import java.io.IOException @@ -51,37 +49,25 @@ private val PERMISSIONS_STORAGE = arrayOf( Manifest.permission.WRITE_EXTERNAL_STORAGE ) -private const val IMPORT_AGE_NOT_YET_OLD_DAYS = 60 - @Singleton class ImportExportPrefs @Inject constructor( private var log: AAPSLogger, private val resourceHelper: ResourceHelper, private val sp: SP, private val buildHelper: BuildHelper, - private val otp: OneTimePassword, private val rxBus: RxBusWrapper, private val passwordCheck: PasswordCheck, private val classicPrefsFormat: ClassicPrefsFormat, - private val encryptedPrefsFormat: EncryptedPrefsFormat + private val encryptedPrefsFormat: EncryptedPrefsFormat, + private val prefFileList: PrefFileListProvider ) { val TAG = LTag.CORE - private val path = File(Environment.getExternalStorageDirectory().toString()) - - private val file = File(path, resourceHelper.gs(R.string.app_name) + "Preferences") - private val encFile = File(path, resourceHelper.gs(R.string.app_name) + "Preferences.json") - - fun prefsImportFile(): File { - return if (encFile.exists()) encFile else file - } - fun prefsFileExists(): Boolean { - return encFile.exists() || file.exists() + return prefFileList.listPreferenceFiles().size > 0 } - fun exportSharedPreferences(f: Fragment) { f.activity?.let { exportSharedPreferences(it) } } @@ -135,9 +121,6 @@ class ImportExportPrefs @Inject constructor( return name } - private fun getCurrentDeviceModelString() = - Build.MANUFACTURER + " " + Build.MODEL + " (" + Build.DEVICE + ")" - private fun prefsEncryptionIsDisabled() = buildHelper.isEngineeringMode() && !sp.getBoolean(resourceHelper.gs(R.string.key_maintenance_encrypt_exported_prefs), true) @@ -173,36 +156,41 @@ class ImportExportPrefs @Inject constructor( return true } - private fun askToConfirmExport(activity: Activity, then: ((password: String) -> Unit)) { + private fun askToConfirmExport(activity: Activity, fileToExport: File, then: ((password: String) -> Unit)) { if (!prefsEncryptionIsDisabled() && !assureMasterPasswordSet(activity, R.string.nav_export)) return TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_export), - resourceHelper.gs(R.string.export_to) + " " + encFile + " ?", + resourceHelper.gs(R.string.export_to) + " " + fileToExport + " ?", resourceHelper.gs(R.string.password_preferences_encrypt_prompt), { askForMasterPassIfNeeded(activity, R.string.preferences_export_canceled, then) - }, null, R.drawable.ic_header_export) + }, null, R.drawable.ic_header_export) } - private fun askToConfirmImport(activity: Activity, fileToImport: File, then: ((password: String) -> Unit)) { + private fun askToConfirmImport(activity: Activity, fileToImport: PrefsFile, then: ((password: String) -> Unit)) { - if (encFile.exists()) { + if (fileToImport.handler == PrefsFormatsHandler.ENCRYPTED) { if (!assureMasterPasswordSet(activity, R.string.nav_import)) return TwoMessagesAlertDialog.showAlert(activity, resourceHelper.gs(R.string.nav_import), - resourceHelper.gs(R.string.import_from) + " " + fileToImport + " ?", + resourceHelper.gs(R.string.import_from) + " " + fileToImport.file + " ?", resourceHelper.gs(R.string.password_preferences_decrypt_prompt), { askForMasterPass(activity, R.string.preferences_import_canceled, then) }, null, R.drawable.ic_header_import) } else { OKDialog.showConfirmation(activity, resourceHelper.gs(R.string.nav_import), - resourceHelper.gs(R.string.import_from) + " " + fileToImport + " ?", + resourceHelper.gs(R.string.import_from) + " " + fileToImport.file + " ?", Runnable { then("") }) } } private fun exportSharedPreferences(activity: Activity) { - askToConfirmExport(activity) { password -> + + prefFileList.ensureExportDirExists() + val legacyFile = prefFileList.legacyFile() + val newFile = prefFileList.newExportFile() + + askToConfirmExport(activity, newFile) { password -> try { val entries: MutableMap = mutableMapOf() for ((key, value) in sp.getAll()) { @@ -211,12 +199,14 @@ class ImportExportPrefs @Inject constructor( val prefs = Prefs(entries, prepareMetadata(activity)) - classicPrefsFormat.savePreferences(file, prefs) - encryptedPrefsFormat.savePreferences(encFile, prefs, password) + if (BuildConfig.DEBUG && buildHelper.isEngineeringMode()) { + classicPrefsFormat.savePreferences(legacyFile, prefs) + } + encryptedPrefsFormat.savePreferences(newFile, prefs, password) ToastUtils.okToast(activity, resourceHelper.gs(R.string.exported)) } catch (e: FileNotFoundException) { - ToastUtils.errorToast(activity, resourceHelper.gs(R.string.filenotfound) + " " + encFile) + ToastUtils.errorToast(activity, resourceHelper.gs(R.string.filenotfound) + " " + newFile) log.error(TAG, "Unhandled exception", e) } catch (e: IOException) { ToastUtils.errorToast(activity, e.message) @@ -226,21 +216,38 @@ class ImportExportPrefs @Inject constructor( } fun importSharedPreferences(fragment: Fragment) { - fragment.activity?.let { importSharedPreferences(it) } + fragment.activity?.let { fragmentAct -> + val callForPrefFile = fragmentAct.registerForActivityResult(PrefsFileContract()) { + it?.let { + importSharedPreferences(fragmentAct, it) + } + } + callForPrefFile.invoke() + } } - fun importSharedPreferences(activity: Activity) { + fun importSharedPreferences(activity: FragmentActivity) { + val callForPrefFile = activity.registerForActivityResult(PrefsFileContract()) { + it?.let { + importSharedPreferences(activity, it) + } + } + callForPrefFile.invoke() + } - val importFile = prefsImportFile() + private fun importSharedPreferences(activity: Activity, importFile: PrefsFile) { askToConfirmImport(activity, importFile) { password -> - val format: PrefsFormat = if (encFile.exists()) encryptedPrefsFormat else classicPrefsFormat + val format: PrefsFormat = when (importFile.handler) { + PrefsFormatsHandler.CLASSIC -> classicPrefsFormat + PrefsFormatsHandler.ENCRYPTED -> encryptedPrefsFormat + } try { - val prefs = format.loadPreferences(importFile, password) - prefs.metadata = checkMetadata(prefs.metadata) + val prefs = format.loadPreferences(importFile.file, password) + prefs.metadata = prefFileList.checkMetadata(prefs.metadata) // import is OK when we do not have errors (warnings are allowed) val importOk = checkIfImportIsOk(prefs) @@ -276,45 +283,6 @@ class ImportExportPrefs @Inject constructor( } } - // check metadata for known issues, change their status and add info with explanations - private fun checkMetadata(metadata: Map): Map { - val meta = metadata.toMutableMap() - - meta[PrefsMetadataKey.AAPS_FLAVOUR]?.let { flavour -> - val flavourOfPrefs = flavour.value - if (flavour.value != BuildConfig.FLAVOR) { - flavour.status = PrefsStatus.WARN - flavour.info = resourceHelper.gs(R.string.metadata_warning_different_flavour, flavourOfPrefs, BuildConfig.FLAVOR) - } - } - - meta[PrefsMetadataKey.DEVICE_MODEL]?.let { model -> - if (model.value != getCurrentDeviceModelString()) { - model.status = PrefsStatus.WARN - model.info = resourceHelper.gs(R.string.metadata_warning_different_device) - } - } - - meta[PrefsMetadataKey.CREATED_AT]?.let { createdAt -> - try { - val date1 = DateTime.parse(createdAt.value); - val date2 = DateTime.now() - - val daysOld = Days.daysBetween(date1.toLocalDate(), date2.toLocalDate()).getDays() - - if (daysOld > IMPORT_AGE_NOT_YET_OLD_DAYS) { - createdAt.status = PrefsStatus.WARN - createdAt.info = resourceHelper.gs(R.string.metadata_warning_old_export, daysOld.toString()) - } - } catch (e: Exception) { - createdAt.status = PrefsStatus.WARN - createdAt.info = resourceHelper.gs(R.string.metadata_warning_date_format) - } - } - - return meta - } - private fun checkIfImportIsOk(prefs: Prefs): Boolean { var importOk = true diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/LoggerUtils.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/LoggerUtils.java index 9205dc0ccd..2d1dcb19b8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/LoggerUtils.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/LoggerUtils.java @@ -1,19 +1,14 @@ package info.nightscout.androidaps.plugins.general.maintenance; -import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; -import info.nightscout.androidaps.logging.L; -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; /** * This class provides serveral methods for log-handling (eg. sending logs as emails). */ public class LoggerUtils { - private static final Logger LOGGER = StacktraceLoggerWrapper.getLogger(L.CORE); - public static String SUFFIX = ".log.zip"; /** 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..9377b58992 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) @@ -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/PrefFileListProvider.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt new file mode 100644 index 0000000000..52910dfff1 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -0,0 +1,219 @@ +package info.nightscout.androidaps.plugins.general.maintenance + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Environment +import android.os.Parcelable +import androidx.activity.result.contract.ActivityResultContract +import info.nightscout.androidaps.BuildConfig +import info.nightscout.androidaps.R +import info.nightscout.androidaps.logging.AAPSLogger +import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils +import info.nightscout.androidaps.plugins.general.maintenance.activities.PrefImportListActivity +import info.nightscout.androidaps.plugins.general.maintenance.formats.* +import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.sharedPreferences.SP +import info.nightscout.androidaps.utils.storage.Storage +import kotlinx.android.parcel.Parcelize +import kotlinx.android.parcel.RawValue +import org.joda.time.DateTime +import org.joda.time.Days +import org.joda.time.Hours +import org.joda.time.LocalDateTime +import org.joda.time.format.DateTimeFormat +import java.io.File +import javax.inject.Inject +import javax.inject.Singleton + +enum class PrefsImportDir { + ROOT_DIR, + AAPS_DIR +} + +@Parcelize +data class PrefsFile( + val file: File, + val baseDir: File, + val dirKind: PrefsImportDir, + val handler: PrefsFormatsHandler, + + // metadata here is used only for list display + val metadata: @RawValue Map +) : Parcelable + +class PrefsFileContract : ActivityResultContract() { + + companion object { + const val OUTPUT_PARAM = "prefs_file" + } + + override fun parseResult(resultCode: Int, intent: Intent?): PrefsFile? { + return when (resultCode) { + Activity.RESULT_OK -> intent?.getParcelableExtra(OUTPUT_PARAM) + else -> null + } + } + + override fun createIntent(context: Context, input: Void?): Intent { + return Intent(context, PrefImportListActivity::class.java) + } +} + +fun getCurrentDeviceModelString() = + Build.MANUFACTURER + " " + Build.MODEL + " (" + Build.DEVICE + ")" + +@Singleton +class PrefFileListProvider @Inject constructor( + private val resourceHelper: ResourceHelper, + private val classicPrefsFormat: ClassicPrefsFormat, + private val encryptedPrefsFormat: EncryptedPrefsFormat, + private val storage: Storage, + private val versionCheckerUtils: VersionCheckerUtils +) { + + companion object { + private val path = File(Environment.getExternalStorageDirectory().toString()) + private val aapsPath = File(path, "AAPS" + File.separator + "preferences") + private const val IMPORT_AGE_NOT_YET_OLD_DAYS = 60 + } + + /** + * This function tries to list possible preference files from main SDCard root dir and AAPS/preferences dir + * and tries to do quick assessment for preferences format plausibility. + * It does NOT load full metadata or is 100% accurate - it tries to do QUICK detection, based on: + * - file name and extension + * - predicted file contents + */ + fun listPreferenceFiles(loadMetadata: Boolean = false): MutableList { + val prefFiles = mutableListOf() + + // searching rood dir for legacy files + path.walk().maxDepth(1).filter { it.isFile && (it.name.endsWith(".json") || it.name.contains("Preferences")) }.forEach { + val contents = storage.getFileContents(it) + val detectedNew = encryptedPrefsFormat.isPreferencesFile(it, contents) + val detectedOld = !detectedNew && classicPrefsFormat.isPreferencesFile(it, contents) + if (detectedNew || detectedOld) { + val formatHandler = if (detectedNew) PrefsFormatsHandler.ENCRYPTED else PrefsFormatsHandler.CLASSIC + prefFiles.add(PrefsFile(it, path, PrefsImportDir.ROOT_DIR, formatHandler, metadataFor(loadMetadata, formatHandler, contents))) + } + } + + // searching dedicated dir, only for new JSON format + aapsPath.walk().filter { it.isFile && it.name.endsWith(".json") }.forEach { + val contents = storage.getFileContents(it) + if (encryptedPrefsFormat.isPreferencesFile(it, contents)) { + prefFiles.add(PrefsFile(it, aapsPath, PrefsImportDir.AAPS_DIR, PrefsFormatsHandler.ENCRYPTED, metadataFor(loadMetadata, PrefsFormatsHandler.ENCRYPTED, contents))) + } + } + + // we sort only if we have metadata to be used for that + if (loadMetadata) { + prefFiles.sortWith( + compareByDescending { it.handler } + .thenBy { it.metadata[PrefsMetadataKey.AAPS_FLAVOUR]?.status } + .thenByDescending { it.metadata[PrefsMetadataKey.CREATED_AT]?.value } + ) + } + + return prefFiles + } + + private fun metadataFor(loadMetadata: Boolean, formatHandler: PrefsFormatsHandler, contents: String): PrefMetadataMap { + if (!loadMetadata) { + return mapOf() + } + return checkMetadata(when (formatHandler) { + PrefsFormatsHandler.CLASSIC -> classicPrefsFormat.loadMetadata(contents) + PrefsFormatsHandler.ENCRYPTED -> encryptedPrefsFormat.loadMetadata(contents) + }) + } + + fun legacyFile(): File { + return File(path, resourceHelper.gs(R.string.app_name) + "Preferences") + } + + fun ensureExportDirExists() { + if (!aapsPath.exists()) { + aapsPath.mkdirs() + } + } + + fun newExportFile(): File { + val timeLocal = LocalDateTime.now().toString(DateTimeFormat.forPattern("yyyy-MM-dd'_'HHmmss")) + return File(aapsPath, timeLocal + "_" + BuildConfig.FLAVOR + ".json") + } + + // check metadata for known issues, change their status and add info with explanations + fun checkMetadata(metadata: Map): Map { + val meta = metadata.toMutableMap() + + meta[PrefsMetadataKey.AAPS_FLAVOUR]?.let { flavour -> + val flavourOfPrefs = flavour.value + if (flavour.value != BuildConfig.FLAVOR) { + flavour.status = PrefsStatus.WARN + flavour.info = resourceHelper.gs(R.string.metadata_warning_different_flavour, flavourOfPrefs, BuildConfig.FLAVOR) + } + } + + meta[PrefsMetadataKey.DEVICE_MODEL]?.let { model -> + if (model.value != getCurrentDeviceModelString()) { + model.status = PrefsStatus.WARN + model.info = resourceHelper.gs(R.string.metadata_warning_different_device) + } + } + + meta[PrefsMetadataKey.CREATED_AT]?.let { createdAt -> + try { + val date1 = DateTime.parse(createdAt.value); + val date2 = DateTime.now() + + val daysOld = Days.daysBetween(date1.toLocalDate(), date2.toLocalDate()).getDays() + + if (daysOld > IMPORT_AGE_NOT_YET_OLD_DAYS) { + createdAt.status = PrefsStatus.WARN + createdAt.info = resourceHelper.gs(R.string.metadata_warning_old_export, daysOld.toString()) + } + } catch (e: Exception) { + createdAt.status = PrefsStatus.WARN + createdAt.info = resourceHelper.gs(R.string.metadata_warning_date_format) + } + } + + meta[PrefsMetadataKey.AAPS_VERSION]?.let { version -> + val currentAppVer = versionCheckerUtils.versionDigits(BuildConfig.VERSION_NAME) + val metadataVer = versionCheckerUtils.versionDigits(version.value) + + if ((currentAppVer.size >= 2) && (metadataVer.size >= 2) && (Math.abs(currentAppVer[1] - metadataVer[1]) > 1)) { + version.status = PrefsStatus.WARN + version.info = resourceHelper.gs(R.string.metadata_warning_different_version) + } + + if ((currentAppVer.isNotEmpty()) && (metadataVer.isNotEmpty()) && (currentAppVer[0] != metadataVer[0])) { + version.status = PrefsStatus.WARN + version.info = resourceHelper.gs(R.string.metadata_urgent_different_version) + } + } + + return meta + } + + fun formatExportedAgo(utcTime: String): String { + val refTime = DateTime.now() + val itTime = DateTime.parse(utcTime) + val days = Days.daysBetween(itTime, refTime).days + val hours = Hours.hoursBetween(itTime, refTime).hours + + return if (hours == 0) { + resourceHelper.gs(R.string.exported_less_than_hour_ago) + } else if ((hours < 24) && (hours > 0)) { + resourceHelper.gs(R.string.exported_ago, resourceHelper.gq(R.plurals.objective_hours, hours, hours)) + } else if ((days < IMPORT_AGE_NOT_YET_OLD_DAYS) && (days > 0)) { + resourceHelper.gs(R.string.exported_ago, resourceHelper.gq(R.plurals.objective_days, days, days)) + } else { + resourceHelper.gs(R.string.exported_at, utcTime.substring(0, 10)) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt index c6cdaa4397..17a18629d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/LogSettingActivity.kt @@ -9,9 +9,12 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.logging.L import kotlinx.android.synthetic.main.activity_logsetting.* +import javax.inject.Inject class LogSettingActivity : NoSplashAppCompatActivity() { + @Inject lateinit var l :L + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_logsetting) @@ -19,7 +22,7 @@ class LogSettingActivity : NoSplashAppCompatActivity() { createViewsForSettings() logsettings_reset.setOnClickListener { - L.resetToDefaults() + l.resetToDefaults() createViewsForSettings() } ok.setOnClickListener { finish() } @@ -27,7 +30,7 @@ class LogSettingActivity : NoSplashAppCompatActivity() { private fun createViewsForSettings() { logsettings_placeholder.removeAllViews() - for (element in L.getLogElements()) { + for (element in l.getLogElements()) { val logViewHolder = LogViewHolder(element) logsettings_placeholder.addView(logViewHolder.baseView) } 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 new file mode 100644 index 0000000000..7703166d04 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt @@ -0,0 +1,135 @@ +package info.nightscout.androidaps.plugins.general.maintenance.activities + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.os.Bundle +import android.view.LayoutInflater +import android.view.MenuItem +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import androidx.recyclerview.widget.LinearLayoutManager +import androidx.recyclerview.widget.RecyclerView +import dagger.android.support.DaggerAppCompatActivity +import info.nightscout.androidaps.R +import info.nightscout.androidaps.plugins.general.maintenance.PrefFileListProvider +import info.nightscout.androidaps.plugins.general.maintenance.PrefsFile +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.resources.ResourceHelper +import kotlinx.android.synthetic.main.maintenance_importlist_activity.* +import javax.inject.Inject + +class PrefImportListActivity : DaggerAppCompatActivity() { + + @Inject lateinit var resourceHelper: ResourceHelper + @Inject lateinit var prefFileListProvider: PrefFileListProvider + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setTheme(R.style.AppTheme) + setContentView(R.layout.maintenance_importlist_activity) + + title = resourceHelper.gs(R.string.preferences_import_list_title) + supportActionBar?.setDisplayHomeAsUpEnabled(true) + supportActionBar?.setDisplayShowHomeEnabled(true) + supportActionBar?.setDisplayShowTitleEnabled(true) + + importlist_recyclerview.layoutManager = LinearLayoutManager(this) + importlist_recyclerview.adapter = RecyclerViewAdapter(prefFileListProvider.listPreferenceFiles(loadMetadata = true)) + } + + inner class RecyclerViewAdapter internal constructor(private var prefFileList: List) : RecyclerView.Adapter() { + + inner class PrefFileViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { + var fileName: TextView = itemView.findViewById(R.id.filelist_name) + var fileDir: TextView = itemView.findViewById(R.id.filelist_dir) + var metaDateTime: TextView = itemView.findViewById(R.id.meta_date_time) + var metaDeviceName: TextView = itemView.findViewById(R.id.meta_device_name) + var metaAppVersion: TextView = itemView.findViewById(R.id.meta_app_version) + var metaVariantFormat: TextView = itemView.findViewById(R.id.meta_variant_format) + + var metalineName: View = itemView.findViewById(R.id.metaline_name) + var metaDateTimeIcon: View = itemView.findViewById(R.id.meta_date_time_icon) + + init { + itemView.isClickable = true + itemView.setOnClickListener { + val prefFile = fileName.tag as PrefsFile + val i = Intent() + + i.putExtra(PrefsFileContract.OUTPUT_PARAM, prefFile) + setResult(Activity.RESULT_OK, i) + finish() + } + } + } + + override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PrefFileViewHolder { + val v = LayoutInflater.from(parent.context).inflate(R.layout.maintenance_importlist_item, parent, false) + return PrefFileViewHolder(v) + } + + override fun getItemCount(): Int { + return prefFileList.size + } + + override fun onBindViewHolder(holder: PrefFileViewHolder, position: Int) { + val prefFile = prefFileList[position] + holder.fileName.text = prefFile.file.name + holder.fileName.tag = prefFile + + holder.fileDir.text = resourceHelper.gs(R.string.in_directory, prefFile.file.parentFile.absolutePath) + + val visible = if (prefFile.handler == PrefsFormatsHandler.CLASSIC) View.GONE else View.VISIBLE + holder.metalineName.visibility = visible + holder.metaDateTimeIcon.visibility = visible + holder.metaAppVersion.visibility = visible + + if (prefFile.handler == PrefsFormatsHandler.CLASSIC) { + holder.metaVariantFormat.text = resourceHelper.gs(R.string.metadata_format_old) + holder.metaVariantFormat.setTextColor(resourceHelper.gc(R.color.metadataTextWarning)) + holder.metaDateTime.text = " " + } else { + + prefFile.metadata[PrefsMetadataKey.AAPS_FLAVOUR]?.let { + holder.metaVariantFormat.text = it.value + val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning + holder.metaVariantFormat.setTextColor(resourceHelper.gc(color)) + } + + prefFile.metadata[PrefsMetadataKey.CREATED_AT]?.let { + holder.metaDateTime.text = prefFileListProvider.formatExportedAgo(it.value) + } + + prefFile.metadata[PrefsMetadataKey.AAPS_VERSION]?.let { + holder.metaAppVersion.text = it.value + val color = if (it.status == PrefsStatus.OK) R.color.metadataOk else R.color.metadataTextWarning + holder.metaAppVersion.setTextColor(resourceHelper.gc(color)) + } + + prefFile.metadata[PrefsMetadataKey.DEVICE_NAME]?.let { + holder.metaDeviceName.text = it.value + } + + } + + } + } + + override fun onOptionsItemSelected(item: MenuItem): Boolean { + if (item.itemId == android.R.id.home) { + finish() + return true + } + return false + } + + public override fun attachBaseContext(newBase: Context) { + super.attachBaseContext(LocaleHelper.wrap(newBase)) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/ClassicPrefsFormat.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/ClassicPrefsFormat.kt index 4689f549a6..40b1ceada4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/ClassicPrefsFormat.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/ClassicPrefsFormat.kt @@ -1,5 +1,6 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats +import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage @@ -19,6 +20,11 @@ class ClassicPrefsFormat @Inject constructor( val FORMAT_KEY = "aaps_old" } + override fun isPreferencesFile(file: File, preloadedContents: String?): Boolean { + val contents = preloadedContents ?: storage.getFileContents(file) + return contents.contains("units::" + Constants.MGDL) || contents.contains("units::" + Constants.MMOL) + } + override fun savePreferences(file: File, prefs: Prefs, masterPassword: String?) { try { val contents = prefs.values.entries.joinToString("\n") { entry -> @@ -35,7 +41,6 @@ class ClassicPrefsFormat @Inject constructor( override fun loadPreferences(file: File, masterPassword: String?): Prefs { var lineParts: Array val entries: MutableMap = mutableMapOf() - val metadata: MutableMap = mutableMapOf() try { val rawLines = storage.getFileContents(file).split("\n") @@ -46,9 +51,7 @@ class ClassicPrefsFormat @Inject constructor( } } - metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(FORMAT_KEY, PrefsStatus.WARN, resourceHelper.gs(R.string.metadata_warning_outdated_format)) - - return Prefs(entries, metadata) + return Prefs(entries, loadMetadata()) } catch (e: FileNotFoundException) { throw PrefFileNotFoundError(file.absolutePath) @@ -57,4 +60,10 @@ class ClassicPrefsFormat @Inject constructor( } } + override fun loadMetadata(contents: String?): PrefMetadataMap { + val metadata: MutableMap = mutableMapOf() + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(FORMAT_KEY, PrefsStatus.WARN, resourceHelper.gs(R.string.metadata_warning_outdated_format)) + return metadata + } + } \ No newline at end of file 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 463b5a31cb..ec88c07bec 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 @@ -27,6 +27,16 @@ class EncryptedPrefsFormat @Inject constructor( val FORMAT_KEY_NOENC = "aaps_structured" private val KEY_CONSCIENCE = "if you remove/change this, please make sure you know the consequences!" + private val FORMAT_TEST_REGEX = Regex("(\\\"format\\\"\\s*\\:\\s*\\\"aaps_[^\"]*\\\")") + } + + override fun isPreferencesFile(file: File, preloadedContents: String?): Boolean { + return if (file.absolutePath.endsWith(".json")) { + val contents = preloadedContents ?: storage.getFileContents(file) + FORMAT_TEST_REGEX.containsMatchIn(contents) + } else { + false + } } override fun savePreferences(file: File, prefs: Prefs, masterPassword: String?) { @@ -97,7 +107,6 @@ class EncryptedPrefsFormat @Inject constructor( override fun loadPreferences(file: File, masterPassword: String?): Prefs { val entries: MutableMap = mutableMapOf() - val metadata: MutableMap = mutableMapOf() val issues = LinkedList() try { @@ -105,25 +114,11 @@ class EncryptedPrefsFormat @Inject constructor( val fileContents = jsonBody.replace(Regex("(?is)(\\\"file_hash\\\"\\s*\\:\\s*\\\")([^\"]*)(\\\")"), "$1--to-be-calculated--$3") val calculatedFileHash = cryptoUtil.hmac256(fileContents, KEY_CONSCIENCE) val container = JSONObject(jsonBody) + val metadata: MutableMap = loadMetadata(container) - if (container.has(PrefsMetadataKey.FILE_FORMAT.key) && container.has("security") && container.has("content") && container.has("metadata")) { + if (container.has(PrefsMetadataKey.FILE_FORMAT.key) && container.has("security") && container.has("content")) { val fileFormat = container.getString(PrefsMetadataKey.FILE_FORMAT.key) - - if ((fileFormat != FORMAT_KEY_ENC) && (fileFormat != FORMAT_KEY_NOENC)) { - throw PrefFormatError("Unsupported file format: " + fileFormat) - } - - val meta = container.getJSONObject("metadata") val security = container.getJSONObject("security") - - metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(fileFormat, PrefsStatus.OK) - for (key in meta.keys()) { - val metaKey = PrefsMetadataKey.fromKey(key) - if (metaKey != null) { - metadata[metaKey] = PrefMetadata(meta.getString(key), PrefsStatus.OK) - } - } - val encrypted = fileFormat == FORMAT_KEY_ENC var secure: PrefsStatus = PrefsStatus.OK var decryptedOk = false @@ -208,8 +203,6 @@ class EncryptedPrefsFormat @Inject constructor( } metadata[PrefsMetadataKey.ENCRYPTION] = PrefMetadata(encryptionDescStr, secure, issuesStr) - } else { - metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR) } return Prefs(entries, metadata) @@ -223,4 +216,35 @@ class EncryptedPrefsFormat @Inject constructor( } } + override fun loadMetadata(contents: String?): PrefMetadataMap { + contents?.let { + val container = JSONObject(contents) + return loadMetadata(container) + } + return mutableMapOf() + } + + private fun loadMetadata(container: JSONObject): MutableMap { + val metadata: MutableMap = mutableMapOf() + if (container.has(PrefsMetadataKey.FILE_FORMAT.key) && container.has("security") && container.has("content") && container.has("metadata")) { + val fileFormat = container.getString(PrefsMetadataKey.FILE_FORMAT.key) + if ((fileFormat != FORMAT_KEY_ENC) && (fileFormat != FORMAT_KEY_NOENC)) { + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.metadata_format_other), PrefsStatus.ERROR) + } else { + val meta = container.getJSONObject("metadata") + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(fileFormat, PrefsStatus.OK) + for (key in meta.keys()) { + val metaKey = PrefsMetadataKey.fromKey(key) + if (metaKey != null) { + metadata[metaKey] = PrefMetadata(meta.getString(key), PrefsStatus.OK) + } + } + } + } else { + metadata[PrefsMetadataKey.FILE_FORMAT] = PrefMetadata(resourceHelper.gs(R.string.prefdecrypt_wrong_json), PrefsStatus.ERROR) + } + + return metadata; + } + } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt index a47add0dd7..d0d3935023 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/PrefsFormat.kt @@ -1,12 +1,14 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats import android.content.Context +import android.os.Parcelable import androidx.annotation.DrawableRes import androidx.annotation.StringRes import info.nightscout.androidaps.R +import kotlinx.android.parcel.Parcelize import java.io.File -enum class PrefsMetadataKey(val key: String, @DrawableRes val icon:Int, @StringRes val label:Int) { +enum class PrefsMetadataKey(val key: String, @DrawableRes val icon: Int, @StringRes val label: Int) { FILE_FORMAT("format", R.drawable.ic_meta_format, R.string.metadata_label_format), CREATED_AT("created_at", R.drawable.ic_meta_date, R.string.metadata_label_created_at), @@ -33,16 +35,15 @@ enum class PrefsMetadataKey(val key: String, @DrawableRes val icon:Int, @StringR } } - } - fun formatForDisplay(context: Context, value:String): String { + fun formatForDisplay(context: Context, value: String): String { return when (this) { FILE_FORMAT -> when (value) { - ClassicPrefsFormat.FORMAT_KEY -> context.getString(R.string.metadata_format_old) - EncryptedPrefsFormat.FORMAT_KEY_ENC -> context.getString(R.string.metadata_format_new) + ClassicPrefsFormat.FORMAT_KEY -> context.getString(R.string.metadata_format_old) + EncryptedPrefsFormat.FORMAT_KEY_ENC -> context.getString(R.string.metadata_format_new) EncryptedPrefsFormat.FORMAT_KEY_NOENC -> context.getString(R.string.metadata_format_debug) - else -> context.getString(R.string.metadata_format_other) + else -> context.getString(R.string.metadata_format_other) } CREATED_AT -> value.replace("T", " ").replace("Z", " (UTC)") else -> value @@ -51,16 +52,21 @@ enum class PrefsMetadataKey(val key: String, @DrawableRes val icon:Int, @StringR } -data class PrefMetadata(var value : String, var status : PrefsStatus, var info : String? = null) +@Parcelize +data class PrefMetadata(var value: String, var status: PrefsStatus, var info: String? = null) : Parcelable -data class Prefs(val values : Map, var metadata : Map) +typealias PrefMetadataMap = Map + +data class Prefs(val values: Map, var metadata: PrefMetadataMap) interface PrefsFormat { fun savePreferences(file: File, prefs: Prefs, masterPassword: String? = null) - fun loadPreferences(file: File, masterPassword: String? = null) : Prefs + fun loadPreferences(file: File, masterPassword: String? = null): Prefs + fun loadMetadata(contents: String? = null): PrefMetadataMap + fun isPreferencesFile(file: File, preloadedContents: String? = null): Boolean } -enum class PrefsStatus(@DrawableRes val icon:Int) { +enum class PrefsStatus(@DrawableRes val icon: Int) { OK(R.drawable.ic_meta_ok), WARN(R.drawable.ic_meta_warning), ERROR(R.drawable.ic_meta_error), @@ -68,6 +74,11 @@ enum class PrefsStatus(@DrawableRes val icon:Int) { DISABLED(R.drawable.ic_meta_error) } +enum class PrefsFormatsHandler { + CLASSIC, + ENCRYPTED +} + class PrefFileNotFoundError(message: String) : Exception(message) class PrefIOError(message: String) : Exception(message) class PrefFormatError(message: String) : Exception(message) 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..da77936384 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 @@ -11,7 +11,6 @@ import android.text.Html; import android.text.Spanned; import androidx.preference.PreferenceFragmentCompat; -import androidx.preference.PreferenceScreen; import org.jetbrains.annotations.NotNull; @@ -58,6 +57,7 @@ public class NSClientPlugin extends PluginBase { private final ResourceHelper resourceHelper; private final Context context; private final SP sp; + private final Config config; public Handler handler; @@ -81,7 +81,8 @@ public class NSClientPlugin extends PluginBase { ResourceHelper resourceHelper, Context context, SP sp, - NsClientReceiverDelegate nsClientReceiverDelegate + NsClientReceiverDelegate nsClientReceiverDelegate, + Config config ) { super(new PluginDescription() .mainType(PluginType.GENERAL) @@ -99,8 +100,9 @@ public class NSClientPlugin extends PluginBase { this.context = context; this.sp = sp; this.nsClientReceiverDelegate = nsClientReceiverDelegate; + this.config = config; - if (Config.NSCLIENT) { + if (config.getNSCLIENT()) { getPluginDescription().alwaysEnabled(true).visibleByDefault(true); } if (handler == null) { @@ -184,7 +186,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)); } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java index 5b2fd496c7..48a2b31b35 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSUpload.java @@ -25,7 +25,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.DetailedBolusInfo; import info.nightscout.androidaps.data.IobTotal; import info.nightscout.androidaps.data.Profile; -import info.nightscout.androidaps.data.ProfileStore; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.db.BgReading; import info.nightscout.androidaps.db.CareportalEvent; import info.nightscout.androidaps.db.DbRequest; @@ -35,11 +35,12 @@ import info.nightscout.androidaps.db.TempTarget; import info.nightscout.androidaps.db.TemporaryBasal; import info.nightscout.androidaps.interfaces.PumpInterface; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.aps.loop.APSResult; import info.nightscout.androidaps.plugins.aps.loop.DeviceStatus; 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.IobCobCalculatorPlugin; import info.nightscout.androidaps.receivers.ReceiverStatusStore; import info.nightscout.androidaps.utils.DateUtil; @@ -50,7 +51,7 @@ import info.nightscout.androidaps.utils.SP; * Created by mike on 26.05.2017. */ public class NSUpload { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); public static void uploadTempBasalStartAbsolute(TemporaryBasal temporaryBasal, Double originalExtendedAmount) { try { @@ -200,7 +201,7 @@ public class NSUpload { deviceStatus.enacted.put("requested", requested); } } else { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("OpenAPS data too old to upload, sending iob only"); IobTotal[] iob = iobCobCalculatorPlugin.calculateIobArrayInDia(profile); if (iob.length > 0) { 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 fb425a23df..0786aae250 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 @@ -9,7 +9,6 @@ import com.j256.ormlite.dao.CloseableIterator; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.sql.SQLException; @@ -18,6 +17,7 @@ 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.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientResend; @@ -28,7 +28,7 @@ import info.nightscout.androidaps.utils.SP; * Created by mike on 21.02.2016. */ public class UploadQueue { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); public static String status() { return "QUEUE: " + MainApp.getDbHelper().size(DatabaseHelper.DATABASE_DBREQUESTS); @@ -48,7 +48,7 @@ public class UploadQueue { public static void add(final DbRequest dbr) { if (SP.getBoolean(R.string.key_ns_noupload, false)) return; - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("Adding to queue: " + dbr.log()); try { MainApp.getDbHelper().create(dbr); @@ -62,10 +62,10 @@ public class UploadQueue { startService(); if (NSClientService.handler != null) { NSClientService.handler.post(() -> { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("ClearQueue"); MainApp.getDbHelper().deleteAllDbRequests(); - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug(status()); }); } @@ -83,7 +83,7 @@ public class UploadQueue { return; } if (MainApp.getDbHelper().deleteDbRequest(id) == 1) { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("Removed item from UploadQueue. " + UploadQueue.status()); } } catch (JSONException e) { @@ -100,7 +100,7 @@ public class UploadQueue { if (NSClientService.handler != null) { NSClientService.handler.post(() -> { MainApp.getDbHelper().deleteDbRequestbyMongoId(action, _id); - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("Removing " + _id + " from UploadQueue. " + UploadQueue.status()); }); } 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 cd1b525d59..8541253f81 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 @@ -3,10 +3,10 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import info.nightscout.androidaps.events.Event; 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.events.EventNSClientRestart; @@ -16,7 +16,7 @@ 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(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); public String _id = null; public String nsClientID = null; public JSONObject json = null; @@ -48,7 +48,7 @@ public class NSAddAck extends Event implements Ack { RxBus.Companion.getINSTANCE().send(new EventNSClientRestart()); return; } - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("DBACCESS " + response.getString("result")); } return; 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 805a1495a8..bc79bd2739 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 @@ -3,10 +3,9 @@ package info.nightscout.androidaps.plugins.general.nsclient.acks; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import info.nightscout.androidaps.events.Event; -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 io.socket.client.Ack; @@ -15,12 +14,13 @@ 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(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); public boolean result = false; public String _id; public String action; - public void call(Object...args) { - JSONObject response = (JSONObject)args[0]; + + public void call(Object... args) { + JSONObject response = (JSONObject) args[0]; if (response.has("result")) try { if (response.getString("result").equals("success")) 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..d0441cccfa 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 { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSTreatment.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSTreatment.java index 1c31922949..8eda8c7e70 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSTreatment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSTreatment.java @@ -3,15 +3,14 @@ package info.nightscout.androidaps.plugins.general.nsclient.data; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.Date; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; public class NSTreatment { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); private JSONObject data; private String action = null; // "update", "remove" or null (add) @@ -82,15 +81,47 @@ public class NSTreatment { return ret; } - public String getAction() { return action; } - public JSONObject getData() { return data; } - public String get_id() { return getStringOrNull("_id"); } - public String getEnteredBy() { return getStringOrNull("enteredBy"); } - public String getEventType() { return getStringOrNull("eventType"); } - public Integer getHapp_id() { return getIntegerOrNull("happ_id"); } - public Integer getDuration() { return getIntegerOrNull("duration"); } - public Integer getMgdl() { return getIntegerOrNull("mgdl"); } - public Double getAbsolute() { return getDoubleOrNull("absolute"); } - public Long getMills() { return getLongOrNull("mills"); } - public Date getCreated_at() { return getDateOrNull("created_at"); } + public String getAction() { + return action; + } + + public JSONObject getData() { + return data; + } + + public String get_id() { + return getStringOrNull("_id"); + } + + public String getEnteredBy() { + return getStringOrNull("enteredBy"); + } + + public String getEventType() { + return getStringOrNull("eventType"); + } + + public Integer getHapp_id() { + return getIntegerOrNull("happ_id"); + } + + public Integer getDuration() { + return getIntegerOrNull("duration"); + } + + public Integer getMgdl() { + return getIntegerOrNull("mgdl"); + } + + public Double getAbsolute() { + return getDoubleOrNull("absolute"); + } + + public Long getMills() { + return getLongOrNull("mills"); + } + + public Date getCreated_at() { + return getDateOrNull("created_at"); + } } 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 5c43c96771..3187ccc924 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 @@ -20,7 +20,6 @@ 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,11 +30,10 @@ 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.interfaces.ProfileStore; import info.nightscout.androidaps.db.DbRequest; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventConfigBuilderChange; @@ -91,8 +89,10 @@ public class NSClientService extends DaggerService { @Inject SP sp; @Inject NSClientPlugin nsClientPlugin; @Inject BuildHelper buildHelper; + @Inject Config config; + @Inject DateUtil dateUtil; - private static Logger log = StacktraceLoggerWrapper.getLogger(L.NSCLIENT); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.NSCLIENT); private CompositeDisposable disposable = new CompositeDisposable(); static public PowerManager.WakeLock mWakeLock; @@ -178,7 +178,7 @@ public class NSClientService extends DaggerService { .toObservable(EventAppExit.class) .observeOn(Schedulers.io()) .subscribe(event -> { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("EventAppExit received"); destroy(); stopSelf(); @@ -367,7 +367,7 @@ public class NSClientService extends DaggerService { private Emitter.Listener onDisconnect = new Emitter.Listener() { @Override public void call(Object... args) { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("disconnect reason: {}", args); rxBus.send(new EventNSClientNewLog("NSCLIENT", "disconnect event")); } @@ -557,7 +557,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 { @@ -722,7 +722,7 @@ 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); } @@ -804,7 +804,7 @@ public class NSClientService extends DaggerService { if (mSocket == null || !mSocket.connected()) return; if (lastResendTime > System.currentTimeMillis() - 10 * 1000L) { - if (L.isEnabled(L.NSCLIENT)) + if (L.isEnabled(LTag.NSCLIENT)) log.debug("Skipping resend by lastResendTime: " + ((System.currentTimeMillis() - lastResendTime) / 1000L) + " sec"); return; } 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 b577b2927c..92cde49903 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 @@ -36,14 +36,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 @@ -57,6 +58,7 @@ import info.nightscout.androidaps.plugins.source.DexcomPlugin import info.nightscout.androidaps.plugins.source.XdripPlugin import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.queue.CommandQueue +import info.nightscout.androidaps.skins.SkinProvider import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper @@ -64,41 +66,33 @@ 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.sharedPreferences.SP +import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.androidaps.utils.wizard.QuickWizard import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers -import kotlinx.android.synthetic.main.overview_fragment.* -import kotlinx.android.synthetic.main.overview_fragment.careportal_canulaage -import kotlinx.android.synthetic.main.overview_fragment.careportal_insulinage -import kotlinx.android.synthetic.main.overview_fragment.careportal_reservoirlevel -import kotlinx.android.synthetic.main.overview_fragment.careportal_sensorage -import kotlinx.android.synthetic.main.overview_fragment.careportal_pbage -import kotlinx.android.synthetic.main.overview_fragment.careportal_batterylevel -import kotlinx.android.synthetic.main.overview_fragment.overview_activeprofile -import kotlinx.android.synthetic.main.overview_fragment.overview_apsmode -import kotlinx.android.synthetic.main.overview_fragment.overview_arrow -import kotlinx.android.synthetic.main.overview_fragment.overview_basebasal -import kotlinx.android.synthetic.main.overview_fragment.overview_bg -import kotlinx.android.synthetic.main.overview_fragment.overview_bggraph -import kotlinx.android.synthetic.main.overview_fragment.overview_carbsbutton -import kotlinx.android.synthetic.main.overview_fragment.overview_chartMenuButton -import kotlinx.android.synthetic.main.overview_fragment.overview_cob -import kotlinx.android.synthetic.main.overview_fragment.overview_extendedbolus -import kotlinx.android.synthetic.main.overview_fragment.overview_insulinbutton -import kotlinx.android.synthetic.main.overview_fragment.overview_iob -import kotlinx.android.synthetic.main.overview_fragment.overview_iobcalculationprogess -import kotlinx.android.synthetic.main.overview_fragment.overview_iobgraph -import kotlinx.android.synthetic.main.overview_fragment.overview_looplayout +import kotlinx.android.synthetic.main.overview_buttons_layout.* +import kotlinx.android.synthetic.main.overview_buttons_layout.overview_carbsbutton +import kotlinx.android.synthetic.main.overview_buttons_layout.overview_insulinbutton +import kotlinx.android.synthetic.main.overview_buttons_layout.overview_quickwizardbutton +import kotlinx.android.synthetic.main.overview_buttons_layout.overview_treatmentbutton +import kotlinx.android.synthetic.main.overview_buttons_layout.overview_wizardbutton import kotlinx.android.synthetic.main.overview_fragment.overview_notifications -import kotlinx.android.synthetic.main.overview_fragment.overview_pumpstatus -import kotlinx.android.synthetic.main.overview_fragment.overview_pumpstatuslayout -import kotlinx.android.synthetic.main.overview_fragment.overview_quickwizardbutton -import kotlinx.android.synthetic.main.overview_fragment.overview_sensitivity -import kotlinx.android.synthetic.main.overview_fragment.overview_temptarget -import kotlinx.android.synthetic.main.overview_fragment.overview_treatmentbutton -import kotlinx.android.synthetic.main.overview_fragment.overview_wizardbutton import kotlinx.android.synthetic.main.overview_fragment_nsclient_tablet.* +import kotlinx.android.synthetic.main.overview_graphs_layout.overview_bggraph +import kotlinx.android.synthetic.main.overview_graphs_layout.overview_chartMenuButton +import kotlinx.android.synthetic.main.overview_graphs_layout.overview_iobcalculationprogess +import kotlinx.android.synthetic.main.overview_graphs_layout.overview_iobgraph +import kotlinx.android.synthetic.main.overview_info_layout.* +import kotlinx.android.synthetic.main.overview_info_layout.overview_arrow +import kotlinx.android.synthetic.main.overview_info_layout.overview_basebasal +import kotlinx.android.synthetic.main.overview_info_layout.overview_bg +import kotlinx.android.synthetic.main.overview_info_layout.overview_cob +import kotlinx.android.synthetic.main.overview_info_layout.overview_extendedbolus +import kotlinx.android.synthetic.main.overview_info_layout.overview_iob +import kotlinx.android.synthetic.main.overview_info_layout.overview_sensitivity +import kotlinx.android.synthetic.main.overview_loop_pumpstatus_layout.* +import kotlinx.android.synthetic.main.overview_statuslights_layout.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch @@ -140,6 +134,10 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList @Inject lateinit var protectionCheck: ProtectionCheck @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() @@ -170,19 +168,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList smallHeight = screenHeight <= Constants.SMALL_HEIGHT val landscape = screenHeight < screenWidth - return when { - resourceHelper.gb(R.bool.isTablet) && Config.NSCLIENT -> - inflater.inflate(R.layout.overview_fragment_nsclient_tablet, container, false) - - Config.NSCLIENT -> - inflater.inflate(R.layout.overview_fragment_nsclient, container, false) - - smallHeight || landscape -> - inflater.inflate(R.layout.overview_fragment_landscape, container, false) - - else -> - inflater.inflate(R.layout.overview_fragment, container, false) - } + return inflater.inflate(skinProvider.activeSkin().overviewLayout(landscape, resourceHelper.gb(R.bool.isTablet), smallHeight), container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { @@ -226,7 +212,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList super.onPause() disposable.clear() loopHandler.removeCallbacksAndMessages(null) - overview_apsmode?.let { unregisterForContextMenu(it) } + overview_apsmode_llayout?.let { unregisterForContextMenu(it) } overview_activeprofile?.let { unregisterForContextMenu(it) } overview_temptarget?.let { unregisterForContextMenu(it) } } @@ -300,7 +286,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } loopHandler.postDelayed(refreshLoop, 60 * 1000L) - overview_apsmode?.let { registerForContextMenu(overview_apsmode) } + overview_apsmode_llayout?.let { registerForContextMenu(overview_apsmode) } overview_activeprofile?.let { registerForContextMenu(it) } overview_temptarget?.let { registerForContextMenu(it) } updateGUI("onResume") @@ -312,26 +298,20 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } override fun onContextItemSelected(item: MenuItem): Boolean { - val manager = fragmentManager - return if (manager != null && overviewMenus.onContextItemSelected(item, manager)) true else super.onContextItemSelected(item) + return if (overviewMenus.onContextItemSelected(item, childFragmentManager)) true else super.onContextItemSelected(item) } override fun onClick(v: View) { - val manager = fragmentManager ?: return // 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 (manager.isStateSaved) return + if (childFragmentManager.isStateSaved) return activity?.let { activity -> when (v.id) { - R.id.overview_treatmentbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { TreatmentDialog().show(manager, "Overview") }) - R.id.overview_wizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { WizardDialog().show(manager, "Overview") }) - R.id.overview_insulinbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { InsulinDialog().show(manager, "Overview") }) - R.id.overview_quickwizardbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { onClickQuickWizard() }) - R.id.overview_carbsbutton -> protectionCheck.queryProtection(activity, ProtectionCheck.Protection.BOLUS, Runnable { CarbsDialog().show(manager, "Overview") }) - - R.id.overview_pumpstatus -> { - if (activePlugin.activePump.isSuspended || !activePlugin.activePump.isInitialized) commandQueue.readStatus("RefreshClicked", null) - } + 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)) @@ -346,7 +326,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList R.id.overview_calibrationbutton -> { if (xdripPlugin.isEnabled(PluginType.BGSOURCE)) { - CalibrationDialog().show(manager, "CalibrationDialog") + CalibrationDialog().show(childFragmentManager, "CalibrationDialog") } else if (dexcomPlugin.isEnabled(PluginType.BGSOURCE)) { try { dexcomPlugin.findDexcomPackageName()?.let { @@ -534,7 +514,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList 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) @@ -565,14 +545,14 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_bg?.text = lastBG.valueToUnitsToString(units) overview_bg?.setTextColor(color) - overview_arrow?.text = lastBG.directionToSymbol() + overview_arrow?.text = lastBG.directionToSymbol(databaseHelper) overview_arrow?.setTextColor(color) val glucoseStatus = GlucoseStatus(injector).glucoseStatusData if (glucoseStatus != null) { - overview_delta?.text = "Δ ${Profile.toUnitsString(glucoseStatus.delta, glucoseStatus.delta * Constants.MGDL_TO_MMOLL, units)} $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 = "Δ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)}" } else { overview_delta?.text = "Δ " + resourceHelper.gs(R.string.notavailable) overview_deltashort?.text = "---" @@ -594,56 +574,75 @@ 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(PluginType.LOOP) && loopPlugin.isSuperBolus -> { - overview_apsmode?.text = String.format(resourceHelper.gs(R.string.loopsuperbolusfor), loopPlugin.minutesToEndOfSuspend()) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) + loopPlugin.isEnabled() && loopPlugin.isSuperBolus -> { + overview_apsmode.setImageResource(R.drawable.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?.text = String.format(resourceHelper.gs(R.string.loopdisconnectedfor), loopPlugin.minutesToEndOfSuspend()) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonCritical)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextCritical)) + loopPlugin.isDisconnected -> { + overview_apsmode.setImageResource(R.drawable.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(PluginType.LOOP) && loopPlugin.isSuspended -> { - overview_apsmode?.text = String.format(resourceHelper.gs(R.string.loopsuspendedfor), loopPlugin.minutesToEndOfSuspend()) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) + loopPlugin.isEnabled() && loopPlugin.isSuspended -> { + overview_apsmode.setImageResource(R.drawable.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?.text = resourceHelper.gs(R.string.pumpsuspended) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextWarning)) + pump.isSuspended -> { + overview_apsmode.setImageResource(R.drawable.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(PluginType.LOOP) -> { - val isLGS = loopPlugin.isLGS - overview_apsmode?.text = - if (closedLoopEnabled.value()) - if (isLGS) - resourceHelper.gs(R.string.lgs) - else - resourceHelper.gs(R.string.closedloop) - else - resourceHelper.gs(R.string.openloop) - - overview_apsmode?.setBackgroundColor(if (isLGS) resourceHelper.gc(R.color.ribbonUnusual) else resourceHelper.gc(R.color.ribbonDefault)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextDefault)) + loopPlugin.isEnabled() && closedLoopEnabled.value() && loopPlugin.isLGS -> { + overview_apsmode.setImageResource(R.drawable.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)) } - else -> { - overview_apsmode?.text = resourceHelper.gs(R.string.disabledloop) - overview_apsmode?.setBackgroundColor(resourceHelper.gc(R.color.ribbonCritical)) - overview_apsmode?.setTextColor(resourceHelper.gc(R.color.ribbonTextCritical)) + loopPlugin.isEnabled() && closedLoopEnabled.value() -> { + overview_apsmode.setImageResource(R.drawable.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_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_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 } // temp target @@ -660,9 +659,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList // Basal, TBR val activeTemp = treatmentsPlugin.getTempBasalFromHistory(System.currentTimeMillis()) - overview_basebasal?.text = activeTemp?.let { if (resourceHelper.shortTextMode()) "T: " + activeTemp.toStringVeryShort() else activeTemp.toStringFull() } + overview_basebasal?.text = activeTemp?.let { if (resourceHelper.shortTextMode()) "T:" + activeTemp.toStringVeryShort() else activeTemp.toStringFull() } ?: resourceHelper.gs(R.string.pump_basebasalrate, profile.basal) - overview_basebasal?.setOnClickListener { + overview_basal_llayout?.setOnClickListener { var fullText = "${resourceHelper.gs(R.string.pump_basebasalrate_label)}: ${resourceHelper.gs(R.string.pump_basebasalrate, profile.basal)}" if (activeTemp != null) fullText += "\n" + resourceHelper.gs(R.string.pump_tempbasal_label) + ": " + activeTemp.toStringFull() @@ -672,6 +671,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } 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) // Extended bolus val extendedBolus = treatmentsPlugin.getExtendedBolusFromHistory(System.currentTimeMillis()) @@ -684,7 +684,9 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList OKDialog.show(it, resourceHelper.gs(R.string.extended_bolus), extendedBolus.toString()) } } + overview_extended_llayout?.visibility = (extendedBolus != null && !pump.isFakingTempsByExtendedBoluses).toVisibility() + // Active profile overview_activeprofile?.text = profileFunction.getProfileNameWithDuration() if (profile.percentage != 100 || profile.timeshift != 0) { overview_activeprofile?.setBackgroundColor(resourceHelper.gc(R.color.ribbonWarning)) @@ -702,23 +704,15 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList val bolusIob = treatmentsPlugin.lastCalculationTreatments.round() val basalIob = treatmentsPlugin.lastCalculationTempBasals.round() overview_iob?.text = when { - resourceHelper.shortTextMode() -> { + resourceHelper.shortTextMode() -> resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) - } - resourceHelper.gb(R.bool.isTablet) -> { - resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + " (" + - resourceHelper.gs(R.string.bolus) + ": " + resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob) + - resourceHelper.gs(R.string.basal) + ": " + resourceHelper.gs(R.string.formatinsulinunits, basalIob.basaliob) + ")" - } - - else -> { + else -> resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + " (" + resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob) + "/" + resourceHelper.gs(R.string.formatinsulinunits, basalIob.basaliob) + ")" - } } - overview_iob?.setOnClickListener { + overview_iob_llayout?.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.iob), resourceHelper.gs(R.string.formatinsulinunits, bolusIob.iob + basalIob.basaliob) + "\n" + @@ -729,29 +723,29 @@ 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 var cobText: String = resourceHelper.gs(R.string.value_unavailable_short) val cobInfo = iobCobCalculatorPlugin.getCobInfo(false, "Overview COB") if (cobInfo.displayCob != null) { - cobText = DecimalFormatter.to0Decimal(cobInfo.displayCob) + 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 - if (Config.APS && lastRun?.constraintsProcessed != null && lastRun?.constraintsProcessed.carbsReq > 0) { - overview_cob_required.visibility = View.VISIBLE - var carbsRequiredString: String = String.format(resourceHelper.gs(R.string.overview_carbs_required), lastRun?.constraintsProcessed?.carbsReq, lastRun?.constraintsProcessed?.carbsReqWithin) - overview_cob_required.text = carbsRequiredString - } else { - overview_cob_required.visibility = View.GONE - } + // if (config.APS && lastRun?.constraintsProcessed != null && lastRun?.constraintsProcessed.carbsReq > 0) { + // overview_cob_required.visibility = View.VISIBLE + // var carbsRequiredString: String = String.format(resourceHelper.gs(R.string.overview_carbs_required), lastRun?.constraintsProcessed?.carbsReq, lastRun?.constraintsProcessed?.carbsReqWithin) + // overview_cob_required.text = carbsRequiredString + // } else { + // overview_cob_required.visibility = View.GONE + // } - val predictionsAvailable = if (Config.APS) lastRun?.request?.hasPredictions == true else Config.NSCLIENT + val predictionsAvailable = if (config.APS) lastRun?.request?.hasPredictions == true else config.NSCLIENT // pump status from ns overview_pump?.text = nsDeviceStatus.pumpStatus @@ -766,9 +760,10 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList overview_uploader?.setOnClickListener { activity?.let { OKDialog.show(it, resourceHelper.gs(R.string.uploader), nsDeviceStatus.extendedUploaderStatus) } } // Sensitivity - iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData -> - overview_sensitivity?.text = String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100) - } + overview_sensitivity?.text = + iobCobCalculatorPlugin.getLastAutosensData("Overview")?.let { autosensData -> + String.format(Locale.ENGLISH, "%.0f%%", autosensData.autosensResult.ratio * 100) + } ?: "" // ****** GRAPH ******* GlobalScope.launch(Dispatchers.Main) { @@ -789,7 +784,7 @@ 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) @@ -885,4 +880,4 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList } } } -} \ 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..69c6f84cb2 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,7 +57,8 @@ 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) { @@ -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) 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..188ce707db 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 diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt index 52b62790da..fe43913333 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/events/EventOverviewBolusProgress.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.plugins.general.overview.events -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.events.Event object EventOverviewBolusProgress : Event() { 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..02ccf1480f 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 @@ -21,7 +21,7 @@ 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 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 fd1ca3fce1..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 @@ -24,6 +24,7 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.services.AlarmSoundService import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import java.util.* @@ -36,7 +37,9 @@ class NotificationStore @Inject constructor( private val sp: SP, private val rxBus: RxBusWrapper, private val resourceHelper: ResourceHelper, - private val context: Context + private val context: Context, + private val iconsProvider: IconsProvider, + private val dateUtil: DateUtil ) { var store: MutableList = ArrayList() @@ -109,8 +112,8 @@ class NotificationStore @Inject constructor( private fun raiseSystemNotification(n: Notification) { val mgr = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - val largeIcon = resourceHelper.decodeResource(resourceHelper.getIcon()) - val smallIcon = resourceHelper.getNotificationIcon() + val largeIcon = resourceHelper.decodeResource(iconsProvider.getIcon()) + val smallIcon = iconsProvider.getNotificationIcon() val sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM) val notificationBuilder = NotificationCompat.Builder(context, CHANNEL_ID) .setSmallIcon(smallIcon) @@ -190,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/persistentNotification/PersistentNotificationPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/PersistentNotificationPlugin.kt index cabbf3b1ef..e8d32ed386 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 @@ -14,20 +14,18 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.R import info.nightscout.androidaps.data.Profile +import info.nightscout.androidaps.db.DatabaseHelper 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 import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.androidNotification.NotificationHolder +import info.nightscout.androidaps.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers @@ -45,7 +43,9 @@ class PersistentNotificationPlugin @Inject constructor( private var iobCobCalculatorPlugin: IobCobCalculatorPlugin, private var rxBus: RxBusWrapper, private var context: Context, - private var notificationHolder: NotificationHolder + private var notificationHolder: NotificationHolder, + private val iconsProvider: IconsProvider, + private val databaseHelper: DatabaseHelperInterface ) : PluginBase(PluginDescription() .mainType(PluginType.GENERAL) .neverVisible(true) @@ -145,7 +145,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) + @@ -209,8 +209,8 @@ class PersistentNotificationPlugin @Inject constructor( builder.setOngoing(true) builder.setOnlyAlertOnce(true) builder.setCategory(NotificationCompat.CATEGORY_STATUS) - builder.setSmallIcon(resourceHelper.getNotificationIcon()) - builder.setLargeIcon(resourceHelper.decodeResource(resourceHelper.getIcon())) + builder.setSmallIcon(iconsProvider.getNotificationIcon()) + builder.setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) if (line1 != null) builder.setContentTitle(line1) if (line2 != null) builder.setContentText(line2) if (line3 != null) builder.setSubText(line3) 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..7aa94f1dcc 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) @@ -612,7 +614,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 +715,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..8aed0f5288 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 @@ -20,7 +20,7 @@ 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 @@ -67,7 +67,9 @@ class ActionStringHandler @Inject constructor( private val danaRSPlugin: DanaRSPlugin, private val danaRPump: DanaRPump, 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 @@ -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) @@ -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!" 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..e0a0657826 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"); @@ -712,7 +713,7 @@ 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; } else { 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/IobCobCalculatorPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.java index c35e3797dc..c38c286122 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,20 @@ 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.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 +57,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 +69,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(); @@ -96,7 +99,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 +121,7 @@ public class IobCobCalculatorPlugin extends PluginBase { this.sensitivityAAPSPlugin = sensitivityAAPSPlugin; this.sensitivityWeightedAveragePlugin = sensitivityWeightedAveragePlugin; this.fabricPrivacy = fabricPrivacy; + this.dateUtil = dateUtil; } @Override @@ -245,10 +250,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)); } } @@ -438,7 +443,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.dateAndTimeString(oldestDataAvailable)); } else getBGDataFrom = (long) (from - T.hours(1).msecs() * (24 + dia)); return getBGDataFrom; @@ -673,7 +678,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.dateAndTimeString(data.time)); return null; } else { getAapsLogger().debug(LTag.AUTOSENS, "AUTOSENSDATA (" + reason + ") " + data.toString()); @@ -681,9 +686,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.dateAndTimeString(autosensDataTable.valueAt(autosensDataTable.size() - 1).time); else return "autosensDataTable empty"; } @@ -805,7 +811,7 @@ 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.dateAndTimeString(end)); if (thread == null || thread.getState() == Thread.State.TERMINATED) { if (sensitivityOref1Plugin.isEnabled()) thread = new IobCobOref1Thread(injector, from, end, bgDataReload, limitDataToOldestAvailable, cause); @@ -822,10 +828,10 @@ public class IobCobCalculatorPlugin extends PluginBase { 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.dateAndTimeString(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.dateAndTimeString(iobTable.keyAt(index))); iobTable.removeAt(index); } else { break; @@ -833,7 +839,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.dateAndTimeString(absIobTable.keyAt(index))); absIobTable.removeAt(index); } else { break; @@ -841,7 +847,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.dateAndTimeString(autosensDataTable.keyAt(index))); autosensDataTable.removeAt(index); } else { break; @@ -849,7 +855,7 @@ 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.dateAndTimeString(basalDataTable.keyAt(index))); basalDataTable.removeAt(index); } else { break; 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..457b16716a 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,15 @@ 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.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.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -67,6 +68,7 @@ public class IobCobOref1Thread extends Thread { @Inject BuildHelper buildHelper; @Inject Profiler profiler; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private final HasAndroidInjector injector; private boolean bgDataReload; @@ -121,7 +123,7 @@ public class IobCobOref1Thread extends Thread { } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); + 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--) { @@ -240,7 +242,8 @@ public class IobCobOref1Thread extends Thread { List recentCarbTreatments = activePluginProvider.getActiveTreatments().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 +280,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; @@ -375,7 +379,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..84a02005e1 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,15 @@ 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.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.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -64,6 +65,7 @@ public class IobCobThread extends Thread { @Inject BuildHelper buildHelper; @Inject Profiler profiler; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private final HasAndroidInjector injector; private boolean bgDataReload; @@ -118,7 +120,7 @@ public class IobCobThread extends Thread { } long prevDataTime = IobCobCalculatorPlugin.roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date); - aapsLogger.debug(LTag.AUTOSENS, "Prev data time: " + DateUtil.dateAndTimeString(prevDataTime)); + 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--) { @@ -237,7 +239,8 @@ public class IobCobThread extends Thread { List recentCarbTreatments = activePluginProvider.getActiveTreatments().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 +271,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 +303,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/profile/local/LocalProfileFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfileFragment.kt index 3acf960195..ef64d4a690 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() @@ -103,14 +106,14 @@ class LocalProfileFragment : DaggerFragment() { 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.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.nsprofileview_ic_label), localProfilePlugin.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.nsprofileview_basal_label) + ": " + sumLabel(), localProfilePlugin.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.nsprofileview_isf_label), localProfilePlugin.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.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) } 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.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, aapsLogger, dateUtil, 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) } // Spinner @@ -178,7 +181,7 @@ class LocalProfileFragment : DaggerFragment() { localprofile_profileswitch.setOnClickListener { // TODO: select in dialog localProfilePlugin.currentProfileIndex - fragmentManager?.let { ProfileSwitchDialog().show(it, "NewNSTreatmentDialog") } + ProfileSwitchDialog().show(childFragmentManager, "NewNSTreatmentDialog") } localprofile_reset.setOnClickListener { @@ -187,10 +190,10 @@ class LocalProfileFragment : DaggerFragment() { 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) + TimeListEdit(context, aapsLogger, dateUtil, 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, aapsLogger, dateUtil, 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, aapsLogger, dateUtil, 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_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() } 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..8d2761cfa3 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,7 +5,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.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 @@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.ProfileInterface 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.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter @@ -53,11 +53,6 @@ class LocalProfilePlugin @Inject constructor( private val defaultArray = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]" - companion object { - @JvmStatic - val LOCAL_PROFILE = "LocalProfile" - } - override fun onStart() { super.onStart() loadSettings() @@ -122,7 +117,7 @@ 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 + "_" + val LOCAL_PROFILE_NUMBERED = Constants.LOCAL_PROFILE + "_" + i + "_" sp.putString(LOCAL_PROFILE_NUMBERED + "name", name!!) sp.putBoolean(LOCAL_PROFILE_NUMBERED + "mgdl", mgdl) sp.putDouble(LOCAL_PROFILE_NUMBERED + "dia", dia) @@ -133,7 +128,7 @@ class LocalProfilePlugin @Inject constructor( sp.putString(LOCAL_PROFILE_NUMBERED + "targethigh", targetHigh.toString()) } } - sp.putInt(LOCAL_PROFILE + "_profiles", numOfProfiles) + sp.putInt(Constants.LOCAL_PROFILE + "_profiles", numOfProfiles) createAndStoreConvertedProfile() isEdited = false @@ -154,20 +149,20 @@ class LocalProfilePlugin @Inject constructor( @Synchronized fun loadSettings() { - if (sp.contains(LOCAL_PROFILE + "mgdl")) { + if (sp.contains(Constants.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 for (i in 0 until numOfProfiles) { val p = SingleProfile() - val LOCAL_PROFILE_NUMBERED = LOCAL_PROFILE + "_" + i + "_" + val LOCAL_PROFILE_NUMBERED = Constants.LOCAL_PROFILE + "_" + i + "_" - p.name = sp.getString(LOCAL_PROFILE_NUMBERED + "name", LOCAL_PROFILE + i) + p.name = sp.getString(LOCAL_PROFILE_NUMBERED + "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) @@ -240,10 +235,10 @@ class LocalProfilePlugin @Inject constructor( 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) + p.mgdl = sp.getBoolean(Constants.LOCAL_PROFILE + "mgdl", profileFunction.getUnits() == Constants.MGDL) + p.dia = sp.getDouble(Constants.LOCAL_PROFILE + "dia", Constants.defaultDIA) try { - p.ic = JSONArray(sp.getString(LOCAL_PROFILE + "ic", defaultArray)) + p.ic = JSONArray(sp.getString(Constants.LOCAL_PROFILE + "ic", defaultArray)) } catch (e1: JSONException) { try { p.ic = JSONArray(defaultArray) @@ -252,7 +247,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.isf = JSONArray(sp.getString(LOCAL_PROFILE + "isf", defaultArray)) + p.isf = JSONArray(sp.getString(Constants.LOCAL_PROFILE + "isf", defaultArray)) } catch (e1: JSONException) { try { p.isf = JSONArray(defaultArray) @@ -261,7 +256,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.basal = JSONArray(sp.getString(LOCAL_PROFILE + "basal", defaultArray)) + p.basal = JSONArray(sp.getString(Constants.LOCAL_PROFILE + "basal", defaultArray)) } catch (e1: JSONException) { try { p.basal = JSONArray(defaultArray) @@ -270,7 +265,7 @@ class LocalProfilePlugin @Inject constructor( } try { - p.targetLow = JSONArray(sp.getString(LOCAL_PROFILE + "targetlow", defaultArray)) + p.targetLow = JSONArray(sp.getString(Constants.LOCAL_PROFILE + "targetlow", defaultArray)) } catch (e1: JSONException) { try { p.targetLow = JSONArray(defaultArray) @@ -279,23 +274,23 @@ class LocalProfilePlugin @Inject constructor( } try { - p.targetHigh = JSONArray(sp.getString(LOCAL_PROFILE + "targethigh", defaultArray)) + p.targetHigh = JSONArray(sp.getString(Constants.LOCAL_PROFILE + "targethigh", defaultArray)) } catch (e1: JSONException) { try { p.targetHigh = JSONArray(defaultArray) } catch (ignored: JSONException) { } } - p.name = LOCAL_PROFILE + p.name = Constants.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") + sp.remove(Constants.LOCAL_PROFILE + "mgdl") + sp.remove(Constants.LOCAL_PROFILE + "mmol") + sp.remove(Constants.LOCAL_PROFILE + "dia") + sp.remove(Constants.LOCAL_PROFILE + "ic") + sp.remove(Constants.LOCAL_PROFILE + "isf") + sp.remove(Constants.LOCAL_PROFILE + "basal") + sp.remove(Constants.LOCAL_PROFILE + "targetlow") + sp.remove(Constants.LOCAL_PROFILE + "targethigh") currentProfileIndex = 0 numOfProfiles = 1 @@ -352,13 +347,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) 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..ace9df0a97 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 @@ -44,7 +44,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 +65,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; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java index 126b017b5e..0bb38acb76 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.java @@ -37,9 +37,8 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewB import info.nightscout.androidaps.plugins.pump.common.data.PumpStatus; import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkService; import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; @@ -66,6 +65,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI protected ResourceHelper resourceHelper; protected CommandQueueProvider commandQueue; protected SP sp; + protected DateUtil dateUtil; /* protected static final PumpEnactResult OPERATION_NOT_SUPPORTED = new PumpEnactResult().success(false) @@ -93,7 +93,8 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI ActivePluginProvider activePlugin, SP sp, Context context, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + DateUtil dateUtil ) { super(pluginDescription, injector, aapsLogger, resourceHelper, commandQueue); @@ -108,7 +109,7 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI pumpDescription.setPumpDescription(pumpType); this.pumpType = pumpType; - + this.dateUtil = dateUtil; } @@ -346,14 +347,14 @@ public abstract class PumpPluginAbstract extends PumpPluginBase implements PumpI if (tb != null) { extended.put("TempBasalAbsoluteRate", tb.tempBasalConvertedToAbsolute(System.currentTimeMillis(), profile)); - extended.put("TempBasalStart", DateUtil.dateAndTimeString(tb.date)); + extended.put("TempBasalStart", dateUtil.dateAndTimeString(tb.date)); extended.put("TempBasalRemaining", tb.getPlannedRemainingMinutes()); } ExtendedBolus eb = activePlugin.getActiveTreatments().getExtendedBolusFromHistory(System.currentTimeMillis()); 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()); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java index 34a3418902..3c51b484e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/data/PumpStatus.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.common.data; import java.util.Date; -import info.nightscout.androidaps.data.ProfileStore; +import info.nightscout.androidaps.interfaces.ProfileStore; import info.nightscout.androidaps.plugins.pump.common.defs.PumpStatusType; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; 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 index 48d1df3b9d..bbe96c41c5 100644 --- 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 @@ -6,6 +6,7 @@ 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. diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java index 623ecae9ef..bec19c7d1f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.java @@ -32,6 +32,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -45,6 +46,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re @Inject MedtronicUtil medtronicUtil; @Inject AAPSLogger aapsLogger; @Inject RileyLinkServiceData rileyLinkServiceData; + @Inject DateUtil dateUtil; TextView connectionStatus; TextView configuredAddress; @@ -148,7 +150,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re rileyLinkServiceData.lastGoodFrequency)); if (medtronicPumpStatus.lastConnection != 0) - this.lastDeviceContact.setText(StringUtil.toDateTimeString(new LocalDateTime( + this.lastDeviceContact.setText(StringUtil.toDateTimeString(dateUtil, new LocalDateTime( medtronicPumpStatus.lastDataTime))); else this.lastDeviceContact.setText(resourceHelper.gs(R.string.common_never)); @@ -182,7 +184,7 @@ public class RileyLinkStatusGeneralFragment extends DaggerFragment implements Re rileyLinkServiceData.lastGoodFrequency)); if (omnipodPumpStatus.lastConnection != 0) - this.lastDeviceContact.setText(StringUtil.toDateTimeString(new LocalDateTime( + this.lastDeviceContact.setText(StringUtil.toDateTimeString(dateUtil, new LocalDateTime( omnipodPumpStatus.lastDataTime))); else this.lastDeviceContact.setText(resourceHelper.gs(R.string.common_never)); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java index f8f79c821a..8a3ff18207 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.java @@ -34,6 +34,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re @Inject RileyLinkUtil rileyLinkUtil; @Inject ResourceHelper resourceHelper; + @Inject DateUtil dateUtil; RecyclerView recyclerView; RecyclerViewAdapter recyclerViewAdapter; @@ -136,7 +137,7 @@ public class RileyLinkStatusHistoryFragment extends DaggerFragment implements Re RLHistoryItem item = historyList.get(position); if (item != null) { - holder.timeView.setText(DateUtil.dateAndTimeAndSecondsString(item.getDateTime().toDateTime().getMillis())); + holder.timeView.setText(dateUtil.dateAndTimeAndSecondsString(item.getDateTime().toDateTime().getMillis())); holder.typeView.setText(item.getSource().getDesc()); holder.valueView.setText(item.getDescription(resourceHelper)); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java index f7d3b686e0..4beea20154 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkBroadcastReceiver.java @@ -20,11 +20,13 @@ import javax.inject.Inject; import dagger.android.DaggerBroadcastReceiver; import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.DiscoverGattServicesTask; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.tasks.InitializePumpManagerTask; @@ -45,10 +47,11 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { @Inject AAPSLogger aapsLogger; @Inject RileyLinkServiceData rileyLinkServiceData; @Inject ServiceTaskExecutor serviceTaskExecutor; + @Inject ActivePluginProvider activePlugin; RileyLinkService serviceInstance; protected Map> broadcastIdentifiers = null; - String deviceSpecificPrefix; + //String deviceSpecificPrefix; public RileyLinkBroadcastReceiver(RileyLinkService serviceInstance) { this.serviceInstance = serviceInstance; @@ -80,12 +83,18 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { RileyLinkConst.Intents.RileyLinkDisconnect)); // Device Specific - deviceSpecificPrefix = serviceInstance.getDeviceSpecificBroadcastsIdentifierPrefix(); + // TODO remove from service instance + //deviceSpecificPrefix = serviceInstance.getDeviceSpecificBroadcastsIdentifierPrefix(); // Application specific } + private RileyLinkService getServiceInstance() { + RileyLinkPumpDevice pumpDevice = (RileyLinkPumpDevice)activePlugin.getActivePump(); + return pumpDevice.getRileyLinkService(); + } + @Override public void onReceive(Context context, Intent intent) { @@ -103,7 +112,6 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { if (!processBluetoothBroadcasts(action) && // !processRileyLinkBroadcasts(action, context) && // !processTuneUpBroadcasts(action) && // - !processDeviceSpecificBroadcasts(action, intent) && // !processApplicationSpecificBroadcasts(action, intent) // ) { aapsLogger.error(LTag.PUMPCOMM, "Unhandled broadcast: action=" + action); @@ -124,16 +132,14 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } } - if (deviceSpecificPrefix != null) { - serviceInstance.registerDeviceSpecificBroadcasts(intentFilter); - } - LocalBroadcastManager.getInstance(context).registerReceiver(this, intentFilter); } private boolean processRileyLinkBroadcasts(String action, Context context) { + RileyLinkService rileyLinkService = getServiceInstance(); + if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnected)) { if (BluetoothAdapter.getDefaultAdapter().isEnabled()) { rileyLinkServiceData.setServiceState(RileyLinkServiceState.BluetoothError, RileyLinkError.RileyLinkUnreachable); @@ -147,20 +153,20 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { aapsLogger.warn(LTag.PUMPCOMM, "MedtronicConst.Intents.RileyLinkReady"); // sendIPCNotification(RT2Const.IPC.MSG_note_WakingPump); - serviceInstance.rileyLinkBLE.enableNotifications(); - serviceInstance.rfspy.startReader(); // call startReader from outside? + rileyLinkService.rileyLinkBLE.enableNotifications(); + rileyLinkService.rfspy.startReader(); // call startReader from outside? - serviceInstance.rfspy.initializeRileyLink(); - String bleVersion = serviceInstance.rfspy.getBLEVersionCached(); + rileyLinkService.rfspy.initializeRileyLink(); + String bleVersion = rileyLinkService.rfspy.getBLEVersionCached(); RileyLinkFirmwareVersion rlVersion = rileyLinkServiceData.firmwareVersion; // if (isLoggingEnabled()) aapsLogger.debug(LTag.PUMPCOMM, "RfSpy version (BLE113): " + bleVersion); - serviceInstance.rileyLinkServiceData.versionBLE113 = bleVersion; + rileyLinkService.rileyLinkServiceData.versionBLE113 = bleVersion; // if (isLoggingEnabled()) aapsLogger.debug(LTag.PUMPCOMM, "RfSpy Radio version (CC110): " + rlVersion.name()); - serviceInstance.rileyLinkServiceData.versionCC110 = rlVersion; + this.rileyLinkServiceData.versionCC110 = rlVersion; ServiceTask task = new InitializePumpManagerTask(injector, context); serviceTaskExecutor.startTask(task); @@ -174,13 +180,13 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } else { // showBusy("Configuring Service", 50); // rileyLinkBLE.findRileyLink(RileylinkBLEAddress); - serviceInstance.reconfigureRileyLink(RileylinkBLEAddress); + rileyLinkService.reconfigureRileyLink(RileylinkBLEAddress); // MainApp.getServiceClientConnection().setThisRileylink(RileylinkBLEAddress); } return true; } else if (action.equals(RileyLinkConst.Intents.RileyLinkDisconnect)) { - serviceInstance.disconnectRileyLink(); + rileyLinkService.disconnectRileyLink(); return true; } else { @@ -201,7 +207,7 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } else if (action.equals(RileyLinkConst.Intents.BluetoothReconnected)) { aapsLogger.debug(LTag.PUMPCOMM, "Bluetooth - Reconnecting"); - serviceInstance.bluetoothInit(); + getServiceInstance().bluetoothInit(); serviceTaskExecutor.startTask(new DiscoverGattServicesTask(injector, true)); return true; @@ -209,7 +215,6 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { return false; } - } @@ -226,19 +231,6 @@ public class RileyLinkBroadcastReceiver extends DaggerBroadcastReceiver { } - public boolean processDeviceSpecificBroadcasts(String action, Intent intent) { - - if (this.deviceSpecificPrefix == null) { - return false; - } - - if (action.startsWith(this.deviceSpecificPrefix)) { - return serviceInstance.handleDeviceSpecificBroadcasts(intent); - } else - return false; - } - - public boolean processApplicationSpecificBroadcasts(String action, Intent intent) { return false; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java index 383eb57cb6..a9d84d63d5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/DiscoverGattServicesTask.java @@ -3,15 +3,19 @@ package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.task import javax.inject.Inject; import dagger.android.HasAndroidInjector; -import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil; -import info.nightscout.androidaps.plugins.pump.medtronic.MedtronicPumpPlugin; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice; /** * Created by geoff on 7/9/16. */ public class DiscoverGattServicesTask extends ServiceTask { - @Inject MedtronicPumpPlugin medtronicPumpPlugin; + @Inject ActivePluginProvider activePlugin; + @Inject AAPSLogger aapsLogger; public boolean needToConnect = false; @@ -30,9 +34,18 @@ public class DiscoverGattServicesTask extends ServiceTask { @Override public void run() { - if (needToConnect) - medtronicPumpPlugin.getRileyLinkService().getRileyLinkBLE().connectGatt(); + if (activePlugin.getActivePump().model() == PumpType.Insulet_Omnipod_Dash) { + // TODO different init classes, this can be probably removed later + aapsLogger.warn(LTag.PUMPCOMM, "Discovery Gatt Services not implemeneted for Dash."); + return; + } - medtronicPumpPlugin.getRileyLinkService().getRileyLinkBLE().discoverServices(); + RileyLinkPumpDevice pumpDevice = (RileyLinkPumpDevice) activePlugin.getActivePump(); + + if (needToConnect) { + pumpDevice.getRileyLinkService().getRileyLinkBLE().connectGatt(); + } + + pumpDevice.getRileyLinkService().getRileyLinkBLE().discoverServices(); } -} +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java index 97a7adc018..73aab9c4f9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/tasks/InitializePumpManagerTask.java @@ -66,7 +66,6 @@ public class InitializePumpManagerTask extends ServiceTask { lastGoodFrequency = rileyLinkServiceData.lastGoodFrequency; } - // TODO Omnipod/Dagger needs refactoring RileyLinkCommunicationManager rileyLinkCommunicationManager = ((RileyLinkPumpDevice) activePlugin.getActivePump()).getRileyLinkService().getDeviceCommunicationManager(); if (activePlugin.getActivePump().manufacturer() == ManufacturerType.Medtronic) { @@ -102,9 +101,8 @@ public class InitializePumpManagerTask extends ServiceTask { rileyLinkServiceData.lastGoodFrequency = lastGoodFrequency; } - rileyLinkServiceData.setRileyLinkServiceState(RileyLinkServiceState.RileyLinkReady); - rileyLinkUtil.setRileyLinkTargetFrequency(RileyLinkTargetFrequency.Omnipod); + rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod; // TODO shouldn't be needed aapsLogger.info(LTag.PUMPCOMM, "Setting radio frequency to {} MHz", lastGoodFrequency); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java index f7d86e5774..cc9533e669 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/common/utils/StringUtil.java @@ -84,8 +84,8 @@ public class StringUtil { } - public static String toDateTimeString(LocalDateTime localDateTime) { - return DateUtil.dateAndTimeAndSecondsString(localDateTime.toDateTime().getMillis()); + public static String toDateTimeString(DateUtil dateUtil, LocalDateTime localDateTime) { + return dateUtil.dateAndTimeAndSecondsString(localDateTime.toDateTime().getMillis()); //return localDateTime.toString("dd.MM.yyyy HH:mm:ss"); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java index 4fe2815bdc..50a94b0ca9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/AbstractDanaRPlugin.java @@ -59,6 +59,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump protected RxBusWrapper rxBus; protected TreatmentsPlugin treatmentsPlugin; protected SP sp; + protected DateUtil dateUtil; protected AbstractDanaRPlugin( HasAndroidInjector injector, @@ -69,7 +70,8 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump CommandQueueProvider commandQueue, RxBusWrapper rxBus, TreatmentsPlugin treatmentsPlugin, - SP sp + SP sp, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.PUMP) @@ -85,6 +87,7 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump this.rxBus = rxBus; this.treatmentsPlugin = treatmentsPlugin; this.sp = sp; + this.dateUtil = dateUtil; } @Override @@ -349,19 +352,19 @@ public abstract class AbstractDanaRPlugin extends PumpPluginBase implements Pump 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("LastBolus", dateUtil.dateAndTimeString(pump.getLastBolusTime())); extended.put("LastBolusAmount", pump.getLastBolusAmount()); } TemporaryBasal tb = treatmentsPlugin.getRealTempBasalFromHistory(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()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt index 60420d6d70..3b4f84a4d8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRFragment.kt @@ -46,6 +46,7 @@ class DanaRFragment : DaggerFragment() { @Inject lateinit var danaRPump: DanaRPump @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var warnColors: WarnColors + @Inject lateinit var dateUtil: DateUtil private var disposable: CompositeDisposable = CompositeDisposable() @@ -71,21 +72,19 @@ class DanaRFragment : DaggerFragment() { danar_history.setOnClickListener { startActivity(Intent(context, DanaRHistoryActivity::class.java)) } danar_viewprofile.setOnClickListener { - fragmentManager?.let { fragmentManager -> - val profile = danaRPump.createConvertedProfile()?.getDefaultProfile() - ?: return@let - val profileName = danaRPump.createConvertedProfile()?.getDefaultProfileName() - ?: return@let - 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", profileName) - val pvd = ProfileViewerDialog() - pvd.arguments = args - pvd.show(fragmentManager, "ProfileViewDialog") - } + val profile = danaRPump.createConvertedProfile()?.getDefaultProfile() + ?: return@setOnClickListener + val profileName = danaRPump.createConvertedProfile()?.getDefaultProfileName() + ?: return@setOnClickListener + 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", profileName) + val pvd = ProfileViewerDialog() + pvd.arguments = args + pvd.show(childFragmentManager, "ProfileViewDialog") } danar_stats.setOnClickListener { startActivity(Intent(context, TDDStatsActivity::class.java)) } danar_user_options.setOnClickListener { startActivity(Intent(context, DanaRUserOptionsActivity::class.java)) } @@ -157,7 +156,7 @@ class DanaRFragment : DaggerFragment() { if (pump.lastConnection != 0L) { val agoMsec = System.currentTimeMillis() - pump.lastConnection val agoMin = (agoMsec.toDouble() / 60.0 / 1000.0).toInt() - danar_lastconnection.text = DateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")" + danar_lastconnection.text = dateUtil.timeString(pump.lastConnection) + " (" + resourceHelper.gs(R.string.minago, agoMin) + ")" warnColors.setColor(danar_lastconnection, agoMin.toDouble(), 16.0, 31.0) } if (pump.lastBolusTime != 0L) { @@ -165,7 +164,7 @@ class DanaRFragment : DaggerFragment() { val agoHours = agoMsec.toDouble() / 60.0 / 60.0 / 1000.0 if (agoHours < 6) // max 6h back - danar_lastbolus.text = DateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) + danar_lastbolus.text = dateUtil.timeString(pump.lastBolusTime) + " " + DateUtil.sinceString(pump.lastBolusTime, resourceHelper) + " " + resourceHelper.gs(R.string.formatinsulinunits, pump.lastBolusAmount) else danar_lastbolus.text = "" } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java index 3c6ce84c42..e1f06d4017 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPlugin.java @@ -29,8 +29,9 @@ import info.nightscout.androidaps.plugins.bus.RxBusWrapper; import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker; import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.services.DanaRExecutionService; -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.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -58,9 +59,10 @@ public class DanaRPlugin extends AbstractDanaRPlugin { TreatmentsPlugin treatmentsPlugin, SP sp, CommandQueueProvider commandQueue, - DanaRPump danaRPump + DanaRPump danaRPump, + DateUtil dateUtil ) { - super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt index 0621fd80ad..2f18df687e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/DanaRPump.kt @@ -4,10 +4,10 @@ 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.interfaces.ProfileStore import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.plugins.treatments.Treatment +import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.utils.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/SerialIOThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/SerialIOThread.java index 652ecf88b9..4b49d652a2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/SerialIOThread.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/SerialIOThread.java @@ -4,13 +4,13 @@ import android.bluetooth.BluetoothSocket; import android.os.SystemClock; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageBase; import info.nightscout.androidaps.plugins.pump.danaR.comm.MessageHashTableBase; @@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.CRC; * Created by mike on 17.07.2016. */ public class SerialIOThread extends AbstractSerialIOThread { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPBTCOMM); private InputStream mInputStream = null; private OutputStream mOutputStream = null; @@ -76,7 +76,7 @@ public class SerialIOThread extends AbstractSerialIOThread { message = hashTable.findMessage(command); } - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("<<<<< " + message.getMessageName() + " " + MessageBase.toHexString(extractedBuff)); // process the message content @@ -152,7 +152,7 @@ public class SerialIOThread extends AbstractSerialIOThread { processedMessage = message; byte[] messageBytes = message.getRawMessageBytes(); - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(">>>>> " + message.getMessageName() + " " + MessageBase.toHexString(messageBytes)); try { @@ -172,11 +172,11 @@ public class SerialIOThread extends AbstractSerialIOThread { SystemClock.sleep(200); if (!message.isReceived()) { message.handleMessageNotReceived(); - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.error("Reply not received " + message.getMessageName()); if (message.getCommand() == 0xF0F1) { danaRPump.setNewPump(false); - if (L.isEnabled(L.PUMPCOMM)) + if (L.isEnabled(LTag.PUMPCOMM)) log.debug("Old firmware detected"); } } @@ -188,28 +188,28 @@ public class SerialIOThread extends AbstractSerialIOThread { try { mInputStream.close(); } catch (Exception e) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(e.getMessage()); } try { mOutputStream.close(); } catch (Exception e) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(e.getMessage()); } try { mRfCommSocket.close(); } catch (Exception e) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(e.getMessage()); } try { System.runFinalization(); } catch (Exception e) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(e.getMessage()); } - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("Disconnected: " + reason); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt index 0daed24ddb..18ffab8460 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRHistoryActivity.kt @@ -21,7 +21,7 @@ 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.pump.danaR.comm.RecordTypes import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRSyncStatus import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin @@ -47,6 +47,7 @@ class DanaRHistoryActivity : NoSplashAppCompatActivity() { @Inject lateinit var danaRKoreanPlugin: DanaRKoreanPlugin @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var commandQueue: CommandQueueProvider + @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() @@ -143,7 +144,7 @@ class DanaRHistoryActivity : NoSplashAppCompatActivity() { override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) { val record = historyList[position] - holder.time.text = DateUtil.dateAndTimeString(record.recordDate) + holder.time.text = dateUtil.dateAndTimeString(record.recordDate) holder.value.text = DecimalFormatter.to2Decimal(record.recordValue) holder.stringValue.text = record.stringRecordValue holder.bolusType.text = record.bolusType diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt index 0c6a73a267..624b681dc5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/activities/DanaRUserOptionsActivity.kt @@ -11,7 +11,6 @@ import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.logging.AAPSLogger -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.danaR.DanaRPlugin @@ -71,16 +70,15 @@ class DanaRUserOptionsActivity : NoSplashAppCompatActivity() { save_user_options.setOnClickListener { onSaveClick() } - if (L.isEnabled(L.PUMP)) - aapsLogger.debug(LTag.PUMP, - "UserOptionsLoaded:" + (System.currentTimeMillis() - danaRPump.lastConnection) / 1000 + " s ago" - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nbuttonScroll:" + danaRPump.buttonScrollOnOff - + "\ntimeDisplayType:" + danaRPump.timeDisplayType - + "\nlcdOnTimeSec:" + danaRPump.lcdOnTimeSec - + "\nbackLight:" + danaRPump.backlightOnTimeSec - + "\npumpUnits:" + danaRPump.units - + "\nlowReservoir:" + danaRPump.lowReservoirRate) + aapsLogger.debug(LTag.PUMP, + "UserOptionsLoaded:" + (System.currentTimeMillis() - danaRPump.lastConnection) / 1000 + " s ago" + + "\ntimeDisplayType:" + danaRPump.timeDisplayType + + "\nbuttonScroll:" + danaRPump.buttonScrollOnOff + + "\ntimeDisplayType:" + danaRPump.timeDisplayType + + "\nlcdOnTimeSec:" + danaRPump.lcdOnTimeSec + + "\nbackLight:" + danaRPump.backlightOnTimeSec + + "\npumpUnits:" + danaRPump.units + + "\nlowReservoir:" + danaRPump.lowReservoirRate) danar_screentimeout.setParams(danaRPump.lcdOnTimeSec.toDouble(), 5.0, 240.0, 5.0, DecimalFormat("1"), false, save_user_options) danar_backlight.setParams(danaRPump.backlightOnTimeSec.toDouble(), 1.0, 60.0, 1.0, DecimalFormat("1"), false, save_user_options) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageBase.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageBase.java index f52d62d9c2..9ebf373795 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageBase.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MessageBase.java @@ -13,6 +13,7 @@ import java.util.Date; import java.util.GregorianCalendar; import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.utils.CRC; @@ -23,7 +24,7 @@ import info.nightscout.androidaps.utils.CRC; */ public class MessageBase { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private static Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPCOMM); public byte[] buffer = new byte[512]; private int position = 6; @@ -96,7 +97,7 @@ public class MessageBase { } public void handleMessage(byte[] bytes) { - if (L.isEnabled(L.PUMPCOMM)) { + if (L.isEnabled(LTag.PUMPCOMM)) { if (bytes.length > 6) { int command = (bytes[5] & 0xFF) | ((bytes[4] << 8) & 0xFF00); log.debug("UNPROCESSED MSG: " + getMessageName() + " Command: " + String.format("%04X", command) + " Data: " + toHexString(bytes)); 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 index a81408b381..dd4c59cee4 100644 --- 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 @@ -10,6 +10,7 @@ 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.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -27,7 +28,8 @@ class MessageHashTableR @Inject constructor( configBuilderPlugin: ConfigBuilderPlugin, commandQueue: CommandQueueProvider, activePlugin: ActivePluginProvider, - injector: HasAndroidInjector + injector: HasAndroidInjector, + dateUtil: DateUtil ) : MessageHashTableBase { var messages: HashMap = HashMap() @@ -39,11 +41,11 @@ class MessageHashTableR @Inject constructor( 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(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 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(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) 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 @@ -55,15 +57,15 @@ class MessageHashTableR @Inject constructor( 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(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS + put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS + put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE + put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM + put(MsgHistoryError(aapsLogger, rxBus, dateUtil)) // 0x3106 CMD_HISTORY_ERROR + put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY + put(MsgHistoryRefill(aapsLogger, rxBus, dateUtil)) // 0x3108 CMD_HISTORY_REFILL + put(MsgHistorySuspend(aapsLogger, rxBus, dateUtil)) // 0x3109 CMD_HISTORY_SUSPEND + put(MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil)) // 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)) @@ -74,7 +76,7 @@ class MessageHashTableR @Inject constructor( 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(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 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 @@ -83,9 +85,9 @@ class MessageHashTableR @Inject constructor( 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(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW + put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW // 0xF0F1 CMD_PUMP_CHECK_VALUE put(MsgCheckValue(aapsLogger, danaRPump, danaRPlugin)) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt index 695c3f1ec0..e0e2df7a90 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStart.kt @@ -4,7 +4,6 @@ import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump class MsgBolusStart( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt index 3ea3eed8f1..8080166af1 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgBolusStartWithSpeed.kt @@ -4,7 +4,6 @@ import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.pump.danaR.DanaRPlugin import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump class MsgBolusStartWithSpeed( 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 index 142d0fea04..97c942fbf1 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryAlarm( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3105) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.kt index 8c50099756..8b953a15f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgHistoryAll.kt @@ -10,7 +10,8 @@ import info.nightscout.androidaps.utils.DateUtil open class MsgHistoryAll( val aapsLogger: AAPSLogger, - val rxBus: RxBusWrapper + val rxBus: RxBusWrapper, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -138,6 +139,6 @@ open class MsgHistoryAll( 17.toByte() -> failed = true } MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord) - rxBus.send(EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)) + rxBus.send(EventDanaRSyncStatus(dateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)) } } \ 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 index 2f235f38d1..87bfbbc870 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryBasalHour( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x310A) 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 index 26e1506eac..693d56d462 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryBolus( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3101) 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 index 8650e251a8..23e060d2a7 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryCarbo( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3107) 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 index 60c1fffd14..5a978fc0ec 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryDailyInsulin( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3102) 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 index 50d6cb9051..8883a704a9 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryError( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3106) 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 index 07e2354f18..4f717dded1 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryGlucose( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3104) 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 index 0bf49cc612..b271f4f915 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryNew( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x42F2) 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 index d77d0fbca7..24bb799db8 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistoryRefill( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3108) 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 index d3f947f77d..bd116ed709 100644 --- 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 @@ -3,11 +3,13 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class MsgHistorySuspend( aapsLogger: AAPSLogger, - rxBus: RxBusWrapper -) : MsgHistoryAll(aapsLogger, rxBus) { + rxBus: RxBusWrapper, + dateUtil: DateUtil +) : MsgHistoryAll(aapsLogger, rxBus, dateUtil) { init { SetCommand(0x3109) diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.kt index 1ff8eb0e9b..7d1ded9f8f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgInitConnStatusTime.kt @@ -24,7 +24,8 @@ class MsgInitConnStatusTime( private val danaRPlugin: DanaRPlugin, private val danaRKoreanPlugin: DanaRKoreanPlugin, private val configBuilderPlugin: ConfigBuilderPlugin, - private val commandQueue: CommandQueueProvider + private val commandQueue: CommandQueueProvider, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -54,7 +55,7 @@ class MsgInitConnStatusTime( } val time = dateTimeSecFromBuff(bytes, 0) val versionCode = intFromBuff(bytes, 6, 1) - aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + DateUtil.dateAndTimeString(time)) + aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time)) aapsLogger.debug(LTag.PUMPCOMM, "Version code: $versionCode") } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTempBasalStop.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTempBasalStop.kt index b728b9e2ee..cc1308b5e3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTempBasalStop.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTempBasalStop.kt @@ -1,11 +1,7 @@ package info.nightscout.androidaps.plugins.pump.danaR.comm import info.nightscout.androidaps.logging.AAPSLogger -import info.nightscout.androidaps.logging.L -import info.nightscout.androidaps.logging.L.isEnabled import info.nightscout.androidaps.logging.LTag -import info.nightscout.androidaps.logging.StacktraceLoggerWrapper.Companion.getLogger -import org.slf4j.Logger class MsgSetTempBasalStop( private val aapsLogger: AAPSLogger diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTime.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTime.kt index 70971c431e..0fcdcd5589 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTime.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgSetTime.kt @@ -7,13 +7,14 @@ import java.util.* class MsgSetTime( private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, time: Date ) : MessageBase() { init { SetCommand(0x330a) AddParamDateTime(time) - aapsLogger.debug(LTag.PUMPCOMM, "New message: time:" + DateUtil.dateAndTimeString(time)) + aapsLogger.debug(LTag.PUMPCOMM, "New message: time:" + dateUtil.dateAndTimeString(time)) } override fun handleMessage(bytes: ByteArray) { 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 index df356ca744..b8c9af91f4 100644 --- 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 @@ -8,7 +8,8 @@ import java.util.* class MsgSettingPumpTime( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -25,7 +26,7 @@ class MsgSettingPumpTime( intFromBuff(bytes, 1, 1), intFromBuff(bytes, 0, 1) ).time - aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + DateUtil.dateAndTimeString(time) + " Phone time: " + Date()) + aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time) + " Phone time: " + Date()) danaRPump.pumpTime = time } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt index 448b45346a..b7151d8add 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/comm/MsgStatusBolusExtended.kt @@ -14,7 +14,8 @@ class MsgStatusBolusExtended( private val injector: HasAndroidInjector, private val aapsLogger: AAPSLogger, private val danaRPump: DanaRPump, - private val activePlugin: ActivePluginProvider + private val activePlugin: ActivePluginProvider, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -48,7 +49,7 @@ class MsgStatusBolusExtended( aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus amount: $extendedBolusAmount") aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus so far in minutes: $extendedBolusSoFarInMinutes") aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus absolute rate: $extendedBolusAbsoluteRate") - aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start: " + DateUtil.dateAndTimeString(extendedBolusStart)) + aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start: " + dateUtil.dateAndTimeString(extendedBolusStart)) aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus remaining minutes: $extendedBolusRemainingMinutes") } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java index f93ce4a780..b6b707381f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/AbstractDanaRExecutionService.java @@ -21,7 +21,6 @@ import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventBTChange; -import info.nightscout.androidaps.events.EventPreferenceChange; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; @@ -41,7 +40,7 @@ import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgHistorySuspend; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgPCCommStart; import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgPCCommStop; import info.nightscout.androidaps.plugins.pump.danaR.comm.RecordTypes; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.ToastUtils; @@ -63,6 +62,7 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { @Inject ResourceHelper resourceHelper; @Inject DanaRPump danaRPump; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -229,31 +229,31 @@ public abstract class AbstractDanaRExecutionService extends DaggerService { MessageBase msg = null; switch (type) { case RecordTypes.RECORD_TYPE_ALARM: - msg = new MsgHistoryAlarm(aapsLogger, rxBus); + msg = new MsgHistoryAlarm(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_BASALHOUR: - msg = new MsgHistoryBasalHour(aapsLogger, rxBus); + msg = new MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_BOLUS: - msg = new MsgHistoryBolus(aapsLogger, rxBus); + msg = new MsgHistoryBolus(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_CARBO: - msg = new MsgHistoryCarbo(aapsLogger, rxBus); + msg = new MsgHistoryCarbo(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_DAILY: - msg = new MsgHistoryDailyInsulin(aapsLogger, rxBus); + msg = new MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_ERROR: - msg = new MsgHistoryError(aapsLogger, rxBus); + msg = new MsgHistoryError(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_GLUCOSE: - msg = new MsgHistoryGlucose(aapsLogger, rxBus); + msg = new MsgHistoryGlucose(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_REFILL: - msg = new MsgHistoryRefill(aapsLogger, rxBus); + msg = new MsgHistoryRefill(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_SUSPEND: - msg = new MsgHistorySuspend(aapsLogger, rxBus); + msg = new MsgHistorySuspend(aapsLogger, rxBus, dateUtil); break; } danaRPump.setHistoryDoneReceived(false); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java index 832826cf52..f027216839 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaR/services/DanaRExecutionService.java @@ -1,8 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaR.services; -import android.bluetooth.BluetoothDevice; import android.content.Context; -import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; @@ -16,20 +14,19 @@ import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Profile; import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventPreferenceChange; 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.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.ConfigBuilderPlugin; 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; @@ -67,15 +64,10 @@ import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgStatusBolusExtended import info.nightscout.androidaps.plugins.pump.danaR.comm.MsgStatusTempBasal; import info.nightscout.androidaps.plugins.pump.danaR.events.EventDanaRNewStatus; import info.nightscout.androidaps.plugins.pump.danaRKorean.DanaRKoreanPlugin; -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.resources.ResourceHelper; import info.nightscout.androidaps.utils.sharedPreferences.SP; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; public class DanaRExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @@ -150,7 +142,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { MsgStatus statusMsg = new MsgStatus(aapsLogger, danaRPump); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(aapsLogger, danaRPump); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector); - MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin); + MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil); MsgCheckValue checkValue = new MsgCheckValue(aapsLogger, danaRPump, danaRPlugin); if (danaRPump.isNewPump()) { @@ -194,7 +186,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingProfileRatiosAll(aapsLogger, danaRPump)); mSerialIOThread.sendMessage(new MsgSettingUserOptions(aapsLogger, danaRPump)); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); if (danaRPump.getPumpTime() == 0) { // initial handshake was not successfull // deinitialize pump @@ -207,8 +199,8 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); if (Math.abs(timeDiff) > 10) { - mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, new Date())); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, dateUtil, new Date())); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } @@ -259,7 +251,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -268,7 +260,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(aapsLogger)); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -357,7 +349,7 @@ public class DanaRExecutionService extends AbstractDanaRExecutionService { t.insulin = danaRPump.getLastBolusAmount(); aapsLogger.debug(LTag.PUMP, "Used bolus amount from history: " + danaRPump.getLastBolusAmount()); } else { - aapsLogger.debug(LTag.PUMP, "Bolus amount in history too old: " + DateUtil.dateAndTimeString(danaRPump.getLastBolusTime())); + aapsLogger.debug(LTag.PUMP, "Bolus amount in history too old: " + dateUtil.dateAndTimeString(danaRPump.getLastBolusTime())); } synchronized (o) { o.notify(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java index 809cf77e6f..580e7c4ad3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/DanaRKoreanPlugin.java @@ -31,8 +31,9 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.pump.danaRKorean.services.DanaRKoreanExecutionService; -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.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.resources.ResourceHelper; @@ -60,10 +61,10 @@ public class DanaRKoreanPlugin extends AbstractDanaRPlugin { ConstraintChecker constraintChecker, TreatmentsPlugin treatmentsPlugin, SP sp, - CommandQueueProvider commandQueue - + CommandQueueProvider commandQueue, + DateUtil dateUtil ) { - super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; 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 index 7c8f5ca33b..882ab11739 100644 --- 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 @@ -11,6 +11,7 @@ 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.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -28,6 +29,7 @@ class MessageHashTableRKorean @Inject constructor( configBuilderPlugin: ConfigBuilderPlugin, commandQueue: CommandQueueProvider, activePlugin: ActivePluginProvider, + dateUtil: DateUtil, injector: HasAndroidInjector ) : MessageHashTableBase { @@ -39,10 +41,10 @@ class MessageHashTableRKorean @Inject constructor( 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(MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)) // 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(MsgInitConnStatusTime_k(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 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 @@ -53,11 +55,11 @@ class MessageHashTableRKorean @Inject constructor( 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(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS + put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS + put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE + put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM + put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 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 @@ -65,11 +67,11 @@ class MessageHashTableRKorean @Inject constructor( 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(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 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(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW + put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 0x42F2 CMD_HISTORY_NEW put(MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin)) // 0xF0F1 CMD_PUMP_CHECK_VALUE } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.kt index 77402e0389..78575809a3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/comm/MsgInitConnStatusTime_k.kt @@ -25,7 +25,8 @@ class MsgInitConnStatusTime_k( private val danaRPlugin: DanaRPlugin, private val danaRKoreanPlugin: DanaRKoreanPlugin, private val configBuilderPlugin: ConfigBuilderPlugin, - private val commandQueue: CommandQueueProvider + private val commandQueue: CommandQueueProvider, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -55,7 +56,7 @@ class MsgInitConnStatusTime_k( val versionCode2 = intFromBuff(bytes, 7, 1) val versionCode3 = intFromBuff(bytes, 8, 1) val versionCode4 = intFromBuff(bytes, 9, 1) - aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + DateUtil.dateAndTimeString(time)) + aapsLogger.debug(LTag.PUMPCOMM, "Pump time: " + dateUtil.dateAndTimeString(time)) aapsLogger.debug(LTag.PUMPCOMM, "Version code1: $versionCode1") aapsLogger.debug(LTag.PUMPCOMM, "Version code2: $versionCode2") aapsLogger.debug(LTag.PUMPCOMM, "Version code3: $versionCode3") diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java index 0d18b1ecef..0a0b0ce4c7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRKorean/services/DanaRKoreanExecutionService.java @@ -1,8 +1,6 @@ package info.nightscout.androidaps.plugins.pump.danaRKorean.services; -import android.bluetooth.BluetoothDevice; import android.content.Context; -import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; @@ -16,9 +14,7 @@ import info.nightscout.androidaps.R; 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.EventPreferenceChange; import info.nightscout.androidaps.events.EventProfileNeedsUpdate; import info.nightscout.androidaps.events.EventPumpStatusChanged; import info.nightscout.androidaps.interfaces.ActivePluginProvider; @@ -28,7 +24,7 @@ import info.nightscout.androidaps.logging.LTag; 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.interfaces.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.notifications.Notification; @@ -59,14 +55,11 @@ import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MessageHashTable import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MsgCheckValue_k; import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MsgSettingBasal_k; import info.nightscout.androidaps.plugins.pump.danaRKorean.comm.MsgStatusBasic_k; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; 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 io.reactivex.disposables.CompositeDisposable; -import io.reactivex.schedulers.Schedulers; public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; @@ -82,6 +75,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject MessageHashTableRKorean messageHashTableRKorean; @Inject ActivePluginProvider activePlugin; @Inject ProfileFunction profileFunction; + @Inject DateUtil dateUtil; public DanaRKoreanExecutionService() { } @@ -139,7 +133,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { //MsgStatus_k statusMsg = new MsgStatus_k(); MsgStatusBasic_k statusBasicMsg = new MsgStatusBasic_k(aapsLogger, danaRPump); MsgStatusTempBasal tempStatusMsg = new MsgStatusTempBasal(aapsLogger, danaRPump, activePlugin, injector); - MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin); + MsgStatusBolusExtended exStatusMsg = new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil); MsgCheckValue_k checkValue = new MsgCheckValue_k(aapsLogger, danaRPump, danaRKoreanPlugin); if (danaRPump.isNewPump()) { @@ -179,7 +173,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { mSerialIOThread.sendMessage(new MsgSettingGlucose(aapsLogger, danaRPump)); mSerialIOThread.sendMessage(new MsgSettingProfileRatios(aapsLogger, danaRPump)); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); if (danaRPump.getPumpTime() == 0) { // initial handshake was not successfull // deinitialize pump @@ -194,8 +188,8 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (Math.abs(timeDiff) > 10) { waitForWholeMinute(); // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cutted off anyway) - mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, new Date(DateUtil.now() + T.secs(10).msecs()))); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, dateUtil, new Date(DateUtil.now() + T.secs(10).msecs()))); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } @@ -246,7 +240,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStart(aapsLogger, constraintChecker, insulin, (byte) (durationInHalfHours & 0xFF))); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } @@ -255,7 +249,7 @@ public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))); mSerialIOThread.sendMessage(new MsgSetExtendedBolusStop(aapsLogger)); - mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin)); + mSerialIOThread.sendMessage(new MsgStatusBolusExtended(injector, aapsLogger, danaRPump, activePlugin, dateUtil)); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; } 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 index 2227c905a9..293faf8621 100644 --- 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 @@ -41,7 +41,7 @@ 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.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; @@ -54,7 +54,7 @@ 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.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; @@ -81,6 +81,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR private final CommandQueueProvider commandQueue; private final DanaRPump danaRPump; private final DetailedBolusInfoStorage detailedBolusInfoStorage; + private final DateUtil dateUtil; private static DanaRSService danaRSService; @@ -113,7 +114,8 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR SP sp, CommandQueueProvider commandQueue, DanaRPump danaRPump, - DetailedBolusInfoStorage detailedBolusInfoStorage + DetailedBolusInfoStorage detailedBolusInfoStorage, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.PUMP) @@ -134,6 +136,7 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR this.commandQueue = commandQueue; this.danaRPump = danaRPump; this.detailedBolusInfoStorage = detailedBolusInfoStorage; + this.dateUtil = dateUtil; pumpDescription.setPumpDescription(PumpType.DanaRS); } @@ -720,19 +723,19 @@ public class DanaRSPlugin extends PumpPluginBase implements PumpInterface, DanaR 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("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("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()); 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 index 2edf5254b3..0a4c81314d 100644 --- 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 @@ -8,6 +8,7 @@ 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.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -23,7 +24,8 @@ class DanaRSMessageHashTable @Inject constructor( activePlugin: ActivePluginProvider, constraintChecker: ConstraintChecker, detailedBolusInfoStorage: DetailedBolusInfoStorage, - injector: HasAndroidInjector + injector: HasAndroidInjector, + dateUtil: DateUtil ) { var messages: HashMap = HashMap() @@ -47,7 +49,7 @@ class DanaRSMessageHashTable @Inject constructor( 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_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)) 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)) @@ -57,7 +59,7 @@ class DanaRSMessageHashTable @Inject constructor( 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_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)) 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)) @@ -75,33 +77,33 @@ class DanaRSMessageHashTable @Inject constructor( 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_Pump_Time(aapsLogger, danaRPump, dateUtil)) put(DanaRS_Packet_Option_Get_User_Option(aapsLogger, danaRPump)) - put(DanaRS_Packet_Option_Set_Pump_Time(aapsLogger)) + put(DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil)) 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_History_Alarm(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_All_History(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil)) 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_History_Carbohydrate(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_General_Get_More_Information(aapsLogger, danaRPump, dateUtil)) 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_Shipping_Information(aapsLogger, danaRPump, dateUtil)) 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_History_Prime(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil)) 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)) + put(DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil)) + put(DanaRS_Packet_History_Temporary(aapsLogger, rxBus, dateUtil)) // 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)) + put(DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 0)) + put(DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, 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 index 4681e68e92..cb26675222 100644 --- 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 @@ -27,6 +27,7 @@ open class DanaRS_Packet_APS_History_Events( private val danaRSPlugin: DanaRSPlugin, private val detailedBolusInfoStorage: DetailedBolusInfoStorage, private val injector: HasAndroidInjector, + private val dateUtil: DateUtil, private var from: Long ) : DanaRS_Packet() { @@ -51,7 +52,7 @@ open class DanaRS_Packet_APS_History_Events( 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)) + aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(cal.timeInMillis)) danaRSPlugin.apsHistoryDone = false } @@ -82,31 +83,31 @@ open class DanaRS_Packet_APS_History_Events( val status: String when (recordCode.toInt()) { DanaRPump.TEMPSTART -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT TEMPSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") + 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) + status = "TEMPSTART " + dateUtil.timeString(datetime) } DanaRPump.TEMPSTOP -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime)) + aapsLogger.debug(LTag.PUMPCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime)) activePlugin.activeTreatments.addToHistoryTempBasal(temporaryBasal) - status = "TEMPSTOP " + DateUtil.timeString(datetime) + 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") + 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) + 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") + 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) + status = "EXTENDEDSTOP " + dateUtil.timeString(datetime) } DanaRPump.BOLUS -> { @@ -117,8 +118,8 @@ open class DanaRS_Packet_APS_History_Events( 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) + 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 -> { @@ -129,47 +130,47 @@ open class DanaRS_Packet_APS_History_Events( 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) + 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") + 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) + 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") + 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) + status = "DUALEXTENDEDSTOP " + dateUtil.timeString(datetime) } DanaRPump.SUSPENDON -> { - aapsLogger.debug(LTag.PUMPCOMM, "EVENT SUSPENDON (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") - status = "SUSPENDON " + DateUtil.timeString(datetime) + 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) + 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) + 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) + 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) + 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 -> { @@ -179,18 +180,18 @@ open class DanaRS_Packet_APS_History_Events( 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) + 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) + 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) + 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 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 index 266554d3be..f513e6c7ee 100644 --- 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 @@ -9,6 +9,7 @@ import java.util.* class DanaRS_Packet_APS_Set_Event_History( private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, private var packetType: Int, private var time: Long, private var param1: Int, @@ -18,7 +19,7 @@ class DanaRS_Packet_APS_Set_Event_History( 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) + aapsLogger.debug(LTag.PUMPCOMM, "Set history entry: " + dateUtil.dateAndTimeString(time) + " type: " + packetType + " param1: " + param1 + " param2: " + param2) } override fun getRequestParams(): ByteArray { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt index fdc5c16480..7a2f523da8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_Basal_Get_Temporary_Basal_State.kt @@ -9,7 +9,8 @@ import kotlin.math.ceil class DanaRS_Packet_Basal_Get_Temporary_Basal_State( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : DanaRS_Packet() { init { @@ -35,7 +36,7 @@ class DanaRS_Packet_Basal_Get_Temporary_Basal_State( aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal percent: " + danaRPump.tempBasalPercent) aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal remaining min: $tempBasalRemainingMin") aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal total sec: " + danaRPump.tempBasalTotalSec) - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + DateUtil.dateAndTimeString(tempBasalStart)) + aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + dateUtil.dateAndTimeString(tempBasalStart)) } override fun getFriendlyName(): String { 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 index e6c8121506..a78bf0c525 100644 --- 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 @@ -9,7 +9,8 @@ import java.util.* class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : DanaRS_Packet() { init { @@ -48,7 +49,7 @@ class DanaRS_Packet_Bolus_Get_Step_Bolus_Information( 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 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") 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 index b8e7e6bb53..a9b1b2df62 100644 --- 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 @@ -9,7 +9,8 @@ import java.util.* class DanaRS_Packet_General_Get_More_Information( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : DanaRS_Packet() { init { @@ -52,7 +53,7 @@ class DanaRS_Packet_General_Get_More_Information( 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 time: " + dateUtil.dateAndTimeAndSecondsString(lastBolusTime.time)) aapsLogger.debug(LTag.PUMPCOMM, "Last bolus amount: " + danaRPump.lastBolusAmount) } 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 index 00ebd4118a..6a60ea523a 100644 --- 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 @@ -8,7 +8,8 @@ import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_General_Get_Shipping_Information( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : DanaRS_Packet() { init { @@ -31,7 +32,7 @@ class DanaRS_Packet_General_Get_Shipping_Information( 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 date: " + dateUtil.dateAndTimeString(danaRPump.shippingDate)) aapsLogger.debug(LTag.PUMPCOMM, "Shipping country: " + danaRPump.shippingCountry) } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt index 132141b808..f5be92ecd2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear.kt @@ -2,10 +2,7 @@ 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.L -import info.nightscout.androidaps.logging.L.isEnabled import info.nightscout.androidaps.logging.LTag -import org.slf4j.LoggerFactory class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear( private val aapsLogger: AAPSLogger @@ -15,6 +12,7 @@ class DanaRS_Packet_General_Set_User_Time_Change_Flag_Clear( opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SET_USER_TIME_CHANGE_FLAG_CLEAR aapsLogger.debug(LTag.PUMPCOMM, "New message") } + override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) if (result == 0) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.kt index e8da961028..dd62bc2136 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/comm/DanaRS_Packet_History_.kt @@ -13,6 +13,7 @@ import java.util.* abstract class DanaRS_Packet_History_( protected val aapsLogger: AAPSLogger, protected val rxBus: RxBusWrapper, + protected val dateUtil: DateUtil, protected val from: Long ) : DanaRS_Packet() { @@ -36,7 +37,7 @@ abstract class DanaRS_Packet_History_( 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)) + aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(cal.timeInMillis)) } override fun getRequestParams(): ByteArray { @@ -85,7 +86,7 @@ abstract class DanaRS_Packet_History_( val historyCode = byteArrayToInt(getBytes(data, DATA_START + 7, 1)) val paramByte8 = historyCode.toByte() val value: Int = (data[DATA_START + 8].toInt() and 0xFF shl 8) + (data[DATA_START + 9].toInt() and 0xFF) - aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + DateUtil.dateAndTimeString(datetimewihtsec) + " Code: " + historyCode + " Value: " + value) + aapsLogger.debug(LTag.PUMPCOMM, "History packet: " + recordCode + " Date: " + dateUtil.dateAndTimeString(datetimewihtsec) + " Code: " + historyCode + " Value: " + value) val danaRHistoryRecord = DanaRHistoryRecord() danaRHistoryRecord.setBytes(data) // danaRHistoryRecord.recordCode is different from DanaR codes @@ -197,7 +198,7 @@ abstract class DanaRS_Packet_History_( } } MainApp.getDbHelper().createOrUpdate(danaRHistoryRecord) - rxBus.send(EventDanaRSyncStatus(DateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)) + rxBus.send(EventDanaRSyncStatus(dateUtil.dateAndTimeString(danaRHistoryRecord.recordDate) + " " + messageType)) } } 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 index 9b0c7ef4c6..360499cc21 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Alarm @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALARM 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 index a8010b2127..8f6343604b 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_All_History( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__ALL_HISTORY 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 index 0ac22574d5..e3268bcf1d 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Basal @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BASAL 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 index 6ebbeaed53..7235137871 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Blood_Glucose @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BLOOD_GLUCOSE 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 index 47996fc8c6..1d7950e8b3 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Bolus @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__BOLUS 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 index 1084434962..03b84489cb 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Carbohydrate @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__CARBOHYDRATE 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 index 93e974728d..74f3894e79 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Daily @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__DAILY 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 index 0306e6f129..9d283e905c 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Prime @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__PRIME 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 index 672c5e2cc4..637fb1be0d 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Refill @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__REFILL 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 index 9868cd10a4..3d35ec35dc 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Suspend @JvmOverloads constructor( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__SUSPEND 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 index b185748495..31258ea1b0 100644 --- 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 @@ -4,12 +4,14 @@ 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 +import info.nightscout.androidaps.utils.DateUtil class DanaRS_Packet_History_Temporary( aapsLogger: AAPSLogger, rxBus: RxBusWrapper, + dateUtil: DateUtil, from: Long = 0 -) : DanaRS_Packet_History_(aapsLogger, rxBus, from) { +) : DanaRS_Packet_History_(aapsLogger, rxBus, dateUtil, from) { init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_REVIEW__TEMPORARY 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 index 2b18603d11..297804469c 100644 --- 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 @@ -9,7 +9,8 @@ import java.util.* class DanaRS_Packet_Option_Get_Pump_Time( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : DanaRS_Packet() { init { @@ -39,7 +40,7 @@ class DanaRS_Packet_Option_Get_Pump_Time( 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)) + aapsLogger.debug(LTag.PUMPCOMM, "Pump time " + dateUtil.dateAndTimeString(time)) } override fun handleMessageNotReceived() { 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 index ec1a44c789..6739c50f57 100644 --- 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 @@ -8,6 +8,7 @@ import java.util.* class DanaRS_Packet_Option_Set_Pump_Time( private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, private var time: Long = 0 ) : DanaRS_Packet() { @@ -15,7 +16,7 @@ class DanaRS_Packet_Option_Set_Pump_Time( init { opCode = BleCommandUtil.DANAR_PACKET__OPCODE_OPTION__SET_PUMP_TIME - aapsLogger.debug(LTag.PUMPCOMM, "Setting pump time " + DateUtil.dateAndTimeString(time)) + aapsLogger.debug(LTag.PUMPCOMM, "Setting pump time " + dateUtil.dateAndTimeString(time)) } override fun getRequestParams(): ByteArray { 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 index 75ceba52ee..35097dcef5 100644 --- 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 @@ -26,6 +26,7 @@ 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; @@ -44,7 +45,7 @@ import info.nightscout.androidaps.utils.SP; */ public class BLEComm { - private Logger log = StacktraceLoggerWrapper.getLogger(L.PUMPBTCOMM); + private Logger log = StacktraceLoggerWrapper.getLogger(LTag.PUMPBTCOMM); private final long WRITE_DELAY_MILLIS = 50; @@ -81,7 +82,7 @@ public class BLEComm { private BluetoothGattCharacteristic UART_Write; private boolean initialize() { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("Initializing BLEComm."); if (mBluetoothManager == null) { @@ -139,7 +140,7 @@ public class BLEComm { return false; } - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("Trying to create a new connection from: " + from); mBluetoothDeviceName = device.getName(); mBluetoothGatt = device.connectGatt(context, false, mGattCallback); @@ -152,7 +153,7 @@ public class BLEComm { } public synchronized void disconnect(String from) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("disconnect from: " + from); // cancel previous scheduled disconnection to prevent closing upcomming connection @@ -172,7 +173,7 @@ public class BLEComm { } public synchronized void close() { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("BluetoothAdapter close"); if (mBluetoothGatt == null) { return; @@ -193,7 +194,7 @@ public class BLEComm { } public void onServicesDiscovered(BluetoothGatt gatt, int status) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("onServicesDiscovered"); if (status == BluetoothGatt.GATT_SUCCESS) { findCharacteristic(); @@ -203,21 +204,21 @@ public class BLEComm { } public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { - if (L.isEnabled(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("onCharacteristicWrite" + (characteristic != null ? ":" + DanaRS_Packet.toHexString(characteristic.getValue()) : "")); new Thread(() -> { synchronized (mSendQueue) { @@ -233,7 +234,7 @@ public class BLEComm { }; private synchronized void setCharacteristicNotification(BluetoothGattCharacteristic characteristic, boolean enabled) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("setCharacteristicNotification"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { log.error("BluetoothAdapter not initialized_ERROR"); @@ -245,7 +246,7 @@ public class BLEComm { } public synchronized void readCharacteristic(BluetoothGattCharacteristic characteristic) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("readCharacteristic"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { log.error("BluetoothAdapter not initialized_ERROR"); @@ -269,7 +270,7 @@ public class BLEComm { characteristic.setValue(data); characteristic.setWriteType(BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE); - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("writeCharacteristic:" + DanaRS_Packet.toHexString(data)); mBluetoothGatt.writeCharacteristic(characteristic); }).start(); @@ -290,7 +291,7 @@ public class BLEComm { } private List getSupportedGattServices() { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("getSupportedGattServices"); if ((mBluetoothAdapter == null) || (mBluetoothGatt == null)) { log.error("BluetoothAdapter not initialized_ERROR"); @@ -326,7 +327,7 @@ public class BLEComm { } private synchronized void onConnectionStateChangeSynchronized(BluetoothGatt gatt, int status, int newState) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("onConnectionStateChange"); if (newState == BluetoothProfile.STATE_CONNECTED) { @@ -336,7 +337,7 @@ public class BLEComm { isConnected = false; isConnecting = false; RxBus.Companion.getINSTANCE().send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTED)); - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("Device was disconnected " + gatt.getDevice().getName());//Device was disconnected } } @@ -372,7 +373,7 @@ public class BLEComm { 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(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("Shifting the input buffer by " + idxStartByte + " bytes"); System.arraycopy(readBuffer, idxStartByte, readBuffer, 0, bufferLength - idxStartByte); bufferLength -= idxStartByte; @@ -427,16 +428,16 @@ public class BLEComm { // 1st packet case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK: if (inputBuffer.length == 4 && inputBuffer[2] == 'O' && inputBuffer[3] == 'K') { - if (L.isEnabled(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(">>>>> " + "ENCRYPTION__CHECK_PASSKEY" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } else { @@ -445,7 +446,7 @@ public class BLEComm { } } else if (inputBuffer.length == 6 && inputBuffer[2] == 'P' && inputBuffer[3] == 'U' && inputBuffer[4] == 'M' && inputBuffer[5] == 'P') { - if (L.isEnabled(L.PUMPBTCOMM)) + 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))); @@ -453,13 +454,13 @@ public class BLEComm { 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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))); @@ -470,7 +471,7 @@ public class BLEComm { break; // 2nd packet, pairing key case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__CHECK_PASSKEY: - if (L.isEnabled(L.PUMPBTCOMM)) + 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 @@ -481,7 +482,7 @@ public class BLEComm { } break; case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST: - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("<<<<< " + "ENCRYPTION__PASSKEY_REQUEST " + DanaRS_Packet.toHexString(inputBuffer)); if (inputBuffer[2] != (byte) 0x00) { disconnect("passkey request failed"); @@ -489,7 +490,7 @@ public class BLEComm { break; // Paring response, OK button on pump pressed case (byte) BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_RETURN: - if (L.isEnabled(L.PUMPBTCOMM)) + 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()); @@ -497,24 +498,24 @@ public class BLEComm { 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("RS connected and status read"); break; } @@ -533,7 +534,7 @@ public class BLEComm { message = danaRSMessageHashTable.findMessage(receivedCommand); } if (message != null) { - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug("<<<<< " + message.getFriendlyName() + " " + DanaRS_Packet.toHexString(inputBuffer)); // process received data message.handleMessage(inputBuffer); @@ -570,7 +571,7 @@ public class BLEComm { byte[] command = {(byte) message.getType(), (byte) message.getOpCode()}; byte[] params = message.getRequestParams(); - if (L.isEnabled(L.PUMPBTCOMM)) + 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 @@ -652,7 +653,7 @@ public class BLEComm { MainApp.instance().startActivity(i); byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PASSKEY_REQUEST, null, null); - if (L.isEnabled(L.PUMPBTCOMM)) + if (L.isEnabled(LTag.PUMPBTCOMM)) log.debug(">>>>> " + "ENCRYPTION__PASSKEY_REQUEST" + " " + DanaRS_Packet.toHexString(bytes)); writeCharacteristic_NO_RESPONSE(getUARTWriteBTGattChar(), bytes); } @@ -666,14 +667,14 @@ public class BLEComm { return; } byte[] bytes = BleCommandUtil.getInstance().getEncryptedPacket(BleCommandUtil.DANAR_PACKET__OPCODE_ENCRYPTION__PUMP_CHECK, null, devicename); - if (L.isEnabled(L.PUMPBTCOMM)) + 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(L.PUMPBTCOMM)) + 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 index 3d7eb03e0a..359294ca00 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRS/services/DanaRSService.java @@ -27,7 +27,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.general.nsclient.NSUpload; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; @@ -75,7 +75,7 @@ import info.nightscout.androidaps.plugins.pump.danaRS.comm.DanaRS_Packet_History 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.db.Treatment; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; @@ -101,6 +101,7 @@ public class DanaRSService extends DaggerService { @Inject ActivePluginProvider activePlugin; @Inject ConstraintChecker constraintChecker; @Inject DetailedBolusInfoStorage detailedBolusInfoStorage; + @Inject DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -166,9 +167,9 @@ public class DanaRSService extends DaggerService { 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 + bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // 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)); + bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); danaRPump.setLastConnection(System.currentTimeMillis()); @@ -183,7 +184,7 @@ public class DanaRSService extends DaggerService { } rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump)); + bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil)); long timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; if (danaRPump.getPumpTime() == 0) { @@ -197,7 +198,7 @@ public class DanaRSService extends DaggerService { 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_Shipping_Information(aapsLogger, danaRPump, dateUtil)); // 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 @@ -227,13 +228,13 @@ public class DanaRSService extends DaggerService { return; } else { if (danaRPump.getProtocol() >= 6) { - bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, DateUtil.now())); + bleComm.sendMessage(new DanaRS_Packet_Option_Set_Pump_Time(aapsLogger, dateUtil, 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_Set_Pump_Time(aapsLogger, dateUtil, DateUtil.now() + T.secs(10).msecs())); } - bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump)); + bleComm.sendMessage(new DanaRS_Packet_Option_Get_Pump_Time(aapsLogger, danaRPump, dateUtil)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: " + timeDiff + " seconds"); } @@ -271,11 +272,11 @@ public class DanaRSService extends DaggerService { DanaRS_Packet_APS_History_Events msg; if (lastHistoryFetched == 0) { - msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, 0); + msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, 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)); + msg = new DanaRS_Packet_APS_History_Events(aapsLogger, rxBus, resourceHelper, activePlugin, danaRSPlugin, detailedBolusInfoStorage, injector, dateUtil, lastHistoryFetched); + aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched)); } bleComm.sendMessage(msg); while (!danaRSPlugin.apsHistoryDone && bleComm.isConnected()) { @@ -314,7 +315,7 @@ public class DanaRSService extends DaggerService { 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); + DanaRS_Packet_APS_Set_Event_History msgSetHistoryEntry_v2 = new DanaRS_Packet_APS_Set_Event_History(aapsLogger, dateUtil, DanaRPump.CARBS, carbtime, carbs, 0); bleComm.sendMessage(msgSetHistoryEntry_v2); lastHistoryFetched = Math.min(lastHistoryFetched, carbtime - T.mins(1).msecs()); } @@ -369,7 +370,7 @@ public class DanaRSService extends DaggerService { 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 + bleComm.sendMessage(new DanaRS_Packet_Bolus_Get_Step_Bolus_Information(aapsLogger, danaRPump, dateUtil)); // last bolus bolusingEvent.setPercent(100); rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))); } @@ -402,7 +403,7 @@ public class DanaRSService extends DaggerService { 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)); + bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -416,7 +417,7 @@ public class DanaRSService extends DaggerService { } 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)); + bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -435,7 +436,7 @@ public class DanaRSService extends DaggerService { } 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)); + bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -445,7 +446,7 @@ public class DanaRSService extends DaggerService { 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)); + bleComm.sendMessage(new DanaRS_Packet_Basal_Get_Temporary_Basal_State(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -492,31 +493,31 @@ public class DanaRSService extends DaggerService { DanaRS_Packet_History_ msg = null; switch (type) { case RecordTypes.RECORD_TYPE_ALARM: - msg = new DanaRS_Packet_History_Alarm(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Alarm(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_PRIME: - msg = new DanaRS_Packet_History_Prime(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Prime(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_BASALHOUR: - msg = new DanaRS_Packet_History_Basal(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Basal(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_BOLUS: - msg = new DanaRS_Packet_History_Bolus(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Bolus(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_CARBO: - msg = new DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Carbohydrate(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_DAILY: - msg = new DanaRS_Packet_History_Daily(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Daily(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_GLUCOSE: - msg = new DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Blood_Glucose(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_REFILL: - msg = new DanaRS_Packet_History_Refill(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Refill(aapsLogger, rxBus, dateUtil); break; case RecordTypes.RECORD_TYPE_SUSPEND: - msg = new DanaRS_Packet_History_Suspend(aapsLogger, rxBus); + msg = new DanaRS_Packet_History_Suspend(aapsLogger, rxBus, dateUtil); break; } if (msg != null) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java index e783d13d78..72df8b9e68 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/DanaRv2Plugin.java @@ -29,7 +29,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.plugins.pump.danaR.AbstractDanaRPlugin; import info.nightscout.androidaps.plugins.pump.danaR.DanaRPump; import info.nightscout.androidaps.plugins.pump.danaRv2.services.DanaRv2ExecutionService; -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.FabricPrivacy; @@ -66,9 +66,10 @@ public class DanaRv2Plugin extends AbstractDanaRPlugin { TreatmentsPlugin treatmentsPlugin, SP sp, CommandQueueProvider commandQueue, - DetailedBolusInfoStorage detailedBolusInfoStorage + DetailedBolusInfoStorage detailedBolusInfoStorage, + DateUtil dateUtil ) { - super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp); + super(injector, danaRPump, resourceHelper, constraintChecker, aapsLogger, commandQueue, rxBus, treatmentsPlugin, sp, dateUtil); this.aapsLogger = aapsLogger; this.context = context; this.resourceHelper = resourceHelper; 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 index 7fbb2f3258..8833ea6b3f 100644 --- 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 @@ -14,6 +14,7 @@ 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.DateUtil import info.nightscout.androidaps.utils.resources.ResourceHelper import java.util.* import javax.inject.Inject @@ -34,7 +35,8 @@ class MessageHashTableRv2 @Inject constructor( activePlugin: ActivePluginProvider, detailedBolusInfoStorage: DetailedBolusInfoStorage, treatmentsPlugin: TreatmentsPlugin, - injector: HasAndroidInjector + injector: HasAndroidInjector, + dateUtil: DateUtil ) : MessageHashTableBase { var messages: HashMap = HashMap() @@ -45,11 +47,11 @@ class MessageHashTableRv2 @Inject constructor( 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(MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)) // 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(MsgInitConnStatusTime(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, configBuilderPlugin, commandQueue, dateUtil)) // 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 @@ -61,15 +63,15 @@ class MessageHashTableRv2 @Inject constructor( 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(MsgHistoryBolus(aapsLogger, rxBus, dateUtil)) // 0x3101 CMD_HISTORY_MEAL_INS + put(MsgHistoryDailyInsulin(aapsLogger, rxBus, dateUtil)) // 0x3102 CMD_HISTORY_DAY_INS + put(MsgHistoryGlucose(aapsLogger, rxBus, dateUtil)) // 0x3104 CMD_HISTORY_GLUCOSE + put(MsgHistoryAlarm(aapsLogger, rxBus, dateUtil)) // 0x3105 CMD_HISTORY_ALARM + put(MsgHistoryError(aapsLogger, rxBus, dateUtil)) // 0x3106 CMD_HISTORY_ERROR + put(MsgHistoryCarbo(aapsLogger, rxBus, dateUtil)) // 0x3107 CMD_HISTORY_CARBOHY + put(MsgHistoryRefill(aapsLogger, rxBus, dateUtil)) // 0x3108 CMD_HISTORY_REFILL + put(MsgHistorySuspend(aapsLogger, rxBus, dateUtil)) // 0x3109 CMD_HISTORY_SUSPEND + put(MsgHistoryBasalHour(aapsLogger, rxBus, dateUtil)) // 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 @@ -78,7 +80,7 @@ class MessageHashTableRv2 @Inject constructor( 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(MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)) // 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 @@ -87,13 +89,13 @@ class MessageHashTableRv2 @Inject constructor( 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(MsgHistoryAll(aapsLogger, rxBus, dateUtil)) // 0x41F2 CMD_HISTORY_ALL put(MsgHistoryNewDone(aapsLogger, danaRPump)) // 0x42F1 CMD_HISTORY_NEW_DONE - put(MsgHistoryNew(aapsLogger, rxBus)) // 0x42F2 CMD_HISTORY_NEW + put(MsgHistoryNew(aapsLogger, rxBus, dateUtil)) // 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(MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, dateUtil)) // 0xE003 CMD_GET_HISTORY put(MsgSetHistoryEntry_v2(aapsLogger, 0, 0, 0, 0)) // 0xE004 CMD_SET_HISTORY_ENTRY } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt index 0280b0a3e6..7b11695910 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgHistoryEvents_v2.kt @@ -27,6 +27,7 @@ class MsgHistoryEvents_v2 constructor( val rxBus: RxBusWrapper, val treatmentsPlugin: TreatmentsPlugin, private val injector: HasAndroidInjector, + private val dateUtil: DateUtil, var from: Long = 0 ) : MessageBase() { @@ -74,31 +75,31 @@ class MsgHistoryEvents_v2 constructor( val status: String when (recordCode.toInt()) { DanaRPump.TEMPSTART -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Ratio: " + param1 + "% Duration: " + param2 + "min") temporaryBasal.percentRate = param1 temporaryBasal.durationInMinutes = param2 treatmentsPlugin.addToHistoryTempBasal(temporaryBasal) - status = "TEMPSTART " + DateUtil.timeString(datetime) + status = "TEMPSTART " + dateUtil.timeString(datetime) } DanaRPump.TEMPSTOP -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime)) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT TEMPSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime)) treatmentsPlugin.addToHistoryTempBasal(temporaryBasal) - status = "TEMPSTOP " + DateUtil.timeString(datetime) + status = "TEMPSTOP " + dateUtil.timeString(datetime) } DanaRPump.EXTENDEDSTART -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") extendedBolus.insulin = param1 / 100.0 extendedBolus.durationInMinutes = param2 treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) - status = "EXTENDEDSTART " + DateUtil.timeString(datetime) + status = "EXTENDEDSTART " + dateUtil.timeString(datetime) } DanaRPump.EXTENDEDSTOP -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT EXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) - status = "EXTENDEDSTOP " + DateUtil.timeString(datetime) + status = "EXTENDEDSTOP " + dateUtil.timeString(datetime) } DanaRPump.BOLUS -> { @@ -109,8 +110,8 @@ class MsgHistoryEvents_v2 constructor( detailedBolusInfo.pumpId = datetime detailedBolusInfo.insulin = param1 / 100.0 val newRecord = treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) - aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT BOLUS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") - status = "BOLUS " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, (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 -> { @@ -121,47 +122,47 @@ class MsgHistoryEvents_v2 constructor( detailedBolusInfo.pumpId = datetime detailedBolusInfo.insulin = param1 / 100.0 val newRecord = treatmentsPlugin.addToHistoryTreatment(detailedBolusInfo, false) - aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT DUALBOLUS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Bolus: " + param1 / 100.0 + "U Duration: " + param2 + "min") - status = "DUALBOLUS " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, (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.PUMPBTCOMM, "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT DUALEXTENDEDSTART (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U Duration: " + param2 + "min") extendedBolus.insulin = param1 / 100.0 extendedBolus.durationInMinutes = param2 treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) - status = "DUALEXTENDEDSTART " + DateUtil.timeString(datetime) + status = "DUALEXTENDEDSTART " + dateUtil.timeString(datetime) } DanaRPump.DUALEXTENDEDSTOP -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT DUALEXTENDEDSTOP (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Delivered: " + param1 / 100.0 + "U RealDuration: " + param2 + "min") treatmentsPlugin.addToHistoryExtendedBolus(extendedBolus) - status = "DUALEXTENDEDSTOP " + DateUtil.timeString(datetime) + status = "DUALEXTENDEDSTOP " + dateUtil.timeString(datetime) } DanaRPump.SUSPENDON -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDON (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") - status = "SUSPENDON " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDON (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") + status = "SUSPENDON " + dateUtil.timeString(datetime) } DanaRPump.SUSPENDOFF -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDOFF (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") - status = "SUSPENDOFF " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT SUSPENDOFF (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")") + status = "SUSPENDOFF " + dateUtil.timeString(datetime) } DanaRPump.REFILL -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT REFILL (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") - status = "REFILL " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT REFILL (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") + status = "REFILL " + dateUtil.timeString(datetime) } DanaRPump.PRIME -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PRIME (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") - status = "PRIME " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PRIME (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Amount: " + param1 / 100.0 + "U") + status = "PRIME " + dateUtil.timeString(datetime) } DanaRPump.PROFILECHANGE -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PROFILECHANGE (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h") - status = "PROFILECHANGE " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "EVENT PROFILECHANGE (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " No: " + param1 + " CurrentRate: " + param2 / 100.0 + "U/h") + status = "PROFILECHANGE " + dateUtil.timeString(datetime) } DanaRPump.CARBS -> { @@ -171,13 +172,13 @@ class MsgHistoryEvents_v2 constructor( emptyCarbsInfo.source = Source.PUMP emptyCarbsInfo.pumpId = datetime val newRecord = treatmentsPlugin.addToHistoryTreatment(emptyCarbsInfo, false) - aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") - status = "CARBS " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, (if (newRecord) "**NEW** " else "") + "EVENT CARBS (" + recordCode + ") " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Carbs: " + param1 + "g") + status = "CARBS " + dateUtil.timeString(datetime) } else -> { - aapsLogger.debug(LTag.PUMPBTCOMM, "Event: " + recordCode + " " + DateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2) - status = "UNKNOWN " + DateUtil.timeString(datetime) + aapsLogger.debug(LTag.PUMPBTCOMM, "Event: " + recordCode + " " + dateUtil.dateAndTimeString(datetime) + " (" + datetime + ")" + " Param1: " + param1 + " Param2: " + param2) + status = "UNKNOWN " + dateUtil.timeString(datetime) } } if (datetime > danaRv2Plugin.lastEventTimeLoaded) danaRv2Plugin.lastEventTimeLoaded = datetime diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2.kt index ac21c3f533..e4668fcd2b 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/comm/MsgStatusTempBasal_v2.kt @@ -9,8 +9,8 @@ import kotlin.math.ceil class MsgStatusTempBasal_v2( private val aapsLogger: AAPSLogger, - private val danaRPump: DanaRPump - + private val danaRPump: DanaRPump, + private val dateUtil: DateUtil ) : MessageBase() { init { @@ -37,7 +37,7 @@ class MsgStatusTempBasal_v2( aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal percent: $tempBasalPercent") aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal remaining min: $tempBasalRemainingMin") aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal total sec: $tempBasalTotalSec") - aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + DateUtil.dateAndTimeString(tempBasalStart)) + aapsLogger.debug(LTag.PUMPCOMM, "Current temp basal start: " + dateUtil.dateAndTimeString(tempBasalStart)) } private fun getDateFromTempBasalSecAgo(tempBasalAgoSecs: Int): Long { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java index 564b59e77f..1433d3727f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/danaRv2/services/DanaRv2ExecutionService.java @@ -1,9 +1,7 @@ package info.nightscout.androidaps.plugins.pump.danaRv2.services; -import android.bluetooth.BluetoothDevice; import android.content.Context; import android.content.Intent; -import android.content.IntentFilter; import android.os.Binder; import android.os.SystemClock; @@ -18,21 +16,20 @@ 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.db.Treatment; import info.nightscout.androidaps.dialogs.BolusProgressDialog; -import info.nightscout.androidaps.events.EventAppExit; import info.nightscout.androidaps.events.EventInitializationChanged; -import info.nightscout.androidaps.events.EventPreferenceChange; 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.ProfileFunction; 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.ConfigBuilderPlugin; 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; @@ -76,17 +73,13 @@ import info.nightscout.androidaps.plugins.pump.danaRv2.comm.MsgSetAPSTempBasalSt import info.nightscout.androidaps.plugins.pump.danaRv2.comm.MsgSetHistoryEntry_v2; import info.nightscout.androidaps.plugins.pump.danaRv2.comm.MsgStatusBolusExtended_v2; import info.nightscout.androidaps.plugins.pump.danaRv2.comm.MsgStatusTempBasal_v2; -import info.nightscout.androidaps.plugins.treatments.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; 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 DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Inject HasAndroidInjector injector; @@ -107,6 +100,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { @Inject TreatmentsPlugin treatmentsPlugin; @Inject ProfileFunction profileFunction; @Inject SP sp; + @Inject DateUtil dateUtil; private long lastHistoryFetched = 0; @@ -165,7 +159,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))); MsgStatus statusMsg = new MsgStatus(aapsLogger, danaRPump); MsgStatusBasic statusBasicMsg = new MsgStatusBasic(aapsLogger, danaRPump); - MsgStatusTempBasal_v2 tempStatusMsg = new MsgStatusTempBasal_v2(aapsLogger, danaRPump); + MsgStatusTempBasal_v2 tempStatusMsg = new MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil); MsgStatusBolusExtended_v2 exStatusMsg = new MsgStatusBolusExtended_v2(aapsLogger, danaRPump); MsgCheckValue_v2 checkValue = new MsgCheckValue_v2(aapsLogger, rxBus, resourceHelper, danaRPump, danaRPlugin, danaRKoreanPlugin, danaRv2Plugin, configBuilderPlugin, commandQueue); @@ -197,7 +191,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); if (danaRPump.getPumpTime() == 0) { // initial handshake was not successfull // deinitialize pump @@ -228,8 +222,8 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } else { waitForWholeMinute(); // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cutted off anyway) - mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, new Date(DateUtil.now() + T.secs(10).msecs()))); - mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgSetTime(aapsLogger, dateUtil, new Date(DateUtil.now() + T.secs(10).msecs()))); + mSerialIOThread.sendMessage(new MsgSettingPumpTime(aapsLogger, danaRPump, dateUtil)); timeDiff = (danaRPump.getPumpTime() - System.currentTimeMillis()) / 1000L; aapsLogger.debug(LTag.PUMP, "Pump time difference: " + timeDiff + " seconds"); } @@ -280,7 +274,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStart(aapsLogger, percent, durationInHours)); - mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -295,7 +289,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(aapsLogger, percent, durationInMinutes == 15, durationInMinutes == 30)); - mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -315,7 +309,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { } rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))); mSerialIOThread.sendMessage(new MsgSetAPSTempBasalStart_v2(aapsLogger, percent, durationInMinutes == 15, durationInMinutes == 30)); - mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -325,7 +319,7 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return false; rxBus.send(new EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))); mSerialIOThread.sendMessage(new MsgSetTempBasalStop(aapsLogger)); - mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump)); + mSerialIOThread.sendMessage(new MsgStatusTempBasal_v2(aapsLogger, danaRPump, dateUtil)); loadEvents(); rxBus.send(new EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)); return true; @@ -455,8 +449,8 @@ public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { if (!isConnected()) return new PumpEnactResult(injector).success(false); SystemClock.sleep(300); - MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, lastHistoryFetched); - aapsLogger.debug(LTag.PUMP, "Loading event history from: " + DateUtil.dateAndTimeString(lastHistoryFetched)); + MsgHistoryEvents_v2 msg = new MsgHistoryEvents_v2(aapsLogger, resourceHelper, detailedBolusInfoStorage, danaRv2Plugin, rxBus, treatmentsPlugin, injector, dateUtil, lastHistoryFetched); + aapsLogger.debug(LTag.PUMP, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched)); mSerialIOThread.sendMessage(msg); while (!danaRv2Plugin.eventsLoadingDone && mRfcommSocket.isConnected()) { 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..2c1c9b6e91 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))); } } 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..d44470bad1 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 @@ -53,7 +53,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.nsclient.NSUpload; @@ -132,7 +132,7 @@ 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.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.TimeChangeType; @@ -150,6 +150,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, private final CommandQueueProvider commandQueue; private final ProfileFunction profileFunction; private final Context context; + private final DateUtil dateUtil; public static final String ALERT_CHANNEL_ID = "AndroidAPS-InsightAlert"; @@ -208,7 +209,9 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, SP sp, CommandQueueProvider commandQueue, ProfileFunction profileFunction, - Context context + Context context, + Config config, + DateUtil dateUtil ) { super(new PluginDescription() .pluginName(R.string.insight_local) @@ -216,7 +219,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 ); @@ -228,6 +231,7 @@ public class LocalInsightPlugin extends PumpPluginBase implements PumpInterface, this.commandQueue = commandQueue; this.profileFunction = profileFunction; this.context = context; + this.dateUtil = dateUtil; pumpDescription = new PumpDescription(); pumpDescription.setPumpDescription(PumpType.AccuChekInsightBluetooth); @@ -995,13 +999,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()); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java index 9d4b89675e..95a3f68c12 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.java @@ -84,6 +84,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.events.EventRefreshButt import info.nightscout.androidaps.plugins.pump.medtronic.service.RileyLinkMedtronicService; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; +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; @@ -136,7 +137,8 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter MedtronicPumpStatus medtronicPumpStatus, MedtronicHistoryData medtronicHistoryData, RileyLinkServiceData rileyLinkServiceData, - ServiceTaskExecutor serviceTaskExecutor + ServiceTaskExecutor serviceTaskExecutor, + DateUtil dateUtil ) { super(new PluginDescription() // @@ -147,7 +149,7 @@ public class MedtronicPumpPlugin extends PumpPluginAbstract implements PumpInter .preferencesId(R.xml.pref_medtronic) .description(R.string.description_pump_medtronic), // PumpType.Medtronic_522_722, // we default to most basic model, correct model from config is loaded later - injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy + injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil ); this.rileyLinkUtil = rileyLinkUtil; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java index c3d39954a0..9d040fc105 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.java @@ -2,13 +2,12 @@ package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms; import org.joda.time.LocalDateTime; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryDecoder; @@ -23,7 +22,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDeco public class MedtronicCGMSHistoryDecoder extends MedtronicHistoryDecoder { - private static final Logger LOG = StacktraceLoggerWrapper.getLogger(L.PUMPCOMM); + private static final Logger LOG = StacktraceLoggerWrapper.getLogger(LTag.PUMPCOMM); // CGMSValuesWriter cgmsValuesWriter = null; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java index 496f2af06b..d8f5c47b4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.java @@ -35,7 +35,6 @@ import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.LTag; import info.nightscout.androidaps.plugins.general.nsclient.NSUpload; 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.utils.DateTimeUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder; @@ -52,7 +51,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalProce import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst; import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil; -import info.nightscout.androidaps.plugins.treatments.Treatment; +import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.plugins.treatments.TreatmentService; import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin; import info.nightscout.androidaps.utils.DateUtil; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java index 475066cb6c..61b235f1d2 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/BasalProfile.java @@ -364,7 +364,7 @@ public class BasalProfile { private boolean isLogEnabled() { - return L.isEnabled(L.PUMPCOMM); + return L.isEnabled(LTag.PUMPCOMM); } public boolean verify(PumpType pumpType) { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java index 09dd929074..caac54e122 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/TempBasalPair.java @@ -42,7 +42,7 @@ public class TempBasalPair extends info.nightscout.androidaps.plugins.pump.commo public TempBasalPair(AAPSLogger aapsLogger, byte[] response) { super(); - if (L.isEnabled(L.PUMPCOMM)) + if (L.isEnabled(LTag.PUMPCOMM)) aapsLogger.debug(LTag.PUMPBTCOMM, "Received TempBasal response: " + ByteUtil.getHex(response)); isPercent = response[0] == 1; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java index 2a7ffa2ce4..616f033799 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/RileyLinkStatusDeviceMedtronic.java @@ -18,6 +18,7 @@ import info.nightscout.androidaps.R; import info.nightscout.androidaps.plugins.pump.common.dialog.RefreshableInterface; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; +import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.resources.ResourceHelper; /** @@ -32,6 +33,7 @@ import info.nightscout.androidaps.utils.resources.ResourceHelper; public class RileyLinkStatusDeviceMedtronic extends DaggerFragment implements RefreshableInterface { @Inject ResourceHelper resourceHelper; + @Inject DateUtil dateUtil; // @BindView(R.id.rileylink_history_list) ListView listView; @@ -153,7 +155,7 @@ public class RileyLinkStatusDeviceMedtronic extends DaggerFragment implements Re } RLHistoryItem item = historyItemList.get(i); - viewHolder.itemTime.setText(StringUtil.toDateTimeString(item.getDateTime())); + viewHolder.itemTime.setText(StringUtil.toDateTimeString(dateUtil, item.getDateTime())); viewHolder.itemSource.setText("Riley Link"); // for now viewHolder.itemDescription.setText(item.getDescription(resourceHelper)); 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 fce29225d4..6dba697009 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 @@ -176,7 +176,7 @@ class OmnipodFragment : DaggerFragment() { disposable += rxBus .toObservable(EventPreferenceChange::class.java) .observeOn(Schedulers.io()) - .subscribe({ event -> + .subscribe({ setVisibilityOfPodDebugButton() }, { fabricPrivacy.logException(it) }) } 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 62adc49855..0c51b5901c 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 @@ -73,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; @@ -136,7 +137,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) // @@ -146,7 +149,7 @@ 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.rileyLinkServiceData = rileyLinkServiceData; this.serviceTaskExecutor = serviceTaskExecutor; @@ -232,8 +235,10 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump 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); + FabricPrivacy fabricPrivacy, + DateUtil dateUtil + ) { + super(pluginDescription, pumpType, injector, resourceHelper, aapsLogger, commandQueue, rxBus, activePlugin, sp, context, fabricPrivacy, dateUtil); // this.rileyLinkUtil = rileyLinkUtil; // this.medtronicUtil = medtronicUtil; @@ -514,13 +519,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); @@ -619,15 +624,7 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump if (omnipodUtil.getPodSessionState() != null) { podSessionState = omnipodUtil.getPodSessionState(); } else { - String podState = sp.getString(OmnipodConst.Prefs.PodState, null); - - aapsLogger.info(LTag.PUMP, "PodSessionState-SP: loaded from SharedPreferences: " + podState); - - if (podState != null) { - podSessionState = omnipodUtil.getGsonInstance().fromJson(podState, PodSessionState.class); - podSessionState.injectDaggerClass(injector); - omnipodUtil.setPodSessionState(podSessionState); - } + podSessionState = omnipodUtil.loadSessionState(); } @@ -1017,7 +1014,6 @@ public class OmnipodPumpPlugin extends PumpPluginAbstract implements OmnipodPump // Don't trigger an alert when we exceeded the thresholds, but the last communication was successful // This happens when we simply didn't need to send any commands to the pump - return false; } } 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 f8ff351391..e77befd258 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 @@ -23,6 +23,8 @@ 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.action.OmnipodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageSequenceNumberException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalResponseException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NonceOutOfSyncException; @@ -38,13 +40,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.Err import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.StatusResponse; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoFaultEvent; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.ErrorResponseType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodState; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; +import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; /** * Created by andy on 6/29/18. @@ -53,9 +55,9 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { @Inject public AAPSLogger aapsLogger; @Inject OmnipodPumpStatus omnipodPumpStatus; - @Inject OmnipodPumpPlugin omnipodPumpPlugin; - @Inject RileyLinkServiceData rileyLinkServiceData; - @Inject ServiceTaskExecutor serviceTaskExecutor; + //@Inject OmnipodPumpPlugin omnipodPumpPlugin; + //@Inject RileyLinkServiceData rileyLinkServiceData; + //@Inject ServiceTaskExecutor serviceTaskExecutor; public OmnipodCommunicationManager(HasAndroidInjector injector, RFSpy rfspy) { super(injector, rfspy); @@ -149,7 +151,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { } else { if (responseMessageBlock.getType() == MessageBlockType.ERROR_RESPONSE) { ErrorResponse error = (ErrorResponse) responseMessageBlock; - if (error.getErrorResponseType() == ErrorResponseType.BAD_NONCE) { + if (error.getErrorResponseCode() == ErrorResponse.ERROR_RESPONSE_CODE_BAD_NONCE) { podState.resyncNonce(error.getNonceSearchKey(), message.getSentNonce(), message.getSequenceNumber()); if (automaticallyResyncNonce) { message.resyncNonce(podState.getCurrentNonce()); @@ -157,7 +159,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { throw new NonceOutOfSyncException(); } } else { - throw new PodReturnedErrorResponseException((ErrorResponse) responseMessageBlock); + throw new PodReturnedErrorResponseException(error); } } else if (responseMessageBlock.getType() == MessageBlockType.POD_INFO_RESPONSE && ((PodInfoResponse) responseMessageBlock).getSubType() == PodInfoType.FAULT_EVENT) { PodInfoFaultEvent faultEvent = ((PodInfoResponse) responseMessageBlock).getPodInfo(); @@ -178,6 +180,8 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { packetAddress = addressOverride; } + podState.increaseMessageNumber(); + boolean firstPacket = true; byte[] encodedMessage; // this does not work well with the deactivate pod command, we somehow either @@ -230,7 +234,6 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { } if (response.getPacketType() == PacketType.ACK) { - podState.increasePacketNumber(1); throw new IllegalPacketTypeException(null, PacketType.ACK); } @@ -239,6 +242,12 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { while (receivedMessage == null) { try { receivedMessage = OmnipodMessage.decodeMessage(receivedMessageData); + if (receivedMessage.getAddress() != message.getAddress()) { + throw new IllegalMessageAddressException(message.getAddress(), receivedMessage.getAddress()); + } + if (receivedMessage.getSequenceNumber() != podState.getMessageNumber()) { + throw new IllegalMessageSequenceNumberException(podState.getMessageNumber(), receivedMessage.getSequenceNumber()); + } } catch (NotEnoughDataException ex) { // Message is (probably) not complete yet OmnipodPacket ackForCon = createAckPacket(podState, packetAddress, ackAddressOverride); @@ -258,8 +267,6 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { } } - podState.increaseMessageNumber(2); - ackUntilQuiet(podState, packetAddress, ackAddressOverride); List messageBlocks = receivedMessage.getMessageBlocks(); @@ -271,19 +278,23 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { aapsLogger.error(LTag.PUMPBTCOMM, "Received more than one message block: {}", messageBlocks.toString()); } - return messageBlocks.get(0); + MessageBlock messageBlock = messageBlocks.get(0); + + if (messageBlock.getType() != MessageBlockType.ERROR_RESPONSE) { + podState.increaseMessageNumber(); + } + + return messageBlock; } private OmnipodPacket createAckPacket(PodState podState, Integer packetAddress, Integer messageAddress) { - int pktAddress = podState.getAddress(); - int msgAddress = podState.getAddress(); - if (packetAddress != null) { - pktAddress = packetAddress; + if (packetAddress == null) { + packetAddress = podState.getAddress(); } - if (messageAddress != null) { - msgAddress = messageAddress; + if (messageAddress == null) { + messageAddress = podState.getAddress(); } - return new OmnipodPacket(pktAddress, PacketType.ACK, podState.getPacketNumber(), ByteUtil.getBytesFromInt(msgAddress)); + return new OmnipodPacket(packetAddress, PacketType.ACK, podState.getPacketNumber(), ByteUtil.getBytesFromInt(messageAddress)); } private void ackUntilQuiet(PodState podState, Integer packetAddress, Integer messageAddress) { @@ -303,7 +314,7 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); } - podState.increasePacketNumber(1); + podState.increasePacketNumber(); } private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet) { @@ -317,26 +328,39 @@ public class OmnipodCommunicationManager extends RileyLinkCommunicationManager { private OmnipodPacket exchangePackets(PodState podState, OmnipodPacket packet, int repeatCount, int responseTimeoutMilliseconds, int exchangeTimeoutMilliseconds, int preambleExtensionMilliseconds) { long timeoutTime = System.currentTimeMillis() + exchangeTimeoutMilliseconds; + podState.increasePacketNumber(); + while (System.currentTimeMillis() < timeoutTime) { OmnipodPacket response = null; try { response = sendAndListen(packet, responseTimeoutMilliseconds, repeatCount, 9, preambleExtensionMilliseconds, OmnipodPacket.class); } catch (RileyLinkCommunicationException | OmnipodException ex) { - aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in exchangePackets", ex); + aapsLogger.debug(LTag.PUMPBTCOMM, "Ignoring exception in exchangePackets: " + ex.getClass().getSimpleName() + ": " + ex.getMessage()); + continue; } catch (Exception ex) { throw new CommunicationException(CommunicationException.Type.UNEXPECTED_EXCEPTION, ex); } - if (response == null || !response.isValid()) { + if (response == null) { + aapsLogger.debug(LTag.PUMPBTCOMM, "exchangePackets response is null"); + continue; + } else if (!response.isValid()) { + aapsLogger.debug(LTag.PUMPBTCOMM, "exchangePackets response is invalid: " + response); continue; } - if (response.getAddress() != packet.getAddress()) { - continue; - } - if (response.getSequenceNumber() != ((podState.getPacketNumber() + 1) & 0b11111)) { + if (response.getAddress() != packet.getAddress() && + response.getAddress() != OmnipodConst.DEFAULT_ADDRESS) { // In some (strange) cases, the Pod remains a packet address of 0xffffffff during it's lifetime + aapsLogger.debug(LTag.PUMPBTCOMM, "Packet address " + response.getAddress() + " doesn't match " + packet.getAddress()); continue; } - podState.increasePacketNumber(2); + if (response.getSequenceNumber() != podState.getPacketNumber()) { + aapsLogger.debug(LTag.PUMPBTCOMM, "Packet sequence number " + response.getSequenceNumber() + " does not match " + podState.getPacketNumber()); + continue; + } + + // Once we have verification that the POD heard us, we can increment our counters + podState.increasePacketNumber(); + return response; } throw new CommunicationException(CommunicationException.Type.TIMEOUT); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java index 56c8de7626..c1a4cd57c5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/OmnipodManager.java @@ -5,6 +5,7 @@ import org.joda.time.DateTimeZone; import org.joda.time.Duration; import java.util.EnumSet; +import java.util.Random; import java.util.TimeZone; import java.util.concurrent.TimeUnit; @@ -14,7 +15,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.AcknowledgeAl import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.AssignAddressAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.BolusAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.CancelDeliveryAction; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.ConfigurePodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.DeactivatePodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.GetPodInfoAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.GetStatusAction; @@ -22,6 +22,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.InsertCannula import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.PrimeAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.SetBasalScheduleAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.SetTempBasalAction; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.SetupPodAction; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.service.InsertCannulaService; import info.nightscout.androidaps.plugins.pump.omnipod.comm.action.service.PrimeService; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; @@ -61,18 +62,14 @@ public class OmnipodManager { private ActiveBolusData activeBolusData; private final Object bolusDataMutex = new Object(); - //private HasAndroidInjector injector; - AAPSLogger aapsLogger; - SP sp; + private AAPSLogger aapsLogger; + private SP sp; - public OmnipodManager(//HasAndroidInjector injector, - AAPSLogger aapsLogger, + public OmnipodManager(AAPSLogger aapsLogger, SP sp, OmnipodCommunicationManager communicationService, PodSessionState podState, PodStateChangedHandler podStateChangedHandler) { -// this.injector = injector; -// this.injector.androidInjector().inject(this); if (communicationService == null) { throw new IllegalArgumentException("Communication service cannot be null"); } @@ -86,25 +83,18 @@ public class OmnipodManager { this.podStateChangedHandler = podStateChangedHandler; } -// public OmnipodManager(HasAndroidInjector injector, -// OmnipodCommunicationManager communicationService, -// PodSessionState podState) { -// this(injector, communicationService, podState, null); -// } - - public synchronized Single pairAndPrime() { + public synchronized Single pairAndPrime(int address) { logStartingCommandExecution("pairAndPrime"); try { - if (podState == null) { + if (podState == null || podState.getSetupProgress().isBefore(SetupProgress.POD_CONFIGURED)) { + // Always send both 0x07 and 0x03 on retries podState = communicationService.executeAction( - new AssignAddressAction(podStateChangedHandler)); - } else if (SetupProgress.PRIMING.isBefore(podState.getSetupProgress())) { - throw new IllegalSetupProgressException(SetupProgress.ADDRESS_ASSIGNED, podState.getSetupProgress()); - } + new AssignAddressAction(podStateChangedHandler, address)); - if (SetupProgress.ADDRESS_ASSIGNED.equals(podState.getSetupProgress())) { - communicationService.executeAction(new ConfigurePodAction(podState)); + communicationService.executeAction(new SetupPodAction(podState)); + } else if (SetupProgress.PRIMING.isBefore(podState.getSetupProgress())) { + throw new IllegalSetupProgressException(SetupProgress.POD_CONFIGURED, podState.getSetupProgress()); } communicationService.executeAction(new PrimeAction(new PrimeService(), podState)); @@ -574,6 +564,15 @@ public class OmnipodManager { return ex instanceof OmnipodException && ((OmnipodException) ex).isCertainFailure(); } + public static int generateRandomAddress() { + // Create random address with 20 bits to match PDM, could easily use 24 bits instead + return 0x1f000000 | (new Random().nextInt() & 0x000fffff); + } + + public static boolean isValidAddress(int address) { + return (0x1f000000 | (address & 0x000fffff)) == address; + } + public static class BolusCommandResult { private final CommandDeliveryStatus commandDeliveryStatus; private final SingleSubject deliveryResultSubject; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java index b6563fa214..b5e46e38b5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/AssignAddressAction.java @@ -3,9 +3,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.action; import org.joda.time.DateTimeZone; import java.util.Collections; -import java.util.Random; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalVersionResponseTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.AssignAddressCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.VersionResponse; @@ -18,15 +19,11 @@ public class AssignAddressAction implements OmnipodAction { private final int address; private final PodStateChangedHandler podStateChangedHandler; - public AssignAddressAction(PodStateChangedHandler podStateChangedHandler) { - this.address = generateRandomAddress(); + public AssignAddressAction(PodStateChangedHandler podStateChangedHandler, int address) { + this.address = address; this.podStateChangedHandler = podStateChangedHandler; } - private static int generateRandomAddress() { - return 0x1f000000 | (new Random().nextInt() & 0x000fffff); - } - @Override public PodSessionState execute(OmnipodCommunicationManager communicationService) { PodSetupState setupState = new PodSetupState(address, 0x00, 0x00); @@ -38,6 +35,13 @@ public class AssignAddressAction implements OmnipodAction { VersionResponse assignAddressResponse = communicationService.exchangeMessages(VersionResponse.class, setupState, assignAddressMessage, OmnipodConst.DEFAULT_ADDRESS, setupState.getAddress()); + if (!assignAddressResponse.isAssignAddressVersionResponse()) { + throw new IllegalVersionResponseTypeException("assignAddress", "setupPod"); + } + if (assignAddressResponse.getAddress() != address) { + throw new IllegalMessageAddressException(address, assignAddressResponse.getAddress()); + } + DateTimeZone timeZone = DateTimeZone.getDefault(); PodSessionState podState = new PodSessionState(timeZone, address, assignAddressResponse.getPiVersion(), diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java index 1732ddf533..380eb0ce3d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/PrimeAction.java @@ -28,7 +28,7 @@ public class PrimeAction implements OmnipodAction { } public static void updatePrimingStatus(PodSessionState podState, StatusResponse statusResponse, AAPSLogger aapsLogger) { - if (podState.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.READY_FOR_BASAL_SCHEDULE)) { + if (podState.getSetupProgress().equals(SetupProgress.PRIMING) && statusResponse.getPodProgressStatus().equals(PodProgressStatus.PRIMING_COMPLETED)) { aapsLogger.debug(LTag.PUMPBTCOMM, "Updating SetupProgress from PRIMING to PRIMING_FINISHED"); podState.setSetupProgress(SetupProgress.PRIMING_FINISHED); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigurePodAction.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java similarity index 64% rename from app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigurePodAction.java rename to app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java index 7d2cb3b7e3..52979c91f3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/ConfigurePodAction.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/action/SetupPodAction.java @@ -5,22 +5,24 @@ import org.joda.time.DateTime; import java.util.Collections; import info.nightscout.androidaps.plugins.pump.omnipod.comm.OmnipodCommunicationManager; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPacketTypeException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPodProgressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalSetupProgressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalVersionResponseTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.OmnipodMessage; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.ConfigurePodCommand; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.command.SetupPodCommand; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.VersionResponse; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PacketType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress; import info.nightscout.androidaps.plugins.pump.omnipod.defs.state.PodSessionState; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPacketTypeException; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPodProgressException; -import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalSetupProgressException; import info.nightscout.androidaps.plugins.pump.omnipod.util.OmnipodConst; -public class ConfigurePodAction implements OmnipodAction { +public class SetupPodAction implements OmnipodAction { private final PodSessionState podState; - public ConfigurePodAction(PodSessionState podState) { + public SetupPodAction(PodSessionState podState) { this.podState = podState; } @@ -31,13 +33,13 @@ public class ConfigurePodAction implements OmnipodAction { } DateTime activationDate = DateTime.now(podState.getTimeZone()); - ConfigurePodCommand configurePodCommand = new ConfigurePodCommand(podState.getAddress(), activationDate, + SetupPodCommand setupPodCommand = new SetupPodCommand(podState.getAddress(), activationDate, podState.getLot(), podState.getTid()); OmnipodMessage message = new OmnipodMessage(OmnipodConst.DEFAULT_ADDRESS, - Collections.singletonList(configurePodCommand), podState.getMessageNumber()); - VersionResponse configurePodResponse; + Collections.singletonList(setupPodCommand), podState.getMessageNumber()); + VersionResponse setupPodResponse; try { - configurePodResponse = communicationService.exchangeMessages(VersionResponse.class, podState, + setupPodResponse = communicationService.exchangeMessages(VersionResponse.class, podState, message, OmnipodConst.DEFAULT_ADDRESS, podState.getAddress()); } catch (IllegalPacketTypeException ex) { if (PacketType.ACK.equals(ex.getActual())) { @@ -48,12 +50,18 @@ public class ConfigurePodAction implements OmnipodAction { throw ex; } - if (configurePodResponse.getPodProgressStatus() != PodProgressStatus.PAIRING_SUCCESS) { - throw new IllegalPodProgressException(PodProgressStatus.PAIRING_SUCCESS, configurePodResponse.getPodProgressStatus()); + if (!setupPodResponse.isSetupPodVersionResponse()) { + throw new IllegalVersionResponseTypeException("setupPod", "assignAddress"); + } + if (setupPodResponse.getAddress() != podState.getAddress()) { + throw new IllegalMessageAddressException(podState.getAddress(), setupPodResponse.getAddress()); + } + if (setupPodResponse.getPodProgressStatus() != PodProgressStatus.PAIRING_COMPLETED) { + throw new IllegalPodProgressException(PodProgressStatus.PAIRING_COMPLETED, setupPodResponse.getPodProgressStatus()); } podState.setSetupProgress(SetupProgress.POD_CONFIGURED); - return configurePodResponse; + return setupPodResponse; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageAddressException.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageAddressException.java new file mode 100644 index 0000000000..9c674cd8ca --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageAddressException.java @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.comm.exception; + +import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; + +public class IllegalMessageAddressException extends OmnipodException { + private final int expected; + private final int actual; + + public IllegalMessageAddressException(int expected, int actual) { + super("Invalid message address. Expected="+ expected +", actual="+ actual, false); + this.expected = expected; + this.actual = actual; + } + + public int getExpected() { + return expected; + } + + public int getActual() { + return actual; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageSequenceNumberException.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageSequenceNumberException.java new file mode 100644 index 0000000000..b26d2b6ff8 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalMessageSequenceNumberException.java @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.comm.exception; + +import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; + +public class IllegalMessageSequenceNumberException extends OmnipodException { + private final int expected; + private final int actual; + + public IllegalMessageSequenceNumberException(int expected, int actual) { + super("Invalid message sequence number. Expected="+ expected +", actual="+ actual, false); + this.expected = expected; + this.actual = actual; + } + + public int getExpected() { + return expected; + } + + public int getActual() { + return actual; + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalVersionResponseTypeException.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalVersionResponseTypeException.java new file mode 100644 index 0000000000..0dbe0805d5 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/IllegalVersionResponseTypeException.java @@ -0,0 +1,9 @@ +package info.nightscout.androidaps.plugins.pump.omnipod.comm.exception; + +import info.nightscout.androidaps.plugins.pump.omnipod.exception.OmnipodException; + +public class IllegalVersionResponseTypeException extends OmnipodException { + public IllegalVersionResponseTypeException(String expected, String actual) { + super("Invalid Version Response type. Expected="+ expected +", actual="+ actual, false); + } +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodFaultException.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodFaultException.java index 6269f1c39c..7f90a3af36 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodFaultException.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodFaultException.java @@ -7,7 +7,7 @@ public class PodFaultException extends OmnipodException { private final PodInfoFaultEvent faultEvent; public PodFaultException(PodInfoFaultEvent faultEvent) { - super(faultEvent.getFaultEventType().toString(), true); + super(faultEvent.getFaultEventCode().toString(), true); this.faultEvent = faultEvent; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodReturnedErrorResponseException.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodReturnedErrorResponseException.java index f43987b755..d552151142 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodReturnedErrorResponseException.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/exception/PodReturnedErrorResponseException.java @@ -7,7 +7,7 @@ public class PodReturnedErrorResponseException extends OmnipodException { private final ErrorResponse errorResponse; public PodReturnedErrorResponseException(ErrorResponse errorResponse) { - super("Pod returned error response: " + errorResponse.getErrorResponseType(), true); + super("Pod returned error response: " + errorResponse, true); this.errorResponse = errorResponse; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodMessage.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodMessage.java index c328997172..78cfa72e19 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodMessage.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/OmnipodMessage.java @@ -97,6 +97,10 @@ public class OmnipodMessage { } } + public int getAddress() { + return address; + } + public List getMessageBlocks() { return messageBlocks; } @@ -135,7 +139,6 @@ public class OmnipodMessage { return false; } - @Override public String toString() { return "OmnipodMessage{" + 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 fd90ffb640..157e72e51b 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,5 +1,7 @@ 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; @@ -79,4 +81,14 @@ public class OmnipodPacket implements RLMessage { return valid; } + @Override + public String toString() { + return "OmnipodPacket{" + + "packetAddress=" + packetAddress + + ", packetType=" + packetType + + ", sequenceNumber=" + sequenceNumber + + ", encodedMessage=" + ByteUtil.shortHexStringWithoutSpaces(encodedMessage) + + ", valid=" + valid + + '}'; + } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/ConfigurePodCommand.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/SetupPodCommand.java similarity index 90% rename from app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/ConfigurePodCommand.java rename to app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/SetupPodCommand.java index 0f35a1fa24..7ef667d5b6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/ConfigurePodCommand.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/command/SetupPodCommand.java @@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; -public class ConfigurePodCommand extends MessageBlock { +public class SetupPodCommand extends MessageBlock { private static final byte PACKET_TIMEOUT_LIMIT = 0x04; @@ -15,7 +15,7 @@ public class ConfigurePodCommand extends MessageBlock { private final DateTime date; private final int address; - public ConfigurePodCommand(int address, DateTime date, int lot, int tid) { + public SetupPodCommand(int address, DateTime date, int lot, int tid) { this.address = address; this.lot = lot; this.tid = tid; @@ -46,7 +46,7 @@ public class ConfigurePodCommand extends MessageBlock { @Override public String toString() { - return "ConfigurePodCommand{" + + return "SetupPodCommand{" + "lot=" + lot + ", tid=" + tid + ", date=" + date + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/ErrorResponse.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/ErrorResponse.java index 18f02475e1..009baaeee4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/ErrorResponse.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/ErrorResponse.java @@ -2,14 +2,19 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.MessageBlock; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.ErrorResponseType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; public class ErrorResponse extends MessageBlock { + public static final byte ERROR_RESPONSE_CODE_BAD_NONCE = (byte) 0x14; + private static final int MESSAGE_LENGTH = 5; - private final ErrorResponseType errorResponseType; - private final int nonceSearchKey; + private final byte errorResponseCode; + private Integer nonceSearchKey; // only valid for BAD_NONCE + private FaultEventCode faultEventCode; // valid for all but BAD_NONCE + private PodProgressStatus podProgressStatus; // valid for all but BAD_NONCE public ErrorResponse(byte[] encodedData) { if (encodedData.length < MESSAGE_LENGTH) { @@ -17,14 +22,14 @@ public class ErrorResponse extends MessageBlock { } this.encodedData = ByteUtil.substring(encodedData, 2, MESSAGE_LENGTH - 2); - ErrorResponseType errorResponseType = null; - try { - errorResponseType = ErrorResponseType.fromByte(encodedData[2]); - } catch (IllegalArgumentException ex) { - } + errorResponseCode = encodedData[2]; - this.errorResponseType = errorResponseType; - this.nonceSearchKey = ByteUtil.makeUnsignedShort((int) encodedData[3], (int) encodedData[4]); + if (this.errorResponseCode == ERROR_RESPONSE_CODE_BAD_NONCE) { + nonceSearchKey = ByteUtil.makeUnsignedShort(encodedData[3], encodedData[4]); + } else { + faultEventCode = FaultEventCode.fromByte(encodedData[3]); + podProgressStatus = PodProgressStatus.fromByte(encodedData[4]); + } } @Override @@ -32,19 +37,29 @@ public class ErrorResponse extends MessageBlock { return MessageBlockType.ERROR_RESPONSE; } - public ErrorResponseType getErrorResponseType() { - return errorResponseType; + public byte getErrorResponseCode() { + return errorResponseCode; } - public int getNonceSearchKey() { + public FaultEventCode getFaultEventCode() { + return faultEventCode; + } + + public PodProgressStatus getPodProgressStatus() { + return podProgressStatus; + } + + public Integer getNonceSearchKey() { return nonceSearchKey; } @Override public String toString() { return "ErrorResponse{" + - "errorResponseType=" + errorResponseType + + "errorResponseCode=" + errorResponseCode + ", nonceSearchKey=" + nonceSearchKey + + ", faultEventCode=" + faultEventCode + + ", podProgressStatus=" + podProgressStatus + '}'; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/StatusResponse.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/StatusResponse.java index a9d831f8ae..ec99632553 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/StatusResponse.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/StatusResponse.java @@ -31,20 +31,20 @@ public class StatusResponse extends MessageBlock { } this.encodedData = ByteUtil.substring(encodedData, 1, MESSAGE_LENGTH - 1); - this.deliveryStatus = DeliveryStatus.fromByte((byte) (ByteUtil.convertUnsignedByteToInt(encodedData[1]) >>> 4)); - this.podProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[1] & 0x0F)); + deliveryStatus = DeliveryStatus.fromByte((byte) (ByteUtil.convertUnsignedByteToInt(encodedData[1]) >>> 4)); + podProgressStatus = PodProgressStatus.fromByte((byte) (encodedData[1] & 0x0F)); int minutes = ((encodedData[7] & 0x7F) << 6) | ((encodedData[8] & 0xFC) >>> 2); - this.timeActive = Duration.standardMinutes(minutes); + timeActive = Duration.standardMinutes(minutes); int highInsulinBits = (encodedData[2] & 0xF) << 9; int middleInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[3]) << 1; int lowInsulinBits = ByteUtil.convertUnsignedByteToInt(encodedData[4]) >>> 7; - this.insulinDelivered = OmnipodConst.POD_PULSE_SIZE * (highInsulinBits | middleInsulinBits | lowInsulinBits); - this.podMessageCounter = (byte) ((encodedData[4] >>> 3) & 0xf); + insulinDelivered = OmnipodConst.POD_PULSE_SIZE * (highInsulinBits | middleInsulinBits | lowInsulinBits); + podMessageCounter = (byte) ((encodedData[4] >>> 3) & 0xf); - this.insulinNotDelivered = OmnipodConst.POD_PULSE_SIZE * (((encodedData[4] & 0x03) << 8) | ByteUtil.convertUnsignedByteToInt(encodedData[5])); - this.alerts = new AlertSet((byte) (((encodedData[6] & 0x7f) << 1) | (ByteUtil.convertUnsignedByteToInt(encodedData[7]) >>> 7))); + insulinNotDelivered = OmnipodConst.POD_PULSE_SIZE * (((encodedData[4] & 0x03) << 8) | ByteUtil.convertUnsignedByteToInt(encodedData[5])); + alerts = new AlertSet((byte) (((encodedData[6] & 0x7f) << 1) | (ByteUtil.convertUnsignedByteToInt(encodedData[7]) >>> 7))); double reservoirValue = (((encodedData[8] & 0x3) << 8) + ByteUtil.convertUnsignedByteToInt(encodedData[9])) * OmnipodConst.POD_PULSE_SIZE; if (reservoirValue > OmnipodConst.MAX_RESERVOIR_READING) { @@ -94,7 +94,7 @@ public class StatusResponse extends MessageBlock { public byte[] getRawData() { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { - stream.write(this.getType().getValue()); + stream.write(getType().getValue()); stream.write(encodedData); } catch (IOException e) { e.printStackTrace(); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/VersionResponse.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/VersionResponse.java index a8c9e9403d..c62add6732 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/VersionResponse.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/VersionResponse.java @@ -7,45 +7,51 @@ import info.nightscout.androidaps.plugins.pump.omnipod.defs.MessageBlockType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; public class VersionResponse extends MessageBlock { + private static final int ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH = 0x15; + private static final int SETUP_POD_VERSION_RESPONSE_LENGTH = 0x1b; + private final PodProgressStatus podProgressStatus; private final FirmwareVersion pmVersion; private final FirmwareVersion piVersion; private final int lot; private final int tid; + private Byte gain; // Only in the assign address version response + private Byte rssi; // Only in the assign address version response private final int address; - public VersionResponse(byte[] encodedData) { - int length = ByteUtil.convertUnsignedByteToInt(encodedData[1]) + 2; - this.encodedData = ByteUtil.substring(encodedData, 2, length - 2); - - boolean extraByte; - byte[] truncatedData; + public VersionResponse(byte[] data) { + int length = ByteUtil.convertUnsignedByteToInt(data[1]); + this.encodedData = ByteUtil.substring(data, 2, length); switch (length) { - case 0x17: - truncatedData = ByteUtil.substring(encodedData, 2); - extraByte = true; + case ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH: + podProgressStatus = PodProgressStatus.fromByte(data[9]); + pmVersion = new FirmwareVersion(data[2], data[3], data[4]); + piVersion = new FirmwareVersion(data[5], data[6], data[7]); + lot = ByteUtil.toInt((int) data[10], (int) data[11], + (int) data[12], (int) data[13], ByteUtil.BitConversion.BIG_ENDIAN); + tid = ByteUtil.toInt((int) data[14], (int) data[15], + (int) data[16], (int) data[17], ByteUtil.BitConversion.BIG_ENDIAN); + gain = (byte) ((data[18] & 0xc0) >>> 6); + rssi = (byte) (data[18] & 0x3f); + address = ByteUtil.toInt((int) data[19], (int) data[20], + (int) data[21], (int) data[22], ByteUtil.BitConversion.BIG_ENDIAN); break; - case 0x1D: - truncatedData = ByteUtil.substring(encodedData, 9); - extraByte = false; + case SETUP_POD_VERSION_RESPONSE_LENGTH: + podProgressStatus = PodProgressStatus.fromByte(data[16]); + pmVersion = new FirmwareVersion(data[9], data[10], data[11]); + piVersion = new FirmwareVersion(data[12], data[13], data[14]); + lot = ByteUtil.toInt((int) data[17], (int) data[18], + (int) data[19], (int) data[20], ByteUtil.BitConversion.BIG_ENDIAN); + tid = ByteUtil.toInt((int) data[21], (int) data[22], + (int) data[23], (int) data[24], ByteUtil.BitConversion.BIG_ENDIAN); + + address = ByteUtil.toInt((int) data[25], (int) data[26], + (int) data[27], (int) data[28], ByteUtil.BitConversion.BIG_ENDIAN); break; default: throw new IllegalArgumentException("Unrecognized VersionResponse message length: " + length); } - - this.podProgressStatus = PodProgressStatus.fromByte(truncatedData[7]); - this.pmVersion = new FirmwareVersion(truncatedData[0], truncatedData[1], truncatedData[2]); - this.piVersion = new FirmwareVersion(truncatedData[3], truncatedData[4], truncatedData[5]); - this.lot = ByteUtil.toInt((int) truncatedData[8], (int) truncatedData[9], - (int) truncatedData[10], (int) truncatedData[11], ByteUtil.BitConversion.BIG_ENDIAN); - this.tid = ByteUtil.toInt((int) truncatedData[12], (int) truncatedData[13], - (int) truncatedData[14], (int) truncatedData[15], ByteUtil.BitConversion.BIG_ENDIAN); - - int indexIncrementor = extraByte ? 1 : 0; - - this.address = ByteUtil.toInt((int) truncatedData[16 + indexIncrementor], (int) truncatedData[17 + indexIncrementor], - (int) truncatedData[18 + indexIncrementor], (int) truncatedData[19 + indexIncrementor], ByteUtil.BitConversion.BIG_ENDIAN); } @Override @@ -73,6 +79,22 @@ public class VersionResponse extends MessageBlock { return tid; } + public Byte getGain() { + return gain; + } + + public Byte getRssi() { + return rssi; + } + + public boolean isAssignAddressVersionResponse() { + return encodedData.length == ASSIGN_ADDRESS_VERSION_RESPONSE_LENGTH; + } + + public boolean isSetupPodVersionResponse() { + return encodedData.length == SETUP_POD_VERSION_RESPONSE_LENGTH; + } + public int getAddress() { return address; } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoDataLog.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoDataLog.java index a8eebc7696..b8e28169d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoDataLog.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoDataLog.java @@ -7,12 +7,12 @@ import java.util.Collections; import java.util.List; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; public class PodInfoDataLog extends PodInfo { private static final int MINIMUM_MESSAGE_LENGTH = 8; - private final FaultEventType faultEventType; + private final FaultEventCode faultEventCode; private final Duration timeFaultEvent; private final Duration timeSinceActivation; private final byte dataChunkSize; @@ -26,7 +26,7 @@ public class PodInfoDataLog extends PodInfo { throw new IllegalArgumentException("Not enough data"); } - faultEventType = FaultEventType.fromByte(encodedData[1]); + faultEventCode = FaultEventCode.fromByte(encodedData[1]); timeFaultEvent = Duration.standardMinutes(ByteUtil.toInt(encodedData[2], encodedData[3])); timeSinceActivation = Duration.standardMinutes(ByteUtil.toInt(encodedData[4], encodedData[5])); dataChunkSize = encodedData[6]; @@ -45,8 +45,8 @@ public class PodInfoDataLog extends PodInfo { return PodInfoType.DATA_LOG; } - public FaultEventType getFaultEventType() { - return faultEventType; + public FaultEventCode getFaultEventCode() { + return faultEventCode; } public Duration getTimeFaultEvent() { @@ -72,7 +72,7 @@ public class PodInfoDataLog extends PodInfo { @Override public String toString() { return "PodInfoDataLog{" + - "faultEventType=" + faultEventType + + "faultEventCode=" + faultEventCode + ", timeFaultEvent=" + timeFaultEvent + ", timeSinceActivation=" + timeSinceActivation + ", dataChunkSize=" + dataChunkSize + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultAndInitializationTime.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultAndInitializationTime.java index 747b5e821b..2fd1d90406 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultAndInitializationTime.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultAndInitializationTime.java @@ -3,12 +3,12 @@ package info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.po import org.joda.time.DateTime; import org.joda.time.Duration; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; public class PodInfoFaultAndInitializationTime extends PodInfo { private static final int MINIMUM_MESSAGE_LENGTH = 17; - private final FaultEventType faultEventType; + private final FaultEventCode faultEventCode; private final Duration timeFaultEvent; private final DateTime initializationTime; @@ -19,7 +19,7 @@ public class PodInfoFaultAndInitializationTime extends PodInfo { throw new IllegalArgumentException("Not enough data"); } - faultEventType = FaultEventType.fromByte(encodedData[1]); + faultEventCode = FaultEventCode.fromByte(encodedData[1]); timeFaultEvent = Duration.standardMinutes(((encodedData[2] & 0b1) << 8) + encodedData[3]); // We ignore time zones here because we don't keep the time zone in which the pod was initially set up // Which is fine because we don't use the initialization time for anything important anyway @@ -31,8 +31,8 @@ public class PodInfoFaultAndInitializationTime extends PodInfo { return PodInfoType.FAULT_AND_INITIALIZATION_TIME; } - public FaultEventType getFaultEventType() { - return faultEventType; + public FaultEventCode getFaultEventCode() { + return faultEventCode; } public Duration getTimeFaultEvent() { @@ -46,7 +46,7 @@ public class PodInfoFaultAndInitializationTime extends PodInfo { @Override public String toString() { return "PodInfoFaultAndInitializationTime{" + - "faultEventType=" + faultEventType + + "faultEventCode=" + faultEventCode + ", timeFaultEvent=" + timeFaultEvent + ", initializationTime=" + initializationTime + '}'; diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultEvent.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultEvent.java index 9db41a12f7..129ef989bb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultEvent.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/comm/message/response/podinfo/PodInfoFaultEvent.java @@ -5,7 +5,7 @@ import org.joda.time.Duration; import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSet; import info.nightscout.androidaps.plugins.pump.omnipod.defs.DeliveryStatus; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.LogEventErrorCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodProgressStatus; @@ -19,7 +19,7 @@ public class PodInfoFaultEvent extends PodInfo { private final double insulinNotDelivered; private final byte podMessageCounter; private final double totalInsulinDelivered; - private final FaultEventType faultEventType; + private final FaultEventCode faultEventCode; private final Duration faultEventTime; private final Double reservoirLevel; private final Duration timeSinceActivation; @@ -44,7 +44,7 @@ public class PodInfoFaultEvent extends PodInfo { insulinNotDelivered = OmnipodConst.POD_PULSE_SIZE * ByteUtil.toInt(encodedData[3], encodedData[4]); podMessageCounter = encodedData[5]; totalInsulinDelivered = OmnipodConst.POD_PULSE_SIZE * ByteUtil.toInt(encodedData[6], encodedData[7]); - faultEventType = FaultEventType.fromByte(encodedData[8]); + faultEventCode = FaultEventCode.fromByte(encodedData[8]); int minutesSinceActivation = ByteUtil.toInt(encodedData[9], encodedData[10]); if (minutesSinceActivation == 0xffff) { @@ -99,8 +99,8 @@ public class PodInfoFaultEvent extends PodInfo { return totalInsulinDelivered; } - public FaultEventType getFaultEventType() { - return faultEventType; + public FaultEventCode getFaultEventCode() { + return faultEventCode; } public Duration getFaultEventTime() { @@ -155,7 +155,7 @@ public class PodInfoFaultEvent extends PodInfo { ", insulinNotDelivered=" + insulinNotDelivered + ", podMessageCounter=" + podMessageCounter + ", totalInsulinDelivered=" + totalInsulinDelivered + - ", faultEventType=" + faultEventType + + ", faultEventCode=" + faultEventCode + ", faultEventTime=" + faultEventTime + ", reservoirLevel=" + reservoirLevel + ", timeSinceActivation=" + timeSinceActivation + diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/ErrorResponseType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/ErrorResponseType.java deleted file mode 100644 index 883ae94821..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/ErrorResponseType.java +++ /dev/null @@ -1,24 +0,0 @@ -package info.nightscout.androidaps.plugins.pump.omnipod.defs; - -public enum ErrorResponseType { - BAD_NONCE((byte) 0x14); - - private byte value; - - ErrorResponseType(byte value) { - this.value = value; - } - - public static ErrorResponseType fromByte(byte value) { - for (ErrorResponseType type : values()) { - if (type.value == value) { - return type; - } - } - throw new IllegalArgumentException("Unknown ErrorResponseType: " + value); - } - - public byte getValue() { - return value; - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventType.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventCode.java similarity index 95% rename from app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventType.java rename to app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventCode.java index 69a74aa4c4..df17fd0b5c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventType.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/FaultEventCode.java @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.pump.omnipod.defs; import java.util.Locale; -public enum FaultEventType { +public enum FaultEventCode { NO_FAULTS((byte) 0x00), FAILED_FLASH_ERASE((byte) 0x01), FAILED_FLASH_STORE((byte) 0x02), @@ -124,17 +124,17 @@ public enum FaultEventType { private byte value; - FaultEventType(byte value) { + FaultEventCode(byte value) { this.value = value; } - public static FaultEventType fromByte(byte value) { - for (FaultEventType type : values()) { + public static FaultEventCode fromByte(byte value) { + for (FaultEventCode type : values()) { if (type.value == value) { return type; } } - throw new IllegalArgumentException("Unknown FaultEventType: " + value); + throw new IllegalArgumentException("Unknown FaultEventCode: " + value); } public byte getValue() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodCommunicationManagerInterface.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodCommunicationManagerInterface.java index 3999cd2923..d345a3c385 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodCommunicationManagerInterface.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/OmnipodCommunicationManagerInterface.java @@ -71,9 +71,5 @@ public interface OmnipodCommunicationManagerInterface { */ PumpEnactResult setTime(); - - void setPumpStatus(OmnipodPumpStatus pumpStatusLocal); - - PodInfoRecentPulseLog readPulseLog(); } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodProgressStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodProgressStatus.java index 4bd9780118..1ee1307bd4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodProgressStatus.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/PodProgressStatus.java @@ -1,22 +1,22 @@ package info.nightscout.androidaps.plugins.pump.omnipod.defs; public enum PodProgressStatus { - INITIAL_VALUE((byte) 0x00), - TANK_POWER_ACTIVATED((byte) 0x01), - TANK_FILL_COMPLETED((byte) 0x02), - PAIRING_SUCCESS((byte) 0x03), + INITIALIZED((byte) 0x00), + MEMORY_INITIALIZED((byte) 0x01), + REMINDER_INITIALIZED((byte) 0x02), + PAIRING_COMPLETED((byte) 0x03), PRIMING((byte) 0x04), - READY_FOR_BASAL_SCHEDULE((byte) 0x05), - READY_FOR_CANNULA_INSERTION((byte) 0x06), - CANNULA_INSERTING((byte) 0x07), - RUNNING_ABOVE_FIFTY_UNITS((byte) 0x08), - RUNNING_BELOW_FIFTY_UNITS((byte) 0x09), - ONE_NOT_USED_BUT_IN_33((byte) 0x0a), - TWO_NOT_USED_BUT_IN_33((byte) 0x0b), - THREE_NOT_USED_BUT_IN_33((byte) 0x0c), - FAULT_EVENT_OCCURRED((byte) 0x0d), - FAILED_TO_INITIALIZE_IN_TIME((byte) 0x0e), - INACTIVE((byte) 0x0f); + PRIMING_COMPLETED((byte) 0x05), + BASAL_INITIALIZED((byte) 0x06), + INSERTING_CANNULA((byte) 0x07), + ABOVE_FIFTY_UNITS((byte) 0x08), + FIFTY_OR_LESS_UNITS((byte) 0x09), + ONE_NOT_USED((byte) 0x0a), + TWO_NOT_USED((byte) 0x0b), + THREE_NOT_USED((byte) 0x0c), + FAULT_EVENT_OCCURRED((byte) 0x0d), // Fault event occurred (a "screamer") + ACTIVATION_TIME_EXCEEDED((byte) 0x0e), // Took > 2 hours from progress 2 to 3 or > 1 hour from 3 to 8 + INACTIVE((byte) 0x0f); // Pod deactivated or a fatal packet state error private byte value; @@ -38,6 +38,6 @@ public enum PodProgressStatus { } public boolean isReadyForDelivery() { - return this == RUNNING_ABOVE_FIFTY_UNITS || this == RUNNING_BELOW_FIFTY_UNITS; + return this == ABOVE_FIFTY_UNITS || this == FIFTY_OR_LESS_UNITS; } } diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java index 22bd4293fe..862976afbc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodSessionState.java @@ -33,12 +33,19 @@ import info.nightscout.androidaps.utils.sharedPreferences.SP; public class PodSessionState extends PodState { - @Inject AAPSLogger aapsLogger; - @Inject SP sp; - @Inject OmnipodUtil omnipodUtil; + @Inject transient AAPSLogger aapsLogger; + @Inject transient SP sp; + @Inject transient OmnipodUtil omnipodUtil; + @Inject transient DateUtil dateUtil; - private final Map configuredAlerts; private transient PodStateChangedHandler stateChangedHandler; + + // TODO + // the problem you have with injection in this class is that you are mixing + // data storing and handlind. Move these member variables to extra class you can + // easy serialize and load it here by setData(dataInOtherClass) + private final Map configuredAlerts; + private DateTimeZone timeZone; private DateTime activatedAt; private DateTime expiresAt; private final FirmwareVersion piVersion; @@ -47,8 +54,6 @@ public class PodSessionState extends PodState { private final int tid; private Double reservoirLevel; private boolean suspended; - - private DateTimeZone timeZone; private NonceState nonceState; private SetupProgress setupProgress; private AlertSet activeAlerts; @@ -77,10 +82,12 @@ public class PodSessionState extends PodState { handleUpdates(); } + @Deprecated public void injectDaggerClass(HasAndroidInjector injector) { injector.androidInjector().inject(this); } + @Deprecated public void setStateChangedHandler(PodStateChangedHandler handler) { // FIXME this is an ugly workaround for not being able to serialize the PodStateChangedHandler if (stateChangedHandler != null) { @@ -112,7 +119,7 @@ public class PodSessionState extends PodState { } public String getExpiryDateAsString() { - return expiresAt == null ? "???" : DateUtil.dateAndTimeString(expiresAt.toDate()); + return expiresAt == null ? "???" : dateUtil.dateAndTimeString(expiresAt.toDate()); } public FirmwareVersion getPiVersion() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java index 2e19de1286..c6987c879e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/defs/state/PodState.java @@ -46,12 +46,12 @@ public abstract class PodState { this.packetNumber = packetNumber; } - public void increaseMessageNumber(int increment) { - setMessageNumber((messageNumber + increment) & 0b1111); + public void increaseMessageNumber() { + setMessageNumber((messageNumber + 1) & 0b1111); } - public void increasePacketNumber(int increment) { - setPacketNumber((packetNumber + increment) & 0b11111); + public void increasePacketNumber() { + setPacketNumber((packetNumber + 1) & 0b11111); } public boolean hasFaultEvent() { 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 c3a7bfeccd..20c3078b1a 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 @@ -13,7 +13,7 @@ import info.nightscout.androidaps.events.EventRefreshOverview 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.ProfileFunction +import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.pump.omnipod.defs.SetupProgress import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.defs.PodActionType import info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.model.FullInitPodWizardModel @@ -157,7 +157,7 @@ class PodManagementActivity : NoSplashAppCompatActivity() { val isPodSessionActive = (omnipodUtil.getPodSessionState() != null) initpod_remove_pod.isEnabled = isPodSessionActive - initpod_reset_pod.isEnabled = isPodSessionActive + initpod_reset_pod.isEnabled = isPodSessionActive || omnipodUtil.hasNextPodAddress() if (omnipodUtil.getDriverState() == OmnipodDriverState.NotInitalized) { // if rileylink is not running we disable all operations diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitActionFragment.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitActionFragment.java index 7cb106ca47..387daee11a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitActionFragment.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dialogs/wizard/initpod/InitActionFragment.java @@ -24,11 +24,8 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import javax.inject.Inject; - import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.PumpEnactResult; -import info.nightscout.androidaps.plugins.configBuilder.ProfileFunction; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitReceiver; 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 32f6eabac4..1ab711871c 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 @@ -1,12 +1,11 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dialogs.wizard.initpod; import android.os.AsyncTask; -import android.os.SystemClock; import android.view.View; import javax.inject.Inject; -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/driver/comm/AapsOmnipodManager.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/comm/AapsOmnipodManager.java index f9fdcf8a83..6632cd0213 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 android.text.TextUtils; @@ -44,10 +45,13 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommandIni import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CommunicationException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.CrcMismatchException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalDeliveryStatusException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageAddressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalMessageSequenceNumberException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPacketTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalPodProgressException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalResponseException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalSetupProgressException; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.IllegalVersionResponseTypeException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.MessageDecodingException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NonceOutOfSyncException; import info.nightscout.androidaps.plugins.pump.omnipod.comm.exception.NonceResyncException; @@ -59,7 +63,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.pod import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoResponse; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.defs.AlertType; -import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventType; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.FaultEventCode; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunicationManagerInterface; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInfoType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodInitActionType; @@ -80,42 +84,47 @@ import io.reactivex.disposables.Disposable; public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface { - 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; + @Deprecated private static AapsOmnipodManager instance; private Date lastBolusTime; private Double lastBolusUnits; + @Deprecated public static AapsOmnipodManager getInstance() { return instance; } public AapsOmnipodManager(OmnipodCommunicationManager communicationService, PodSessionState podState, - OmnipodPumpStatus _pumpStatus, + OmnipodPumpStatus pumpStatus, OmnipodUtil omnipodUtil, AAPSLogger aapsLogger, RxBusWrapper rxBus, SP sp, ResourceHelper resourceHelper, HasAndroidInjector injector, - ActivePluginProvider activePlugin) { + ActivePluginProvider activePlugin, + Context context) { this.omnipodUtil = omnipodUtil; this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.resourceHelper = resourceHelper; this.injector = injector; this.activePlugin = activePlugin; - this.pumpStatus = _pumpStatus; + this.pumpStatus = pumpStatus; + this.context = context; delegate = new OmnipodManager(aapsLogger, sp, communicationService, podState, podSessionState -> { // Handle pod state changes @@ -194,8 +203,13 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface long time = System.currentTimeMillis(); if (PodInitActionType.PairAndPrimeWizardStep.equals(podInitActionType)) { try { - Disposable disposable = delegate.pairAndPrime().subscribe(res -> // + int address = obtainNextPodAddress(); + + Disposable disposable = delegate.pairAndPrime(address).subscribe(res -> // handleSetupActionResult(podInitActionType, podInitReceiver, res, time, null)); + + removeNextPodAddress(); + return new PumpEnactResult(injector).success(true).enacted(true); } catch (Exception ex) { String comment = handleAndTranslateException(ex); @@ -299,6 +313,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface reportImplicitlyCanceledTbr(); this.omnipodUtil.setPodSessionState(null); + this.omnipodUtil.removeNextPodAddress(); addSuccessToHistory(System.currentTimeMillis(), PodHistoryEntryType.ResetPodState, null); @@ -355,7 +370,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface activePlugin.getActiveTreatments().addToHistoryTreatment(detailedBolusInfo, false); if (delegate.getPodState().hasFaultEvent()) { - showPodFaultErrorDialog(delegate.getPodState().getFaultEvent().getFaultEventType(), R.raw.urgentalarm); + showPodFaultErrorDialog(delegate.getPodState().getFaultEvent().getFaultEventCode(), R.raw.urgentalarm); } return new PumpEnactResult(injector).success(true).enacted(true).bolusDelivered(unitsDelivered); @@ -371,7 +386,7 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface addSuccessToHistory(time, PodHistoryEntryType.CancelBolus, null); return new PumpEnactResult(injector).success(true).enacted(true); } catch (PodFaultException ex) { - showPodFaultErrorDialog(ex.getFaultEvent().getFaultEventType(), null); + showPodFaultErrorDialog(ex.getFaultEvent().getFaultEventCode(), null); addSuccessToHistory(time, PodHistoryEntryType.CancelBolus, null); return new PumpEnactResult(injector).success(true).enacted(true); } catch (Exception ex) { @@ -451,12 +466,6 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface return new PumpEnactResult(injector).success(true).enacted(true); } - @Override - public void setPumpStatus(OmnipodPumpStatus pumpStatus) { - this.pumpStatus = pumpStatus; - updatePumpStatus(delegate.getPodState()); - } - // TODO should we add this to the OmnipodCommunicationManager interface? public PumpEnactResult getPodInfo(PodInfoType podInfoType) { long time = System.currentTimeMillis(); @@ -562,18 +571,15 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } } - - public long addSuccessToHistory(long requestTime, PodHistoryEntryType entryType, Object data) { + private long addSuccessToHistory(long requestTime, PodHistoryEntryType entryType, Object data) { return addToHistory(requestTime, entryType, data, true); } - public long addFailureToHistory(long requestTime, PodHistoryEntryType entryType, Object data) { + private long addFailureToHistory(long requestTime, PodHistoryEntryType entryType, Object data) { return addToHistory(requestTime, entryType, data, false); } - - public long addToHistory(long requestTime, PodHistoryEntryType entryType, Object data, boolean success) { - + private long addToHistory(long requestTime, PodHistoryEntryType entryType, Object data, boolean success) { PodHistory podHistory = new PodHistory(requestTime, entryType); if (data != null) { @@ -590,7 +596,20 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface MainApp.getDbHelper().createOrUpdate(podHistory); return podHistory.getPumpId(); + } + private int obtainNextPodAddress() { + Integer nextPodAddress = this.omnipodUtil.getNextPodAddress(); + if (nextPodAddress == null) { + nextPodAddress = OmnipodManager.generateRandomAddress(); + this.omnipodUtil.setNextPodAddress(nextPodAddress); + } + + return nextPodAddress; + } + + private void removeNextPodAddress() { + this.omnipodUtil.removeNextPodAddress(); } private void handleSetupActionResult(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, SetupActionResult res, long time, Profile profile) { @@ -624,7 +643,11 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface if (ex instanceof ActionInitializationException || ex instanceof CommandInitializationException) { comment = getStringResource(R.string.omnipod_driver_error_invalid_parameters); } else if (ex instanceof CommunicationException) { - comment = getStringResource(R.string.omnipod_driver_error_communication_failed); + if (((CommunicationException) ex).getType() == CommunicationException.Type.TIMEOUT) { + comment = getStringResource(R.string.omnipod_driver_error_communication_failed_timeout); + } else { + comment = getStringResource(R.string.omnipod_driver_error_communication_failed_unexpected_exception); + } } else if (ex instanceof CrcMismatchException) { comment = getStringResource(R.string.omnipod_driver_error_crc_mismatch); } else if (ex instanceof IllegalPacketTypeException) { @@ -632,8 +655,14 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } else if (ex instanceof IllegalPodProgressException || ex instanceof IllegalSetupProgressException || ex instanceof IllegalDeliveryStatusException) { comment = getStringResource(R.string.omnipod_driver_error_invalid_progress_state); + } else if (ex instanceof IllegalVersionResponseTypeException) { + comment = getStringResource(R.string.omnipod_driver_error_invalid_response); } else if (ex instanceof IllegalResponseException) { comment = getStringResource(R.string.omnipod_driver_error_invalid_response); + } else if (ex instanceof IllegalMessageSequenceNumberException) { + comment = getStringResource(R.string.omnipod_driver_error_invalid_message_sequence_number); + } else if (ex instanceof IllegalMessageAddressException) { + comment = getStringResource(R.string.omnipod_driver_error_invalid_message_address); } else if (ex instanceof MessageDecodingException) { comment = getStringResource(R.string.omnipod_driver_error_message_decoding_failed); } else if (ex instanceof NonceOutOfSyncException) { @@ -643,9 +672,9 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface } else if (ex instanceof NotEnoughDataException) { comment = getStringResource(R.string.omnipod_driver_error_not_enough_data); } else if (ex instanceof PodFaultException) { - FaultEventType faultEventType = ((PodFaultException) ex).getFaultEvent().getFaultEventType(); - showPodFaultErrorDialog(faultEventType, R.raw.urgentalarm); - comment = createPodFaultErrorMessage(faultEventType); + FaultEventCode faultEventCode = ((PodFaultException) ex).getFaultEvent().getFaultEventCode(); + showPodFaultErrorDialog(faultEventCode, R.raw.urgentalarm); + comment = createPodFaultErrorMessage(faultEventCode); } else if (ex instanceof PodReturnedErrorResponseException) { comment = getStringResource(R.string.omnipod_driver_error_pod_returned_error_response); } else { @@ -661,10 +690,10 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface return comment; } - private String createPodFaultErrorMessage(FaultEventType faultEventType) { + private String createPodFaultErrorMessage(FaultEventCode faultEventCode) { String comment; comment = getStringResource(R.string.omnipod_driver_error_pod_fault, - ByteUtil.convertUnsignedByteToInt(faultEventType.getValue()), faultEventType.name()); + ByteUtil.convertUnsignedByteToInt(faultEventCode.getValue()), faultEventCode.name()); return comment; } @@ -672,17 +701,17 @@ public class AapsOmnipodManager implements OmnipodCommunicationManagerInterface rxBus.send(event); } - private void showPodFaultErrorDialog(FaultEventType faultEventType, Integer sound) { - showErrorDialog(createPodFaultErrorMessage(faultEventType), sound); + private void showPodFaultErrorDialog(FaultEventCode faultEventCode, Integer sound) { + showErrorDialog(createPodFaultErrorMessage(faultEventCode), sound); } 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.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/ui/OmnipodUIPostprocessor.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/driver/ui/OmnipodUIPostprocessor.java index cc5878c27e..d206337384 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 @@ -8,6 +8,7 @@ import java.util.Date; 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.defs.OmnipodPumpPluginInterface; import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; @@ -19,7 +20,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.driver.OmnipodPumpStatus; public class OmnipodUIPostprocessor { - private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); + private static final Logger LOG = LoggerFactory.getLogger(LTag.PUMP.name()); private OmnipodPumpStatus pumpStatus; private OmnipodPumpPluginInterface omnipodPumpPlugin; @@ -102,7 +103,7 @@ public class OmnipodUIPostprocessor { private boolean isLogEnabled() { - return L.isEnabled(L.PUMP); + return L.isEnabled(LTag.PUMP); } public RxBusWrapper getRxBus() { 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 abaaaf737a..908748b991 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 @@ -8,6 +8,8 @@ import android.os.IBinder; import com.google.gson.Gson; +import org.apache.commons.lang3.StringUtils; + import javax.inject.Inject; import info.nightscout.androidaps.R; @@ -17,6 +19,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkCons 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; @@ -86,6 +89,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { public void initRileyLinkServiceData() { rileyLinkServiceData.targetDevice = RileyLinkTargetDevice.Omnipod; + rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod; // get most recently used RileyLink address rileyLinkServiceData.rileylinkAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); @@ -106,7 +110,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { if (sp.contains(OmnipodConst.Prefs.PodState) && omnipodUtil.getPodSessionState() == null) { try { Gson gson = omnipodUtil.getGsonInstance(); - String storedPodState = sp.getString(OmnipodConst.Prefs.PodState, null); + String storedPodState = sp.getString(OmnipodConst.Prefs.PodState, ""); aapsLogger.info(LTag.PUMPCOMM, "PodSessionState-SP: loaded from SharedPreferences: " + storedPodState); podState = gson.fromJson(storedPodState, PodSessionState.class); podState.injectDaggerClass(injector); @@ -120,7 +124,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { this.omnipodCommunicationManager = omnipodCommunicationService; this.aapsOmnipodManager = new AapsOmnipodManager(omnipodCommunicationService, podState, omnipodPumpStatus, - omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin); + omnipodUtil, aapsLogger, rxBus, sp, resourceHelper, injector, activePlugin, this); } else { aapsOmnipodManager = AapsOmnipodManager.getInstance(); } @@ -180,10 +184,10 @@ public class RileyLinkOmnipodService extends RileyLinkService { try { omnipodPumpStatus.errorDescription = "-"; - String rileyLinkAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, null); + String rileyLinkAddress = sp.getString(RileyLinkConst.Prefs.RileyLinkAddress, ""); - if (rileyLinkAddress == null) { - aapsLogger.debug(LTag.PUMPCOMM, "RileyLink address invalid: null"); + if (StringUtils.isEmpty(rileyLinkAddress)) { + aapsLogger.debug(LTag.PUMPCOMM, "RileyLink address invalid: no address"); omnipodPumpStatus.errorDescription = resourceHelper.gs(R.string.medtronic_error_rileylink_address_invalid); return false; } else { @@ -204,6 +208,7 @@ public class RileyLinkOmnipodService extends RileyLinkService { this.omnipodPumpStatus.beepTBREnabled = sp.getBoolean(OmnipodConst.Prefs.BeepTBREnabled, true); this.omnipodPumpStatus.podDebuggingOptionsEnabled = sp.getBoolean(OmnipodConst.Prefs.PodDebuggingOptionsEnabled, false); this.omnipodPumpStatus.timeChangeEventEnabled = sp.getBoolean(OmnipodConst.Prefs.TimeChangeEventEnabled, true); + rileyLinkServiceData.rileyLinkTargetFrequency = RileyLinkTargetFrequency.Omnipod; aapsLogger.debug(LTag.PUMPCOMM, "Beeps [basal={}, bolus={}, SMB={}, TBR={}]", this.omnipodPumpStatus.beepBasalEnabled, this.omnipodPumpStatus.beepBolusEnabled, this.omnipodPumpStatus.beepSMBEnabled, this.omnipodPumpStatus.beepTBREnabled); diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodConst.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodConst.java index f7b78250c3..d12fbd31df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodConst.java +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/util/OmnipodConst.java @@ -14,6 +14,7 @@ public class OmnipodConst { public class Prefs { public static final String PodState = Prefix + "pod_state"; + public static final String NextPodAddress = Prefix + "next_pod_address"; public static final int BeepBasalEnabled = R.string.key_omnipod_beep_basal_enabled; public static final int BeepBolusEnabled = R.string.key_omnipod_beep_bolus_enabled; public static final int BeepSMBEnabled = R.string.key_omnipod_beep_smb_enabled; 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 65d9428ffc..f002989e3c 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 @@ -8,6 +8,7 @@ import com.google.gson.JsonDeserializer; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializer; +import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; @@ -15,14 +16,17 @@ import org.joda.time.format.ISODateTimeFormat; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.android.HasAndroidInjector; 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.logging.LTag; 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.comm.OmnipodManager; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommandType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPodType; import info.nightscout.androidaps.plugins.pump.omnipod.defs.PodDeviceState; @@ -31,6 +35,7 @@ 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.sharedPreferences.SP; /** * Created by andy on 4/8/19. @@ -43,7 +48,8 @@ public class OmnipodUtil { private final RileyLinkUtil rileyLinkUtil; private final OmnipodPumpStatus omnipodPumpStatus; private final ActivePluginProvider activePlugins; - + private final SP sp; + private final HasAndroidInjector injector; private boolean lowLevelDebug = true; private OmnipodCommandType currentCommand; @@ -60,13 +66,17 @@ public class OmnipodUtil { RxBusWrapper rxBus, RileyLinkUtil rileyLinkUtil, OmnipodPumpStatus omnipodPumpStatus, - ActivePluginProvider activePlugins + SP sp, + ActivePluginProvider activePlugins, + HasAndroidInjector injector ) { this.aapsLogger = aapsLogger; this.rxBus = rxBus; this.rileyLinkUtil = rileyLinkUtil; this.omnipodPumpStatus = omnipodPumpStatus; + this.sp = sp; this.activePlugins = activePlugins; + this.injector = injector; } @@ -92,7 +102,6 @@ public class OmnipodUtil { rileyLinkUtil.getRileyLinkHistory().add(new RLHistoryItem(currentCommand)); } - 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); @@ -182,7 +191,6 @@ public class OmnipodUtil { omnipodPumpStatus.pumpType = pumpType_; } - public PumpType getPumpType() { return omnipodPumpStatus.pumpType; } @@ -192,4 +200,49 @@ public class OmnipodUtil { return this.gsonInstance; } + public Integer getNextPodAddress() { + if (sp.contains(OmnipodConst.Prefs.NextPodAddress)) { + int nextPodAddress = sp.getInt(OmnipodConst.Prefs.NextPodAddress, 0); + if (OmnipodManager.isValidAddress(nextPodAddress)) { + return nextPodAddress; + } + } + return null; + } + + public boolean hasNextPodAddress() { + return getNextPodAddress() != null; + } + + public void setNextPodAddress(int address) { + sp.putInt(OmnipodConst.Prefs.NextPodAddress, address); + } + + public void removeNextPodAddress() { + sp.remove(OmnipodConst.Prefs.NextPodAddress); + } + + public AAPSLogger getAapsLogger() { + return this.aapsLogger; + } + + public SP getSp() { + return this.sp; + } + + public PodSessionState loadSessionState() { + String podState = sp.getString(OmnipodConst.Prefs.PodState, ""); + + aapsLogger.info(LTag.PUMP, "PodSessionState-SP: loaded from SharedPreferences: " + podState); + + if (StringUtils.isNotEmpty(podState)) { + PodSessionState podSessionState = gsonInstance.fromJson(podState, PodSessionState.class); + podSessionState.injectDaggerClass(injector); + setPodSessionState(podSessionState); + + return podSessionState; + } + + return null; + } } 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 new file mode 100644 index 0000000000..d4f8e8dc85 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/OmnipodDashPumpPlugin.java @@ -0,0 +1,317 @@ +package info.nightscout.androidaps.plugins.pump.omnipod_dash; + +import android.content.Context; +import android.os.Bundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.Arrays; +import java.util.List; + +import javax.inject.Inject; + +import dagger.android.HasAndroidInjector; +import info.nightscout.androidaps.BuildConfig; +import info.nightscout.androidaps.R; +import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.interfaces.ActivePluginProvider; +import info.nightscout.androidaps.interfaces.CommandQueueProvider; +import info.nightscout.androidaps.interfaces.PluginDescription; +import info.nightscout.androidaps.interfaces.PluginType; +import info.nightscout.androidaps.logging.AAPSLogger; +import info.nightscout.androidaps.logging.L; +import info.nightscout.androidaps.logging.LTag; +import info.nightscout.androidaps.plugins.bus.RxBusWrapper; +import info.nightscout.androidaps.plugins.general.actions.defs.CustomAction; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpDriverState; +import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; +import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodFragment; +import info.nightscout.androidaps.plugins.pump.omnipod.OmnipodPumpPlugin; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodPumpPluginInterface; +import info.nightscout.androidaps.plugins.pump.omnipod.events.EventOmnipodPumpValuesChanged; +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; +import info.nightscout.androidaps.utils.sharedPreferences.SP; + +/** + * Created by andy on 23.04.18. + * + * @author Andy Rozman (andy.rozman@gmail.com) + */ +// FIXME this is just placeholder for now, but this should use most of OmnipodPumpPlugin implementation +public class OmnipodDashPumpPlugin extends OmnipodPumpPlugin implements OmnipodPumpPluginInterface { + + // TODO Dagger + //private static final Logger LOG = LoggerFactory.getLogger(L.PUMP); + + protected static OmnipodDashPumpPlugin plugin = null; + //private RileyLinkOmnipodService omnipodService; + //private OmnipodPumpStatus pumpStatusLocal = null; + + // variables for handling statuses and history + private boolean firstRun = true; + private boolean isRefresh = false; + private boolean isBasalProfileInvalid = false; + private boolean basalProfileChanged = false; + private boolean isInitialized = false; + + public static boolean isBusy = false; + //private List busyTimestamps = new ArrayList<>(); + //private boolean sentIdToFirebase = false; + //private boolean hasTimeDateOrTimeZoneChanged = false; + + private Profile currentProfile; + + //@Inject + public OmnipodDashPumpPlugin(HasAndroidInjector injector, + AAPSLogger aapsLogger, + RxBusWrapper rxBus, + Context context, + ResourceHelper resourceHelper, + ActivePluginProvider activePlugin, + SP sp, + CommandQueueProvider commandQueue, + FabricPrivacy fabricPrivacy, + DateUtil dateUtil + ) { + super(new PluginDescription() // + .mainType(PluginType.PUMP) // + .fragmentClass(OmnipodFragment.class.getName()) // + .pluginName(R.string.omnipod_dash_name) // + .shortName(R.string.omnipod_dash_name_short) // + .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, dateUtil + ); + + displayConnectionMessages = false; + + //OmnipodUtil.setOmnipodPodType(OmnipodPodType.Dash); + + if (omnipodCommunicationManager == null) { + omnipodCommunicationManager = OmnipodDashCommunicationManager.getInstance(); + } + + // DG omnipodUIComm = new OmnipodUIComm(omnipodCommunicationManager, this, this.omnipodPumpStatus); + + //OmnipodUtil.setPlugin(this); + + // FIXME +// serviceConnection = new ServiceConnection() { +// +// public void onServiceDisconnected(ComponentName name) { +// if (isLoggingEnabled()) +// aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is disconnected"); +// omnipodService = null; +// } +// +// public void onServiceConnected(ComponentName name, IBinder service) { +// if (isLoggingEnabled()) +// aapsLogger.debug(LTag.PUMP, "RileyLinkOmnipodService is connected"); +// RileyLinkOmnipodService.LocalBinder mLocalBinder = (RileyLinkOmnipodService.LocalBinder) service; +// omnipodService = mLocalBinder.getServiceInstance(); +// +// new Thread(() -> { +// +// for (int i = 0; i < 20; i++) { +// SystemClock.sleep(5000); +// +// if (OmnipodUtil.getPumpStatus() != null) { +// if (isLoggingEnabled()) +// aapsLogger.debug(LTag.PUMP, "Starting OmniPod-RileyLink service"); +// if (OmnipodUtil.getPumpStatus().setNotInPreInit()) { +// break; +// } +// } +// } +// }).start(); +// } +// }; + } + + @Deprecated + public static OmnipodDashPumpPlugin getPlugin() { + if (plugin == null) + throw new IllegalStateException("Plugin not injected jet"); + return plugin; + } + + + private String getLogPrefix() { + return "OmnipodPlugin::"; + } + + + // FIXME + public Class getServiceClass() { + return RileyLinkOmnipodService.class; + } + + + @Override + public String deviceID() { + return "Omnipod Dash"; + } + + + // Pump Plugin + + private boolean isServiceSet() { + return true; //omnipodService != null; + } + + private boolean isServiceInitialized() { + return true; + } + + + @Override + public boolean isInitialized() { + if (displayConnectionMessages) + aapsLogger.debug(LTag.PUMP, getLogPrefix() + "isInitialized"); + return isServiceSet() && isInitialized; + } + + + @Override + public boolean isConnected() { + if (displayConnectionMessages) + aapsLogger.debug(LTag.PUMP, getLogPrefix() + "isConnected"); + return isServiceSet() && isServiceInitialized(); + } + + + @Override + public boolean isConnecting() { + if (displayConnectionMessages) + aapsLogger.debug(LTag.PUMP, getLogPrefix() + "isConnecting"); + return !isServiceSet() || !isServiceInitialized(); + } + + + @Override + public void getPumpStatus() { + + if (firstRun) { + initializePump(!isRefresh); + } + +// getPodPumpStatus(); +// +// if (firstRun) { +// initializePump(!isRefresh); +// } else { +// refreshAnyStatusThatNeedsToBeRefreshed(); +// } +// +// MainApp.bus().post(new EventMedtronicPumpValuesChanged()); + } + + + public void resetStatusState() { + firstRun = true; + isRefresh = true; + } + + + private void setRefreshButtonEnabled(boolean enabled) { + rxBus.send(new EventOmnipodRefreshButtonState(enabled)); + } + + + private void initializePump(boolean realInit) { + + aapsLogger.info(LTag.PUMP, getLogPrefix() + "initializePump - start"); + + if (omnipodCommunicationManager == null) { + omnipodCommunicationManager = OmnipodDashCommunicationManager.getInstance(); + } + +// setRefreshButtonEnabled(false); +// +// getPodPumpStatus(); +// +// if (isRefresh) { +// if (isPumpNotReachable()) { +// if (isLoggingEnabled()) +// LOG.error(getLogPrefix() + "initializePump::Pump unreachable."); +// MedtronicUtil.sendNotification(MedtronicNotificationType.PumpUnreachable); +// +// setRefreshButtonEnabled(true); +// +// return; +// } +// +// MedtronicUtil.dismissNotification(MedtronicNotificationType.PumpUnreachable); +// } +// +// this.pumpState = PumpDriverState.Connected; +// +// pumpStatusLocal.setLastCommunicationToNow(); +// setRefreshButtonEnabled(true); + + // TODO need to read status and BasalProfile if pod inited and pod status and set correct commands enabled + + if (!isRefresh) { + pumpState = PumpDriverState.Initialized; + } + + if (!sentIdToFirebase) { + Bundle params = new Bundle(); + params.putString("version", BuildConfig.VERSION); + //fabricPrivacy.logCustom().logEvent("OmnipodPumpInit", params); + + sentIdToFirebase = true; + } + + isInitialized = true; + // this.pumpState = PumpDriverState.Initialized; + + this.firstRun = false; + } + + + protected void triggerUIChange() { + rxBus.send(new EventOmnipodPumpValuesChanged()); + } + + + // OPERATIONS not supported by Pump or Plugin + + //private List customActions = null; + + + @Override + public List getCustomActions() { + + if (customActions == null) { + this.customActions = Arrays.asList( +// customActionPairAndPrime, // +// customActionFillCanullaSetBasalProfile, // +// customActionDeactivatePod, // +// customActionResetPod + ); + } + + return this.customActions; + } + + + @Override + public void timezoneOrDSTChanged(TimeChangeType timeChangeType) { + +// if (isLoggingEnabled()) +// LOG.warn(getLogPrefix() + "Time, Date and/or TimeZone changed. "); +// +// this.hasTimeDateOrTimeZoneChanged = true; + } + + +} 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 new file mode 100644 index 0000000000..39ccadd308 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/comm/OmnipodDashCommunicationManager.java @@ -0,0 +1,125 @@ +package info.nightscout.androidaps.plugins.pump.omnipod_dash.comm; + +import android.content.Context; + +import info.nightscout.androidaps.data.DetailedBolusInfo; +import info.nightscout.androidaps.data.Profile; +import info.nightscout.androidaps.data.PumpEnactResult; +import info.nightscout.androidaps.plugins.pump.common.data.TempBasalPair; +import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.RFSpy; +import info.nightscout.androidaps.plugins.pump.omnipod.comm.message.response.podinfo.PodInfoRecentPulseLog; +import info.nightscout.androidaps.plugins.pump.omnipod.defs.OmnipodCommunicationManagerInterface; +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.PodSessionState; +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; + + + public OmnipodDashCommunicationManager(Context context, RFSpy rfspy) { + omnipodCommunicationManager = this; +// OmnipodUtil.getPumpStatus().previousConnection = SP.getLong( +// RileyLinkConst.Prefs.LastGoodDeviceCommunicationTime, 0L); + } + + private PodSessionState getPodSessionState() { + return null; + } + + @Deprecated + public static OmnipodDashCommunicationManager getInstance() { + return omnipodCommunicationManager; + } + + //@Override + protected void configurePumpSpecificSettings() { + //pumpStatus = OmnipodUtil.getPumpStatus(); + } + + public String getErrorResponse() { + return this.errorMessage; + } + +// private boolean isLogEnabled() { +// return L.isEnabled(L.PUMPCOMM); +// } + + @Override + public PumpEnactResult initPod(PodInitActionType podInitActionType, PodInitReceiver podInitReceiver, Profile profile) { + return null; + } + + @Override + public PumpEnactResult getPodStatus() { + return null; + } + + @Override + public PumpEnactResult deactivatePod(PodInitReceiver podInitReceiver) { + return null; + } + + @Override + public PumpEnactResult setBasalProfile(Profile profile) { + return null; + } + + @Override + public PumpEnactResult resetPodStatus() { + return null; + } + + @Override + public PumpEnactResult setBolus(DetailedBolusInfo detailedBolusInfo) { + return null; + } + + public PumpEnactResult setBolus(Double parameter, boolean isSmb) { + return null; + } + + @Override + public PumpEnactResult cancelBolus() { + return null; + } + + @Override + public PumpEnactResult setTemporaryBasal(TempBasalPair tbr) { + return null; + } + + @Override + public PumpEnactResult cancelTemporaryBasal() { + return null; + } + + @Override + public PumpEnactResult acknowledgeAlerts() { + return null; + } + + @Override + public PumpEnactResult setTime() { + return null; + } + + @Override + public PodInfoRecentPulseLog readPulseLog() { + return null; + } + +} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/driver/OmnipodDashPumpStatus.java b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/driver/OmnipodDashPumpStatus.java new file mode 100644 index 0000000000..617322af00 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod_dash/driver/OmnipodDashPumpStatus.java @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.plugins.pump.omnipod_dash.driver; + +import javax.inject.Inject; +import javax.inject.Singleton; + +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.omnipod.driver.OmnipodPumpStatus; +import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.utils.sharedPreferences.SP; + +@Singleton +public class OmnipodDashPumpStatus extends OmnipodPumpStatus { + + @Inject + public OmnipodDashPumpStatus(ResourceHelper resourceHelper, + SP sp, + RxBusWrapper rxBus, + RileyLinkUtil rileyLinkUtil) { + super(resourceHelper, sp, rxBus, rileyLinkUtil); + this.pumpType = PumpType.Insulet_Omnipod_Dash; + } +} 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..3db377a230 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 @@ -17,7 +17,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,14 +51,16 @@ 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 @@ -131,7 +133,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? @@ -355,13 +357,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..ced1bcd888 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 @@ -25,7 +25,7 @@ abstract class AbstractSensitivityPlugin( 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 { 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..fc527bab94 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; @@ -37,7 +38,7 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { private SP sp; private ProfileFunction profileFunction; - private ResourceHelper resourceHelper; + private DateUtil dateUtil; @Inject public SensitivityAAPSPlugin( @@ -45,7 +46,8 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { AAPSLogger aapsLogger, ResourceHelper resourceHelper, SP sp, - ProfileFunction profileFunction + ProfileFunction profileFunction, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.SENSITIVITY) @@ -57,17 +59,18 @@ public class SensitivityAAPSPlugin extends AbstractSensitivityPlugin { ); 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, ""); 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); Profile profile = profileFunction.getProfile(); @@ -84,7 +87,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 +118,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 +174,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..5740c7a5d1 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 @@ -15,14 +15,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 +35,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 +44,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 +58,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) { + 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 +82,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 +92,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,7 +117,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { int hoursegment = 0; //hoursegment = 0 = 8 hour //hoursegment = 1 = 24 hour - while (hoursegment < deviationsHour.size()){ + while (hoursegment < deviationsHour.size()) { ArrayList deviationsArray = deviationsHour.get(hoursegment); String pastSensitivity = pastSensitivityArray.get(hoursegment); @@ -124,7 +128,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)"; } @@ -143,7 +147,7 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { for (int i = 0; i < autosensData.extraDeviation.size(); i++) deviationsArray.add(autosensData.extraDeviation.get(i)); - if (deviationsArray.size() > deviationCategory.get(hoursegment)){ + if (deviationsArray.size() > deviationCategory.get(hoursegment)) { deviationsArray.remove(0); } @@ -155,11 +159,11 @@ 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 @@ -167,26 +171,27 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { for (int i = 0; i < deviationsHour.size(); i++) { ArrayList deviations = deviationsHour.get(i); - getAapsLogger().debug(LTag.AUTOSENS,"Using most recent " + deviations.size() + " deviations"); + 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){ + if (hourused == 1) { senstime = "(24 hours) "; sensResult = senstime; } @@ -198,7 +203,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); @@ -208,38 +213,38 @@ public class SensitivityOref1Plugin extends AbstractSensitivityPlugin { if (pSensitive < 0) { // sensitive basalOff = pSensitive * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); - sensResult+= "Excess insulin sensitivity detected"; + sensResult += "Excess insulin sensitivity detected"; } else if (pResistant > 0) { // resistant basalOff = pResistant * (60 / 5) / Profile.toMgdl(sens, profile.getUnits()); - sensResult+= "Excess insulin resistance detected"; + 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..b01ba8d470 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 @@ -12,15 +12,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 +33,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 +84,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.text = bgReading.directionToSymbol(databaseHelper) holder.remove.tag = bgReading } @@ -103,7 +106,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/EversensePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/EversensePlugin.kt index 49e6ddbab8..6b0021fbcf 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 @@ -12,8 +12,6 @@ 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.L -import info.nightscout.androidaps.logging.L.isEnabled import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.DateUtil @@ -30,7 +28,8 @@ class EversensePlugin @Inject constructor( injector: HasAndroidInjector, private val sp: SP, resourceHelper: ResourceHelper, - aapsLogger: AAPSLogger + aapsLogger: AAPSLogger, + private val dateUtil: DateUtil ) : PluginBase(PluginDescription() .mainType(PluginType.BGSOURCE) .fragmentClass(BGSourceFragment::class.java.name) @@ -48,33 +47,29 @@ class EversensePlugin @Inject constructor( override fun handleNewData(intent: Intent) { if (!isEnabled(PluginType.BGSOURCE)) return val bundle = intent.extras ?: return - if (isEnabled(L.BGSOURCE)) { - if (bundle.containsKey("currentCalibrationPhase")) aapsLogger.debug(LTag.BGSOURCE, "currentCalibrationPhase: " + bundle.getString("currentCalibrationPhase")) - 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("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")) - if (bundle.containsKey("isXLVersion")) aapsLogger.debug(LTag.BGSOURCE, "isXLVersion: " + bundle.getBoolean("isXLVersion")) - 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("transmitterVersionNumber")) aapsLogger.debug(LTag.BGSOURCE, "transmitterVersionNumber: " + bundle.getString("transmitterVersionNumber")) - if (bundle.containsKey("transmitterConnectionState")) aapsLogger.debug(LTag.BGSOURCE, "transmitterConnectionState: " + bundle.getString("transmitterConnectionState")) - } + if (bundle.containsKey("currentCalibrationPhase")) aapsLogger.debug(LTag.BGSOURCE, "currentCalibrationPhase: " + bundle.getString("currentCalibrationPhase")) + 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("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")) + if (bundle.containsKey("isXLVersion")) aapsLogger.debug(LTag.BGSOURCE, "isXLVersion: " + bundle.getBoolean("isXLVersion")) + 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("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")) { val glucoseLevels = bundle.getIntArray("glucoseLevels") val glucoseRecordNumbers = bundle.getIntArray("glucoseRecordNumbers") val glucoseTimestamps = bundle.getLongArray("glucoseTimestamps") if (glucoseLevels != null && glucoseRecordNumbers != null && glucoseTimestamps != null) { - if (isEnabled(L.BGSOURCE)) { - aapsLogger.debug(LTag.BGSOURCE, "glucoseLevels" + Arrays.toString(glucoseLevels)) - aapsLogger.debug(LTag.BGSOURCE, "glucoseRecordNumbers" + Arrays.toString(glucoseRecordNumbers)) - aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamps" + Arrays.toString(glucoseTimestamps)) - } + aapsLogger.debug(LTag.BGSOURCE, "glucoseLevels" + Arrays.toString(glucoseLevels)) + aapsLogger.debug(LTag.BGSOURCE, "glucoseRecordNumbers" + Arrays.toString(glucoseRecordNumbers)) + aapsLogger.debug(LTag.BGSOURCE, "glucoseTimestamps" + Arrays.toString(glucoseTimestamps)) for (i in glucoseLevels.indices) { val bgReading = BgReading() bgReading.value = glucoseLevels[i].toDouble() @@ -95,11 +90,9 @@ class EversensePlugin @Inject constructor( val calibrationTimestamps = bundle.getLongArray("calibrationTimestamps") val calibrationRecordNumbers = bundle.getLongArray("calibrationRecordNumbers") if (calibrationGlucoseLevels != null && calibrationTimestamps != null && calibrationRecordNumbers != null) { - if (isEnabled(L.BGSOURCE)) { - aapsLogger.debug(LTag.BGSOURCE, "calibrationGlucoseLevels" + Arrays.toString(calibrationGlucoseLevels)) - aapsLogger.debug(LTag.BGSOURCE, "calibrationTimestamps" + Arrays.toString(calibrationTimestamps)) - aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers)) - } + aapsLogger.debug(LTag.BGSOURCE, "calibrationGlucoseLevels" + Arrays.toString(calibrationGlucoseLevels)) + aapsLogger.debug(LTag.BGSOURCE, "calibrationTimestamps" + Arrays.toString(calibrationTimestamps)) + aapsLogger.debug(LTag.BGSOURCE, "calibrationRecordNumbers" + Arrays.toString(calibrationRecordNumbers)) for (i in calibrationGlucoseLevels.indices) { try { if (MainApp.getDbHelper().getCareportalEventFromTimestamp(calibrationTimestamps[i]) == null) { 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..daf570edc2 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 @@ -70,7 +70,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/treatments/TreatmentService.java b/app/src/main/java/info/nightscout/androidaps/plugins/treatments/TreatmentService.java index cd81621252..f43ece03d8 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,6 +33,7 @@ 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; 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..f83e522b30 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 @@ -31,7 +31,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 +51,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; @@ -75,6 +76,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface private final ProfileFunction profileFunction; private final ActivePluginProvider activePlugin; private final FabricPrivacy fabricPrivacy; + private final DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -99,7 +101,8 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface SP sp, ProfileFunction profileFunction, ActivePluginProvider activePlugin, - FabricPrivacy fabricPrivacy + FabricPrivacy fabricPrivacy, + DateUtil dateUtil ) { super(new PluginDescription() .mainType(PluginType.TREATMENT) @@ -118,6 +121,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface this.profileFunction = profileFunction; this.activePlugin = activePlugin; this.fabricPrivacy = fabricPrivacy; + this.dateUtil = dateUtil; } @Override @@ -338,7 +342,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface last = t.date; } } - getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + DateUtil.dateAndTimeString(last)); + getAapsLogger().debug(LTag.DATATREATMENTS, "Last bolus time: " + dateUtil.dateAndTimeString(last)); return last; } @@ -353,7 +357,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface last = t.date; } } - getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + DateUtil.dateAndTimeString(last)); + getAapsLogger().debug(LTag.DATATREATMENTS, "Last manual bolus time: " + dateUtil.dateAndTimeString(last)); return last; } @@ -642,7 +646,7 @@ public class TreatmentsPlugin extends PluginBase implements TreatmentsInterface 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); 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 a6b1cdf296..63574ea8d2 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,7 @@ class TreatmentsBolusFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var treatmentsPlugin: TreatmentsPlugin @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -109,7 +110,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) @@ -145,12 +146,10 @@ class TreatmentsBolusFragment : DaggerFragment() { init { calculation.setOnClickListener { val treatment = it.tag as Treatment - fragmentManager?.let { fragmentManager -> - if (treatment.getBoluscalc() != null) { - val wizardDialog = WizardInfoDialog() - wizardDialog.setData(treatment.getBoluscalc()!!) - wizardDialog.show(fragmentManager, "WizardInfoDialog") - } + if (treatment.getBoluscalc() != null) { + val wizardDialog = WizardInfoDialog() + wizardDialog.setData(treatment.getBoluscalc()!!) + wizardDialog.show(childFragmentManager, "WizardInfoDialog") } } calculation.paintFlags = calculation.paintFlags or Paint.UNDERLINE_TEXT_FLAG @@ -160,7 +159,7 @@ 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 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..9307238211 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,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var translator: Translator + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -106,7 +107,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) @@ -132,7 +133,7 @@ class TreatmentsCareportalFragment : DaggerFragment() { activity?.let { activity -> val text = resourceHelper.gs(R.string.careportal_newnstreatment_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) 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..d2dcd632ea 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 @@ -40,6 +40,7 @@ class TreatmentsExtendedBolusesFragment : DaggerFragment() { @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -63,7 +64,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,8 +73,8 @@ 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()) holder.duration.text = resourceHelper.gs(R.string.format_mins, extendedBolus.durationInMinutes) holder.insulin.text = resourceHelper.gs(R.string.formatinsulinunits, extendedBolus.insulin) @@ -112,7 +113,7 @@ 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) 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 10bdf42de5..77934e304c 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 @@ -43,6 +43,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { @Inject lateinit var localProfilePlugin: LocalProfilePlugin @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -95,7 +96,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 { @@ -132,7 +133,7 @@ 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) @@ -141,10 +142,10 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { } 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.SingleProfile().copyFrom(localProfilePlugin.rawProfile, nonCustomized, profileSwitch.customizedName + " " + dateUtil.dateAndTimeString(profileSwitch.date).replace(".", "_"))) rxBus.send(EventLocalProfileChanged()) } }) @@ -156,7 +157,7 @@ class TreatmentsProfileSwitchFragment : DaggerFragment() { args.putInt("mode", ProfileViewerDialog.Mode.RUNNING_PROFILE.ordinal) val pvd = ProfileViewerDialog() pvd.arguments = args - fragmentManager?.let { pvd.show(it, "ProfileViewDialog") } + 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..7df7db72be 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; @@ -48,6 +48,7 @@ public class TreatmentsTempTargetFragment extends DaggerFragment { @Inject ProfileFunction profileFunction; @Inject ResourceHelper resourceHelper; @Inject FabricPrivacy fabricPrivacy; + @Inject DateUtil dateUtil; private CompositeDisposable disposable = new CompositeDisposable(); @@ -77,13 +78,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,7 +142,7 @@ 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)) { 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..4ff6b15950 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,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var dateUtil: DateUtil override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { @@ -88,7 +89,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 +101,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) @@ -160,7 +161,7 @@ class TreatmentsTemporaryBasalsFragment : DaggerFragment() { 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.date)}: ${dateUtil.dateAndTimeString(tempBasal.date)} """.trimIndent(), DialogInterface.OnClickListener { _: DialogInterface?, _: Int -> val id = tempBasal._id 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..15f1eaa9f8 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 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..a3dda44325 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveReceiver.kt @@ -16,7 +16,7 @@ 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.interfaces.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,7 +38,8 @@ 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 dateUtil: DateUtil companion object { private val KEEP_ALIVE_MILLISECONDS = T.mins(5).msecs() @@ -100,8 +101,8 @@ 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 @@ -117,7 +118,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/setupwizard/SWDefinition.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt index 5fca6651da..c8e406881b 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 @@ -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) @@ -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/elements/SWEditNumberWithUnits.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWEditNumberWithUnits.kt index 80ed784fff..978455a4ae 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,7 +9,7 @@ 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.SafeParse diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt new file mode 100644 index 0000000000..b2243d3336 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinButtonsOn.kt @@ -0,0 +1,20 @@ +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 SkinButtonsOn @Inject constructor(private val config: Config) : SkinInterface { + + override val description: Int get() = R.string.buttonson_desrciption + + 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 + else -> R.layout.overview_fragment + } + +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt new file mode 100644 index 0000000000..deef2440f3 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinClassic.kt @@ -0,0 +1,21 @@ +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 SkinClassic @Inject constructor(private val config: Config): SkinInterface { + + override val description: Int get() = R.string.classic_desrciption + + 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/skins/SkinInterface.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt new file mode 100644 index 0000000000..6a9d055a13 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinInterface.kt @@ -0,0 +1,10 @@ +package info.nightscout.androidaps.skins + +import androidx.annotation.LayoutRes +import androidx.annotation.StringRes + +interface SkinInterface { + @get:StringRes val description : Int + + @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/SkinListPreference.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinListPreference.kt new file mode 100644 index 0000000000..977f19c268 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinListPreference.kt @@ -0,0 +1,29 @@ +package info.nightscout.androidaps.skins + +import android.content.Context +import android.util.AttributeSet +import androidx.preference.ListPreference +import dagger.android.HasAndroidInjector +import java.util.* +import javax.inject.Inject + +class SkinListPreference(context: Context, attrs: AttributeSet?) + : ListPreference(context, attrs) { + + @Inject lateinit var skinProvider: SkinProvider + + constructor(context: Context) : this(context, null) + + init { + (context.applicationContext as HasAndroidInjector).androidInjector().inject(this) + val entries = Vector() + val values = Vector() + + for (skin in skinProvider.list) { + values.addElement(skin.javaClass.name) + entries.addElement(context.getString(skin.description)) + } + entryValues = values.toTypedArray() + setEntries(entries.toTypedArray()) + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/skins/SkinProvider.kt b/app/src/main/java/info/nightscout/androidaps/skins/SkinProvider.kt new file mode 100644 index 0000000000..5ea6a97501 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/skins/SkinProvider.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.skins + +import info.nightscout.androidaps.R +import info.nightscout.androidaps.dependencyInjection.SkinsModule +import info.nightscout.androidaps.utils.sharedPreferences.SP +import okhttp3.internal.toImmutableMap +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class SkinProvider @Inject constructor( + val sp: SP, + @SkinsModule.Skin val allSkins: Map<@JvmSuppressWildcards Int, @JvmSuppressWildcards SkinInterface> +) { + + fun activeSkin(): SkinInterface = + list.firstOrNull { it.javaClass.name == sp.getString(R.string.key_skin, "") } + ?: list.first() + + val list: List + get() = allSkins.toImmutableMap().toList().sortedBy { it.first }.map { it.second } +} \ No newline at end of file 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 070c1b0c51..eff444aa6e 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,9 @@ 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 dateUtil: DateUtil ) { fun missedReadingsThreshold(): Long { @@ -43,9 +45,9 @@ class LocalAlertUtils @Inject constructor( fun checkPumpUnreachableAlarm(lastConnection: Long, isStatusOutdated: Boolean, isDisconnected: Boolean) { val alarmTimeoutExpired = lastConnection + pumpUnreachableThreshold() < System.currentTimeMillis() 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()) diff --git a/app/src/main/java/info/nightscout/androidaps/utils/SP.java b/app/src/main/java/info/nightscout/androidaps/utils/SP.java index 08ad3a8693..a6124acf10 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SP.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SP.java @@ -19,26 +19,6 @@ public class SP { return sharedPreferences.getAll(); } - @Deprecated - static public void clear() { - sharedPreferences.edit().clear().apply(); - } - - @Deprecated - static public boolean contains(String key) { - return sharedPreferences.contains(key); - } - - @Deprecated - static public boolean contains(int resourceId) { - return sharedPreferences.contains(MainApp.gs(resourceId)); - } - - @Deprecated - static public String getString(int resourceID, String defaultValue) { - return sharedPreferences.getString(MainApp.gs(resourceID), defaultValue); - } - @Deprecated static public String getString(String key, String defaultValue) { return sharedPreferences.getString(key, defaultValue); @@ -53,102 +33,6 @@ public class SP { } } - @Deprecated - static public boolean getBoolean(String key, Boolean defaultValue) { - try { - return sharedPreferences.getBoolean(key, defaultValue); - } catch (Exception e) { - return defaultValue; - } - } - - @Deprecated - static public Double getDouble(int resourceID, Double defaultValue) { - return SafeParse.stringToDouble(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())); - } - - @Deprecated - static public Double getDouble(String key, Double defaultValue) { - return SafeParse.stringToDouble(sharedPreferences.getString(key, defaultValue.toString())); - } - - @Deprecated - static public int getInt(int resourceID, Integer defaultValue) { - try { - return sharedPreferences.getInt(MainApp.gs(resourceID), defaultValue); - } catch (Exception e) { - return SafeParse.stringToInt(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())); - } - } - - @Deprecated - static public int getInt(String key, Integer defaultValue) { - try { - return sharedPreferences.getInt(key, defaultValue); - } catch (Exception e) { - return SafeParse.stringToInt(sharedPreferences.getString(key, defaultValue.toString())); - } - } - - @Deprecated - static public long getLong(int resourceID, Long defaultValue) { - try { - return sharedPreferences.getLong(MainApp.gs(resourceID), defaultValue); - } catch (Exception e) { - return SafeParse.stringToLong(sharedPreferences.getString(MainApp.gs(resourceID), defaultValue.toString())); - } - } - - @Deprecated - static public long getLong(String key, Long defaultValue) { - try { - return sharedPreferences.getLong(key, defaultValue); - } catch (Exception e) { - return SafeParse.stringToLong(sharedPreferences.getString(key, defaultValue.toString())); - } - } - - @Deprecated - static public void putBoolean(String key, boolean value) { - sharedPreferences.edit().putBoolean(key, value).apply(); - } - - @Deprecated - static public void putBoolean(int resourceID, boolean value) { - sharedPreferences.edit().putBoolean(MainApp.gs(resourceID), value).apply(); - } - - @Deprecated - static public void putDouble(String key, double value) { - sharedPreferences.edit().putString(key, Double.toString(value)).apply(); - } - - @Deprecated - static public void putLong(String key, long value) { - sharedPreferences.edit().putLong(key, value).apply(); - } - - @Deprecated - static public void putLong(int resourceID, long value) { - sharedPreferences.edit().putLong(MainApp.gs(resourceID), value).apply(); - } - - @Deprecated - static public void putInt(String key, int value) { - sharedPreferences.edit().putInt(key, value).apply(); - } - - @Deprecated - static public void putInt(int resourceID, int value) { - sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply(); - } - - @Deprecated - static public void incInt(int resourceID) { - int value = getInt(resourceID, 0) + 1; - sharedPreferences.edit().putInt(MainApp.gs(resourceID), value).apply(); - } - @Deprecated static public void putString(int resourceID, String value) { sharedPreferences.edit().putString(MainApp.gs(resourceID), value).apply(); @@ -159,11 +43,6 @@ public class SP { sharedPreferences.edit().putString(key, value).apply(); } - @Deprecated - static public void remove(int resourceID) { - sharedPreferences.edit().remove(MainApp.gs(resourceID)).apply(); - } - @Deprecated static public void remove(String key) { sharedPreferences.edit().remove(key).apply(); 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 2c28d3e212..0bfa1cbd0d 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/SntpClient.java @@ -18,13 +18,16 @@ package info.nightscout.androidaps.utils; import android.os.SystemClock; import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; -import info.nightscout.androidaps.logging.L; +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; /** @@ -39,31 +42,42 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; * } * */ +@Singleton public class SntpClient { - private static Logger log = StacktraceLoggerWrapper.getLogger(L.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; @@ -71,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(); @@ -80,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(); } @@ -95,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); @@ -145,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; } @@ -157,7 +171,7 @@ public class SntpClient { * * @return time value computed from NTP server response. */ - private static long getNtpTime() { + private long getNtpTime() { return mNtpTime; } @@ -167,7 +181,7 @@ public class SntpClient { * * @return reference clock corresponding to the NTP time. */ - private static long getNtpTimeReference() { + private long getNtpTimeReference() { return mNtpTimeReference; } @@ -183,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]; @@ -202,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); @@ -212,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..3386dd9235 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java +++ b/app/src/main/java/info/nightscout/androidaps/utils/TimeListEdit.java @@ -29,6 +29,7 @@ import java.util.List; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.logging.AAPSLogger; import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; /** @@ -36,7 +37,8 @@ import info.nightscout.androidaps.logging.StacktraceLoggerWrapper; */ 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 +67,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; @@ -281,7 +289,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 +319,7 @@ public class TimeListEdit { return time; } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } return 0; } @@ -323,7 +331,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 +344,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 +370,7 @@ public class TimeListEdit { data2.put(index, newObject2); } } catch (JSONException e) { - log.error("Unhandled exception", e); + aapsLogger.error("Unhandled exception", e); } } @@ -383,7 +391,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 +404,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 9ec04d59d7..6ee23a85f5 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.utils.resources.IconsProvider import info.nightscout.androidaps.utils.resources.ResourceHelper import javax.inject.Inject import javax.inject.Singleton @@ -17,7 +18,8 @@ import javax.inject.Singleton @Singleton class NotificationHolder @Inject constructor( private val resourceHelper: ResourceHelper, - private val context: Context + private val context: Context, + private val iconsProvider: IconsProvider ) { val channelID = "AndroidAPS-Ongoing" @@ -32,8 +34,8 @@ class NotificationHolder @Inject constructor( .setOngoing(true) .setOnlyAlertOnce(true) .setCategory(NotificationCompat.CATEGORY_STATUS) - .setSmallIcon(resourceHelper.getNotificationIcon()) - .setLargeIcon(resourceHelper.decodeResource(resourceHelper.getIcon())) + .setSmallIcon(iconsProvider.getNotificationIcon()) + .setLargeIcon(resourceHelper.decodeResource(iconsProvider.getIcon())) .setContentTitle(resourceHelper.gs(R.string.loading)) .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)) notification = builder.build() 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 new file mode 100644 index 0000000000..6bdeaa73a8 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/utils/resources/IconsProvider.kt @@ -0,0 +1,24 @@ +package info.nightscout.androidaps.utils.resources + +import info.nightscout.androidaps.Config +import info.nightscout.androidaps.R +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class IconsProvider @Inject constructor(private val config: Config) { + + fun getIcon(): Int = + when { + 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 + 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..6ee3024fc6 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,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.treatments.TreatmentService import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin import info.nightscout.androidaps.utils.DateUtil @@ -31,8 +31,9 @@ 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, + private val dateUtil: DateUtil +) : TreatmentsPlugin(injector, aapsLogger, rxBus, resourceHelper, mainApp, sp, profileFunction, activePlugin, fabricPrivacy, dateUtil) { init { service = TreatmentService(injector) // plugin is not started @@ -99,7 +100,7 @@ class TddCalculator @Inject constructor( private fun toText(tdds: LongSparseArray): String { var t = "" for (i in 0 until tdds.size()) { - t += "${tdds.valueAt(i).toText(resourceHelper)}
" + t += "${tdds.valueAt(i).toText(resourceHelper, dateUtil)}
" } 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..fffa175e07 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 @@ -19,7 +19,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 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/res/drawable-hdpi/bad.png b/app/src/main/res/drawable-hdpi/bad.png new file mode 100644 index 0000000000..139bf1ddee Binary files /dev/null and b/app/src/main/res/drawable-hdpi/bad.png differ diff --git a/app/src/main/res/drawable-hdpi/good.png b/app/src/main/res/drawable-hdpi/good.png new file mode 100644 index 0000000000..05723ff4ea Binary files /dev/null and b/app/src/main/res/drawable-hdpi/good.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_closed.png b/app/src/main/res/drawable-hdpi/loop_closed.png new file mode 100644 index 0000000000..066dd4c26a Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_closed.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_disabled.png b/app/src/main/res/drawable-hdpi/loop_disabled.png new file mode 100644 index 0000000000..268a9bc76b Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_disabled.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_disconnected.png b/app/src/main/res/drawable-hdpi/loop_disconnected.png new file mode 100644 index 0000000000..bfff44ea1e Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_disconnected.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_lgs.png b/app/src/main/res/drawable-hdpi/loop_lgs.png new file mode 100644 index 0000000000..e45fda615b Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_lgs.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_open.png b/app/src/main/res/drawable-hdpi/loop_open.png new file mode 100644 index 0000000000..cdefc55ce8 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_open.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_pause.png b/app/src/main/res/drawable-hdpi/loop_pause.png new file mode 100644 index 0000000000..bb97008a07 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_pause.png differ diff --git a/app/src/main/res/drawable-hdpi/loop_superbolus.png b/app/src/main/res/drawable-hdpi/loop_superbolus.png new file mode 100644 index 0000000000..d9cec8f047 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/loop_superbolus.png differ diff --git a/app/src/main/res/drawable-hdpi/soso.png b/app/src/main/res/drawable-hdpi/soso.png new file mode 100644 index 0000000000..f7a9be577e Binary files /dev/null and b/app/src/main/res/drawable-hdpi/soso.png differ diff --git a/app/src/main/res/drawable-mdpi/bad.png b/app/src/main/res/drawable-mdpi/bad.png new file mode 100644 index 0000000000..9210154195 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/bad.png differ diff --git a/app/src/main/res/drawable-mdpi/good.png b/app/src/main/res/drawable-mdpi/good.png new file mode 100644 index 0000000000..a15f82c2b2 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/good.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_closed.png b/app/src/main/res/drawable-mdpi/loop_closed.png new file mode 100644 index 0000000000..ba4283035b Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_closed.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_disabled.png b/app/src/main/res/drawable-mdpi/loop_disabled.png new file mode 100644 index 0000000000..e4650ec0ac Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_disabled.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_disconnected.png b/app/src/main/res/drawable-mdpi/loop_disconnected.png new file mode 100644 index 0000000000..0bc9949349 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_disconnected.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_lgs.png b/app/src/main/res/drawable-mdpi/loop_lgs.png new file mode 100644 index 0000000000..a49229d4d8 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_lgs.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_open.png b/app/src/main/res/drawable-mdpi/loop_open.png new file mode 100644 index 0000000000..f82346f739 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_open.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_paused.png b/app/src/main/res/drawable-mdpi/loop_paused.png new file mode 100644 index 0000000000..7258615f66 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_paused.png differ diff --git a/app/src/main/res/drawable-mdpi/loop_superbolus.png b/app/src/main/res/drawable-mdpi/loop_superbolus.png new file mode 100644 index 0000000000..34a61c1bf3 Binary files /dev/null and b/app/src/main/res/drawable-mdpi/loop_superbolus.png differ diff --git a/app/src/main/res/drawable-mdpi/soso.png b/app/src/main/res/drawable-mdpi/soso.png new file mode 100644 index 0000000000..91d9bd7ddf Binary files /dev/null and b/app/src/main/res/drawable-mdpi/soso.png differ diff --git a/app/src/main/res/drawable-xhdpi/bad.png b/app/src/main/res/drawable-xhdpi/bad.png new file mode 100644 index 0000000000..46dca7155f Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/bad.png differ diff --git a/app/src/main/res/drawable-xhdpi/good.png b/app/src/main/res/drawable-xhdpi/good.png new file mode 100644 index 0000000000..08946fed3e Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/good.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_closed.png b/app/src/main/res/drawable-xhdpi/loop_closed.png new file mode 100644 index 0000000000..f7548add59 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_closed.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_disabled.png b/app/src/main/res/drawable-xhdpi/loop_disabled.png new file mode 100644 index 0000000000..0f7db5d681 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_disabled.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_disconnected.png b/app/src/main/res/drawable-xhdpi/loop_disconnected.png new file mode 100644 index 0000000000..7db5047b9f Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_disconnected.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_lgs.png b/app/src/main/res/drawable-xhdpi/loop_lgs.png new file mode 100644 index 0000000000..baa073ac8c Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_lgs.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_open.png b/app/src/main/res/drawable-xhdpi/loop_open.png new file mode 100644 index 0000000000..55726849d0 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_open.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_paused.png b/app/src/main/res/drawable-xhdpi/loop_paused.png new file mode 100644 index 0000000000..399ec449bc Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_paused.png differ diff --git a/app/src/main/res/drawable-xhdpi/loop_superbolus.png b/app/src/main/res/drawable-xhdpi/loop_superbolus.png new file mode 100644 index 0000000000..8bcf96248b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/loop_superbolus.png differ diff --git a/app/src/main/res/drawable-xhdpi/soso.png b/app/src/main/res/drawable-xhdpi/soso.png new file mode 100644 index 0000000000..8e19db274b Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/soso.png differ diff --git a/app/src/main/res/drawable-xxhdpi/bad.png b/app/src/main/res/drawable-xxhdpi/bad.png new file mode 100644 index 0000000000..b7a3201d60 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/bad.png differ diff --git a/app/src/main/res/drawable-xxhdpi/good.png b/app/src/main/res/drawable-xxhdpi/good.png new file mode 100644 index 0000000000..9f5c243b04 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/good.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_closed.png b/app/src/main/res/drawable-xxhdpi/loop_closed.png new file mode 100644 index 0000000000..5418ef1e7e Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_closed.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_disabled.png b/app/src/main/res/drawable-xxhdpi/loop_disabled.png new file mode 100644 index 0000000000..580dc5a5f5 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_disabled.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_disconnected.png b/app/src/main/res/drawable-xxhdpi/loop_disconnected.png new file mode 100644 index 0000000000..6e991f8ebf Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_disconnected.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_lgs.png b/app/src/main/res/drawable-xxhdpi/loop_lgs.png new file mode 100644 index 0000000000..86b4910f33 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_lgs.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_open.png b/app/src/main/res/drawable-xxhdpi/loop_open.png new file mode 100644 index 0000000000..1d35a9c987 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_open.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_paused.png b/app/src/main/res/drawable-xxhdpi/loop_paused.png new file mode 100644 index 0000000000..6db561b858 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_paused.png differ diff --git a/app/src/main/res/drawable-xxhdpi/loop_superbolus.png b/app/src/main/res/drawable-xxhdpi/loop_superbolus.png new file mode 100644 index 0000000000..c5187cf95d Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/loop_superbolus.png differ diff --git a/app/src/main/res/drawable-xxhdpi/soso.png b/app/src/main/res/drawable-xxhdpi/soso.png new file mode 100644 index 0000000000..6caac0cc05 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/soso.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/bad.png b/app/src/main/res/drawable-xxxhdpi/bad.png new file mode 100644 index 0000000000..484bd8fd0b Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/bad.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/good.png b/app/src/main/res/drawable-xxxhdpi/good.png new file mode 100644 index 0000000000..eb81a2b978 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/good.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_closed.png b/app/src/main/res/drawable-xxxhdpi/loop_closed.png new file mode 100644 index 0000000000..bd78239462 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_closed.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_disabled.png b/app/src/main/res/drawable-xxxhdpi/loop_disabled.png new file mode 100644 index 0000000000..824d6b9db1 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_disabled.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png b/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png new file mode 100644 index 0000000000..9c451cca88 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_disconnected.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_lgs.png b/app/src/main/res/drawable-xxxhdpi/loop_lgs.png new file mode 100644 index 0000000000..80848ff60a Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_lgs.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_open.png b/app/src/main/res/drawable-xxxhdpi/loop_open.png new file mode 100644 index 0000000000..f010399a53 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_open.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_paused.png b/app/src/main/res/drawable-xxxhdpi/loop_paused.png new file mode 100644 index 0000000000..36f9bcb5a5 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_paused.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png b/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png new file mode 100644 index 0000000000..018bf70188 Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/loop_superbolus.png differ diff --git a/app/src/main/res/drawable-xxxhdpi/soso.png b/app/src/main/res/drawable-xxxhdpi/soso.png new file mode 100644 index 0000000000..50b8f3fa5c Binary files /dev/null and b/app/src/main/res/drawable-xxxhdpi/soso.png differ diff --git a/app/src/main/res/drawable/ic_swap_vert_black_48dp_green.xml b/app/src/main/res/drawable/ic_swap_vert_black_48dp_green.xml new file mode 100644 index 0000000000..f78eaede2c --- /dev/null +++ b/app/src/main/res/drawable/ic_swap_vert_black_48dp_green.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/layout/maintenance_importlist_activity.xml b/app/src/main/res/layout/maintenance_importlist_activity.xml new file mode 100644 index 0000000000..0bdd43b927 --- /dev/null +++ b/app/src/main/res/layout/maintenance_importlist_activity.xml @@ -0,0 +1,24 @@ + + + + + + + + + + diff --git a/app/src/main/res/layout/maintenance_importlist_item.xml b/app/src/main/res/layout/maintenance_importlist_item.xml new file mode 100644 index 0000000000..8c2cfc0557 --- /dev/null +++ b/app/src/main/res/layout/maintenance_importlist_item.xml @@ -0,0 +1,169 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/layout/overview_buttons_layout.xml b/app/src/main/res/layout/overview_buttons_layout.xml new file mode 100644 index 0000000000..5c97104159 --- /dev/null +++ b/app/src/main/res/layout/overview_buttons_layout.xml @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/overview_fragment.xml b/app/src/main/res/layout/overview_fragment.xml index aa9e1d5c3a..747f53798e 100644 --- a/app/src/main/res/layout/overview_fragment.xml +++ b/app/src/main/res/layout/overview_fragment.xml @@ -1,640 +1,39 @@ - + android:layout_weight="1" + android:layout_width="wrap_content" + android:layout_height="0dp"> - - - - - + android:layout_height="wrap_content" /> - + + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - - - - - - - - - - - - - - - - - - - + diff --git a/app/src/main/res/layout/overview_fragment_landscape.xml b/app/src/main/res/layout/overview_fragment_landscape.xml index 471634ea8a..2d6250384d 100644 --- a/app/src/main/res/layout/overview_fragment_landscape.xml +++ b/app/src/main/res/layout/overview_fragment_landscape.xml @@ -1,628 +1,40 @@ - + android:layout_weight="1" + tools:ignore="UselessParent"> - - - - - + android:layout_height="wrap_content" /> - + + - + - + - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + diff --git a/app/src/main/res/layout/overview_fragment_nsclient.xml b/app/src/main/res/layout/overview_fragment_nsclient.xml index 504e88c789..c4ce063e29 100644 --- a/app/src/main/res/layout/overview_fragment_nsclient.xml +++ b/app/src/main/res/layout/overview_fragment_nsclient.xml @@ -1,466 +1,32 @@ - + android:layout_weight="1" + android:layout_width="wrap_content" + android:layout_height="0dp"> - - - - - + android:layout_height="wrap_content" /> - + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + android:textSize="16sp" /> + android:textSize="16sp" /> + android:textSize="16sp" /> - + - - - - - - - - + - + - - - - - - - - - - - - - - - - - + diff --git a/app/src/main/res/layout/overview_fragment_nsclient_tablet.xml b/app/src/main/res/layout/overview_fragment_nsclient_tablet.xml index 585a72159a..5c4340eea6 100644 --- a/app/src/main/res/layout/overview_fragment_nsclient_tablet.xml +++ b/app/src/main/res/layout/overview_fragment_nsclient_tablet.xml @@ -27,82 +27,7 @@ - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/overview_info_layout.xml b/app/src/main/res/layout/overview_info_layout.xml new file mode 100644 index 0000000000..9f2cdd8c2f --- /dev/null +++ b/app/src/main/res/layout/overview_info_layout.xml @@ -0,0 +1,242 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/overview_loop_pumpstatus_layout.xml b/app/src/main/res/layout/overview_loop_pumpstatus_layout.xml new file mode 100644 index 0000000000..98c0d0bd62 --- /dev/null +++ b/app/src/main/res/layout/overview_loop_pumpstatus_layout.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/overview_notification_item.xml b/app/src/main/res/layout/overview_notification_item.xml index 0c0d36ad25..03b5688fc3 100644 --- a/app/src/main/res/layout/overview_notification_item.xml +++ b/app/src/main/res/layout/overview_notification_item.xml @@ -1,7 +1,6 @@ - + android:layout_height="wrap_content" + android:gravity="center_vertical" + android:orientation="horizontal"> + +