diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e12816b735..aaa245f3bf 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -50,6 +50,10 @@ android:supportsRtl="true" android:theme="@style/AppTheme.Launcher" > + + - - - - + + + + + + + + + - - - - - - - - - - - - @@ -253,10 +209,6 @@ - - 120) { diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt index a4fa56a699..bac313ee14 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsBolusCarbsFragment.kt @@ -41,7 +41,7 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt index 820b5d3b93..14f2554dcc 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsCareportalFragment.kt @@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt index e21bd897ae..a6aa6de45b 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt @@ -33,7 +33,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt index 49e8c4ca52..183b94942f 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsProfileSwitchFragment.kt @@ -37,7 +37,7 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt index 137d6cf94c..3bed1259c8 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTempTargetFragment.kt @@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventNewHi import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt index 1f585ecd0a..7e62e28f1e 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsTemporaryBasalsFragment.kt @@ -38,7 +38,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt index bd442ce723..a5c4c40110 100644 --- a/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsUserEntryFragment.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.userEntry.UserEntryPresentationHelper import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/di/AppModule.kt b/app/src/main/java/info/nightscout/androidaps/di/AppModule.kt index dd3e723960..4b3d0797e7 100644 --- a/app/src/main/java/info/nightscout/androidaps/di/AppModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/di/AppModule.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelperImpl import info.nightscout.androidaps.utils.buildHelper.ConfigImpl import info.nightscout.androidaps.utils.resources.IconsProviderImplementation -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers import info.nightscout.androidaps.utils.storage.FileStorage diff --git a/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt b/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt index b10b4b90e9..9fc54fa7cf 100644 --- a/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt +++ b/app/src/main/java/info/nightscout/androidaps/di/ServicesModule.kt @@ -5,7 +5,7 @@ import dagger.android.ContributesAndroidInjector import info.nightscout.androidaps.plugins.general.nsclient.services.NSClientService import info.nightscout.androidaps.plugins.general.overview.notifications.DismissNotificationService import info.nightscout.androidaps.plugins.general.persistentNotification.DummyService -import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService +import info.nightscout.androidaps.plugins.general.wear.wearintegration.DataLayerListenerServiceMobile import info.nightscout.androidaps.services.AlarmSoundService import info.nightscout.androidaps.services.LocationService @@ -18,5 +18,5 @@ abstract class ServicesModule { @ContributesAndroidInjector abstract fun contributesDummyService(): DummyService @ContributesAndroidInjector abstract fun contributesLocationService(): LocationService @ContributesAndroidInjector abstract fun contributesNSClientService(): NSClientService - @ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): WatchUpdaterService + @ContributesAndroidInjector abstract fun contributesWatchUpdaterService(): DataLayerListenerServiceMobile } \ 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 303df14f60..23aa3a8874 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import java.util.* import javax.inject.Inject 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 cdf688b4c3..cd9eedaeb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CarbsDialog.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DecimalFormat 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 994613c38f..102177366f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/CareDialog.kt @@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.Translator import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.extensions.fromConstant import info.nightscout.androidaps.interfaces.GlucoseUnit -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DecimalFormat diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt index e4f45c4e1e..0f6fd525a1 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.LTag import java.text.DecimalFormat import java.util.* 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 c52ca8436b..a11fd61cbb 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/FillDialog.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* 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 5739902be0..9efb110a4f 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/InsulinDialog.kt @@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.extensions.toSignedString import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.SafeParse import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt index 5802f928bd..b6bff09699 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/LoopDialog.kt @@ -40,7 +40,7 @@ import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign 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 d7c7ecb809..db1a8d0478 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/ProfileSwitchDialog.kt @@ -35,7 +35,7 @@ import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DecimalFormat 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 62bd73862d..39e0ddda9b 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempBasalDialog.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.LTag import java.text.DecimalFormat import java.util.* 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 a1885c2d4e..407af78133 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TempTargetDialog.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DecimalFormat diff --git a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt index ff3dbfb30f..3a783410dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/TreatmentDialog.kt @@ -32,7 +32,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.text.DecimalFormat 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 841344fae3..5b5d56f93e 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardDialog.kt @@ -32,7 +32,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.wizard.BolusWizard import info.nightscout.shared.SafeParse 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 37a653f5e5..90f297bb08 100644 --- a/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt +++ b/app/src/main/java/info/nightscout/androidaps/dialogs/WizardInfoDialog.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt b/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt deleted file mode 100644 index a528ef1656..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/events/EventBolusRequested.kt +++ /dev/null @@ -1,3 +0,0 @@ -package info.nightscout.androidaps.events - -class EventBolusRequested(var amount: Double) : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopFragment.kt index dd524ec047..cb86f279a6 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 @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt index 89f394f696..4303cb179f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/loop/LoopPlugin.kt @@ -27,6 +27,7 @@ import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentOfflineEventTransaction import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction import info.nightscout.androidaps.events.EventAcceptOpenLoopChange +import info.nightscout.androidaps.events.EventMobileToWear import info.nightscout.androidaps.events.EventTempTargetChange import info.nightscout.androidaps.extensions.buildDeviceStatus import info.nightscout.androidaps.extensions.convertedToAbsolute @@ -44,8 +45,6 @@ import info.nightscout.androidaps.plugins.configBuilder.RunningConfiguration import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction -import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.receivers.ReceiverStatusStore @@ -53,11 +52,12 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject @@ -349,7 +349,7 @@ class LoopPlugin @Inject constructor( //only send to wear if Native notifications are turned off if (!sp.getBoolean(R.string.key_raise_notifications_as_android_notifications, true)) { // Send to Wear - rxBus.send(EventWearInitiateAction("changeRequest")) + sendToWear() } } } else { @@ -454,14 +454,28 @@ class LoopPlugin @Inject constructor( rxBus.send(EventNewOpenLoopNotification()) // Send to Wear - rxBus.send(EventWearInitiateAction("changeRequest")) + sendToWear() } private fun dismissSuggestion() { // dismiss notifications val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(Constants.notificationID) - rxBus.send(EventWearConfirmAction("cancelChangeRequest")) + rxBus.send(EventMobileToWear(EventData.CancelNotification(dateUtil.now()))) + } + + private fun sendToWear() { + lastRun?.let { + rxBus.send( + EventMobileToWear( + EventData.OpenLoopRequest( + rh.gs(R.string.openloop_newsuggestion), + it.constraintsProcessed.toString(), + EventData.OpenLoopRequestConfirmed(dateUtil.now()) + ) + ) + ) + } } override fun acceptChangeRequest() { 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 463f15981f..320ce0f2c8 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 @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.JSONFormatter -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt index 229b8ecd14..3e78943b98 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSAMA/OpenAPSAMAPlugin.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.extensions.target -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONException import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt index 33c5bb0aa4..c23f14d54a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/DetermineBasalAdapterSMBJS.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.aps.loop.ScriptReader import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.shared.SafeParse -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException 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 3cd8f8c6f0..23a61db108 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 @@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.JSONFormatter -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt index 873b0294e8..156cceb4ce 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBPlugin.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt index 0c6eb35acb..c1cf1994d3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/DetermineBasalAdapterSMBDynamicISFJS.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.plugins.aps.openAPSSMB.SMBDefaults import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.stats.TddCalculator import info.nightscout.shared.SafeParse import info.nightscout.shared.logging.AAPSLogger diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt index 739379a82c..3c7878676c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMBDynamicISF/OpenAPSSMBDynamicISFPlugin.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt index 96095067d6..a8aab6ee56 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderFragment.kt @@ -26,7 +26,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.PREFERENCES -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt index 72b650e284..e45ec36117 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPlugin.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.events.EventConfigBuilderUpdateGui import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt index 89b1da7047..b851e40b22 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/configBuilder/ProfileFunctionImplementation.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt index 800994fe03..528da25cff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPlugin.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventBucke 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt index 7f8f637bd1..3bd7984943 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPlugin.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject 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 84cd7eebba..09c8b50dc6 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 @@ -38,7 +38,7 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.SntpClient import info.nightscout.androidaps.utils.alertDialogs.OKDialog import io.reactivex.rxjava3.kotlin.plusAssign -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable 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 73f4d99cc9..76e5f397e5 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 @@ -14,7 +14,7 @@ import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.constraints.objectives.objectives.* import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject 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 ecf004f82f..e2ae0121a0 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 @@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Obje import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class ObjectivesExamDialog : DaggerDialogFragment() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt index 9faa974d1f..9929db80e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/objectives/objectives/Objective.kt @@ -11,7 +11,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject 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 fed6ccfd31..8d5e1fdd62 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 @@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt index 80d6728b82..651e5b18a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/safety/SafetyPlugin.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt index 19b0415f96..aba2b0247f 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPlugin.kt @@ -13,7 +13,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.spongycastle.util.encoders.Hex import java.io.* diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt index 2bc2dfef67..2dd8c80832 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPlugin.kt @@ -16,7 +16,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt index 8347a45715..9c55f5cdf3 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerPlugin.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.extensions.daysToMillis -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import java.util.concurrent.TimeUnit 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 d93cd1fa83..5e2342770c 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 @@ -41,7 +41,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.SingleClickButton @@ -84,14 +84,15 @@ class ActionsFragment : DaggerFragment() { // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! - override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { + override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { //check screen width dm = DisplayMetrics() if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) { @Suppress("DEPRECATION") activity?.display?.getRealMetrics(dm) } else { - @Suppress("DEPRECATION") activity?.windowManager?.defaultDisplay?.getMetrics(dm) + @Suppress("DEPRECATION") + activity?.windowManager?.defaultDisplay?.getMetrics(dm) } _binding = ActionsFragmentBinding.inflate(inflater, container, false) return binding.root 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 e99beec86a..879c084315 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 @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton 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 4d08f94a4e..95cfb4a518 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 @@ -22,7 +22,7 @@ import info.nightscout.androidaps.services.Intents import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt index 392adda03d..4ca21b858d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodFragment.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.shared.logging.AAPSLogger diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt index 233d9ba78b..9bc829632c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/food/FoodPlugin.kt @@ -17,7 +17,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt index 69e2fd7c25..c4a10f45a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/ImportExportPrefsImpl.kt @@ -39,7 +39,7 @@ import info.nightscout.androidaps.utils.alertDialogs.TwoMessagesAlertDialog import info.nightscout.androidaps.utils.alertDialogs.WarningDialog 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage import info.nightscout.androidaps.utils.userEntry.UserEntryPresentationHelper import info.nightscout.shared.logging.AAPSLogger diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt index c927072d83..d2085c0194 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenanceFragment.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.database.Ero import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.PREFERENCES -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.core.Completable.fromAction import io.reactivex.rxjava3.disposables.CompositeDisposable 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 15f6ae2bd4..cdbbb6f038 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 @@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger 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.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.io.* import java.util.* diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt index 63351dc7ba..4aa2b84a85 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientFragment.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientR import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt index 94a2eecbac..180440f6db 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NSClientPlugin.kt @@ -35,7 +35,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper.fromHtml import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt index 9415489c78..46b537bd86 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegate.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.receivers.ReceiverStatusStore -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt index 0b1ecc3105..88bbbce04c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/data/NSDeviceStatus.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.utils.HtmlHelper.fromHtml import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP 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 1aa60b800e..455466bbac 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 @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt index c4291de252..abee8602e4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/events/EventNSClientStatus.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.general.nsclient.events import info.nightscout.androidaps.events.EventStatus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class EventNSClientStatus(var text: String) : EventStatus() { override fun getStatus(rh: ResourceHelper): String = text diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt index d5ea640f00..2f6c503318 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/nsclient/services/NSClientService.kt @@ -44,7 +44,7 @@ import info.nightscout.androidaps.utils.JsonHelper.safeGetStringAllowNull import info.nightscout.androidaps.utils.T.Companion.mins import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt index deb355c24d..1f17b786dd 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewData.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.CobInfo import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import java.util.* 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 865ee4496e..d7becd662f 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 @@ -54,7 +54,6 @@ import info.nightscout.androidaps.plugins.general.overview.activities.QuickWizar import info.nightscout.androidaps.plugins.general.overview.events.* import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore -import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.omnipod.eros.OmnipodErosPumpPlugin @@ -69,13 +68,14 @@ import info.nightscout.androidaps.utils.TrendCalculator import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.SingleClickButton import info.nightscout.androidaps.utils.ui.UIRunnable import info.nightscout.androidaps.utils.wizard.QuickWizard import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* @@ -407,7 +407,7 @@ class OverviewFragment : DaggerFragment(), View.OnClickListener, OnLongClickList ?: "".toSpanned(), { uel.log(Action.ACCEPTS_TEMP_BASAL, Sources.Overview) (context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?)?.cancel(Constants.notificationID) - rxBus.send(EventWearInitiateAction("cancelChangeRequest")) + rxBus.send(EventMobileToWear(EventData.CancelNotification(dateUtil.now()))) Thread { loop.acceptChangeRequest() }.run() binding.buttonsLayout.acceptTempButton.visibility = View.GONE }) 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 ae10a7d061..4a7c68ead3 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 @@ -18,7 +18,7 @@ import info.nightscout.androidaps.interfaces.Loop import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt index 86469e8434..50bf49c812 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/OverviewPlugin.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP 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 f3455580ee..11de792fbd 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 @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Om import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.WarnColors -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton 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 9b21d70219..7bc33f3f51 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 @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Doubl import info.nightscout.androidaps.plugins.general.overview.graphExtensions.TimeAsXAxisLabelFormatter import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject import kotlin.math.abs diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt index c354ad9fbb..7ff14d0b43 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/BolusDataPoint.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.database.entities.Bolus import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class BolusDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt index e5b9ca9973..c457ef895e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/CarbsDataPoint.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.general.overview.graphExtensions import android.content.Context import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.Carbs -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class CarbsDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/EffectiveProfileSwitchDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/EffectiveProfileSwitchDataPoint.kt index 58287aaaad..e2135d7a8e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/EffectiveProfileSwitchDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/EffectiveProfileSwitchDataPoint.kt @@ -4,7 +4,7 @@ import android.content.Context import android.graphics.Color import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class EffectiveProfileSwitchDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/ExtendedBolusDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/ExtendedBolusDataPoint.kt index 1d30ca23d9..074140abb5 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/ExtendedBolusDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/ExtendedBolusDataPoint.kt @@ -5,7 +5,7 @@ import android.graphics.Color import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.ExtendedBolus import info.nightscout.androidaps.extensions.toStringTotal -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class ExtendedBolusDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt index bb31301a84..107543f728 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/GlucoseValueDataPoint.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class GlucoseValueDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt index 7849c38318..e73535cbe7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/InMemoryGlucoseValueDataPoint.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.data.InMemoryGlucoseValue import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.ProfileFunction -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class InMemoryGlucoseValueDataPoint @Inject constructor( diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt index 7577062961..4692810ebb 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/graphExtensions/TherapyEventDataPoint.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.utils.Translator -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class TherapyEventDataPoint @Inject constructor( 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 087ec2f2ee..ddfd52f32e 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 @@ -22,7 +22,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewNotification import info.nightscout.androidaps.services.AlarmSoundServiceHelper import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt index 1c5e520aee..2591bafc7c 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/overview/notifications/NotificationWithAction.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.NSClientPlugin import info.nightscout.androidaps.plugins.general.nsclient.data.NSAlarm import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject 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 17afcbebd0..0a4072250b 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 @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt index 910bb76618..f4c41c42c4 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequest.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePas import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class AuthRequest internal constructor( 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 6952ea186e..61021d55bc 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 @@ -43,7 +43,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.* -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.textValidator.ValidatingEditTextPreference diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt index 9a8034ac00..b6f97584c9 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/otp/OneTimePassword.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.Constants import info.nightscout.androidaps.R import info.nightscout.androidaps.annotations.OpenForTesting import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.net.URLEncoder import javax.crypto.KeyGenerator diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/themes/ThemeSwitcherPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/themes/ThemeSwitcherPlugin.kt index 0523fde640..c02ea27396 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/themes/ThemeSwitcherPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/themes/ThemeSwitcherPlugin.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt index 05d0dfbc23..e6e58e9264 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/TidepoolPlugin.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils import io.reactivex.rxjava3.kotlin.plusAssign -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable 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 9d1ca14687..45ad50857b 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 @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.general.tidepool.messages.UploadReplyM import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolResetData.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolResetData.kt index 833353e6b0..8ea3460801 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolResetData.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/tidepool/events/EventTidepoolResetData.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.general.tidepool.events import info.nightscout.androidaps.events.Event -class EventTidepoolResetData :Event() \ No newline at end of file +class EventTidepoolResetData : Event() \ No newline at end of file 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 deleted file mode 100644 index d4eb8a30e1..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/ActionStringHandler.kt +++ /dev/null @@ -1,778 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear - -import android.app.NotificationManager -import android.content.Context -import android.util.Log -import dagger.android.HasAndroidInjector -import info.nightscout.androidaps.Constants -import info.nightscout.androidaps.R -import info.nightscout.androidaps.dana.DanaPump -import info.nightscout.androidaps.danaRKorean.DanaRKoreanPlugin -import info.nightscout.androidaps.danaRv2.DanaRv2Plugin -import info.nightscout.androidaps.danar.DanaRPlugin -import info.nightscout.androidaps.danars.DanaRSPlugin -import info.nightscout.androidaps.data.DetailedBolusInfo -import info.nightscout.androidaps.database.AppRepository -import info.nightscout.androidaps.database.ValueWrapper -import info.nightscout.androidaps.database.entities.TemporaryTarget -import info.nightscout.androidaps.database.entities.TotalDailyDose -import info.nightscout.androidaps.database.entities.UserEntry.Action -import info.nightscout.androidaps.database.entities.UserEntry.Sources -import info.nightscout.androidaps.database.entities.ValueWithUnit -import info.nightscout.androidaps.database.interfaces.end -import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction -import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction -import info.nightscout.androidaps.extensions.total -import info.nightscout.androidaps.extensions.valueToUnits -import info.nightscout.androidaps.interfaces.* -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag -import info.nightscout.androidaps.logging.UserEntryLogger -import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker -import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification -import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction -import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction -import info.nightscout.androidaps.plugins.pump.insight.LocalInsightPlugin -import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.* -import info.nightscout.androidaps.utils.resources.ResourceHelper -import info.nightscout.androidaps.utils.rx.AapsSchedulers -import info.nightscout.shared.sharedPreferences.SP -import info.nightscout.androidaps.utils.wizard.BolusWizard -import info.nightscout.androidaps.utils.wizard.QuickWizard -import info.nightscout.shared.SafeParse -import io.reactivex.rxjava3.disposables.CompositeDisposable -import io.reactivex.rxjava3.kotlin.plusAssign -import java.text.DateFormat -import java.text.SimpleDateFormat -import java.util.* -import java.util.concurrent.TimeUnit -import javax.inject.Inject -import javax.inject.Singleton -import kotlin.math.abs -import kotlin.math.min - -@Suppress("SpellCheckingInspection") -@Singleton -class ActionStringHandler @Inject constructor( - private val sp: SP, - private val rxBus: RxBus, - private val aapsLogger: AAPSLogger, - private val aapsSchedulers: AapsSchedulers, - private val rh: ResourceHelper, - private val injector: HasAndroidInjector, - private val context: Context, - private val constraintChecker: ConstraintChecker, - private val profileFunction: ProfileFunction, - private val loop: Loop, - private val wearPlugin: WearPlugin, - private val fabricPrivacy: FabricPrivacy, - private val commandQueue: CommandQueue, - private val activePlugin: ActivePlugin, - private val iobCobCalculator: IobCobCalculator, - private val localInsightPlugin: LocalInsightPlugin, - private val quickWizard: QuickWizard, - private val danaRPlugin: DanaRPlugin, - private val danaRKoreanPlugin: DanaRKoreanPlugin, - private val danaRv2Plugin: DanaRv2Plugin, - private val danaRSPlugin: DanaRSPlugin, - private val danaPump: DanaPump, - private val dateUtil: DateUtil, - private val config: Config, - private val repository: AppRepository, - private val uel: UserEntryLogger, - private val defaultValueHelper: DefaultValueHelper -) { - - private val timeout = 65 * 1000 - private var lastSentTimestamp: Long = 0 - private var lastConfirmActionString: String? = null - private var lastBolusWizard: BolusWizard? = null - - private val disposable = CompositeDisposable() - - fun setup() { - disposable += rxBus - .toObservable(EventWearInitiateAction::class.java) - .observeOn(aapsSchedulers.main) - .subscribe({ handleInitiate(it.action) }, fabricPrivacy::logException) - - disposable += rxBus - .toObservable(EventWearConfirmAction::class.java) - .observeOn(aapsSchedulers.main) - .subscribe({ handleConfirmation(it.action) }, fabricPrivacy::logException) - } - - fun tearDown() { - disposable.clear() - } - - @Synchronized - private fun handleInitiate(actionString: String) { - //TODO: i18n - Log.i("ActionStringHandler", "handleInitiate actionString=$actionString") - if (!sp.getBoolean(R.string.key_wear_control, false)) return - lastBolusWizard = null - var rTitle = rh.gs(R.string.confirm).uppercase() - var rMessage = "" - var rAction = "" - // do the parsing and check constraints - val act = actionString.split("\\s+".toRegex()).toTypedArray() - if ("fillpreset" == act[0]) { ///////////////////////////////////// PRIME/FILL - val amount: Double = when { - "1" == act[1] -> sp.getDouble("fill_button1", 0.3) - "2" == act[1] -> sp.getDouble("fill_button2", 0.0) - "3" == act[1] -> sp.getDouble("fill_button3", 0.0) - else -> return - } - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() - rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" - if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied) - rAction += "fill $insulinAfterConstraints" - } else if ("fill" == act[0]) { ////////////////////////////////////////////// PRIME/FILL - val amount = SafeParse.stringToDouble(act[1]) - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() - rMessage += rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" - if (insulinAfterConstraints - amount != 0.0) rMessage += "\n" + rh.gs(R.string.constraintapllied) - rAction += "fill $insulinAfterConstraints" - } else if ("bolus" == act[0]) { ////////////////////////////////////////////// BOLUS - val insulin = SafeParse.stringToDouble(act[1]) - val carbs = SafeParse.stringToInt(act[2]) - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(insulin)).value() - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() - val pump = activePlugin.activePump - if (insulinAfterConstraints > 0 && (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected)) { - sendError(rh.gs(R.string.wizard_pump_not_available)) - return - } - rMessage += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" - rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" - if (insulinAfterConstraints - insulin != 0.0 || carbsAfterConstraints - carbs != 0) { - rMessage += "\n" + rh.gs(R.string.constraintapllied) - } - rAction += "bolus $insulinAfterConstraints $carbsAfterConstraints" - } else if ("temptarget" == act[0]) { ///////////////////////////////////////////////////////// TEMPTARGET - aapsLogger.info(LTag.WEAR, "temptarget received: $act") - if ("cancel" == act[1]) { - rMessage += rh.gs(R.string.wear_action_tempt_cancel_message) - rAction = "temptarget true 0 0 0" - } else if ("preset" == act[1]) { - val presetIsMGDL = profileFunction.getUnits() == GlucoseUnit.MGDL - val preset = act[2] - when (preset) { - "activity" -> { - val activityTTDuration = defaultValueHelper.determineActivityTTDuration() - val activityTT = defaultValueHelper.determineActivityTT() - val reason = rh.gs(R.string.activity) - rMessage += rh.gs(R.string.wear_action_tempt_preset_message, reason, activityTT, activityTTDuration) - rAction = "temptarget $presetIsMGDL $activityTTDuration $activityTT $activityTT" - } - - "hypo" -> { - val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() - val hypoTT = defaultValueHelper.determineHypoTT() - val reason = rh.gs(R.string.hypo) - rMessage += rh.gs(R.string.wear_action_tempt_preset_message, reason, hypoTT, hypoTTDuration) - rAction = "temptarget $presetIsMGDL $hypoTTDuration $hypoTT $hypoTT" - } - - "eating" -> { - val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration() - val eatingSoonTT = defaultValueHelper.determineEatingSoonTT() - val reason = rh.gs(R.string.eatingsoon) - rMessage += rh.gs(R.string.wear_action_tempt_preset_message, reason, eatingSoonTT, eatingSoonTTDuration) - rAction = "temptarget $presetIsMGDL $eatingSoonTTDuration $eatingSoonTT $eatingSoonTT" - } - - else -> { - sendError(rh.gs(R.string.wear_action_tempt_preset_error, preset)) - return - } - } - } else { - val isMGDL = java.lang.Boolean.parseBoolean(act[1]) - if (profileFunction.getUnits() == GlucoseUnit.MGDL != isMGDL) { - sendError(rh.gs(R.string.wear_action_tempt_unit_error)) - return - } - val duration = SafeParse.stringToInt(act[2]) - if (duration == 0) { - rMessage += rh.gs(R.string.wear_action_tempt_zero_message) - rAction = "temptarget true 0 0 0" - } else { - var low = SafeParse.stringToDouble(act[3]) - var high = SafeParse.stringToDouble(act[4]) - if (!isMGDL) { - low *= Constants.MMOLL_TO_MGDL - high *= Constants.MMOLL_TO_MGDL - } - if (low < HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0] || low > HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]) { - sendError(rh.gs(R.string.wear_action_tempt_min_bg_error)) - return - } - if (high < HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0] || high > HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]) { - sendError(rh.gs(R.string.wear_action_tempt_max_bg_error)) - return - } - rMessage += if (act[3] === act[4]) rh.gs(R.string.wear_action_tempt_manual_message, act[3], act[2]) - else rh.gs(R.string.wear_action_tempt_manual_range_message, act[3], act[4], act[2]) - rAction = actionString - } - } - } else if ("status" == act[0]) { ////////////////////////////////////////////// STATUS - rTitle = "STATUS" - rAction = "statusmessage" - if ("pump" == act[1]) { - rTitle += " PUMP" - rMessage = pumpStatus - } else if ("loop" == act[1]) { - rTitle += " LOOP" - rMessage = "TARGETS:\n$targetsStatus" - rMessage += "\n\n" + loopStatus - rMessage += "\n\nOAPS RESULT:\n$oAPSResultStatus" - } - } else if ("wizard" == act[0]) { - sendError("Update APP on Watch!") - return - } else if ("wizard2" == act[0]) { ////////////////////////////////////////////// WIZARD - val pump = activePlugin.activePump - if (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected) { - sendError(rh.gs(R.string.wizard_pump_not_available)) - return - } - val carbsBeforeConstraints = SafeParse.stringToInt(act[1]) - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbsBeforeConstraints)).value() - if (carbsAfterConstraints - carbsBeforeConstraints != 0) { - sendError(rh.gs(R.string.wizard_carbs_constraint)) - return - } - val useBG = sp.getBoolean(R.string.key_wearwizard_bg, true) - val useTT = sp.getBoolean(R.string.key_wearwizard_tt, false) - val useBolusIOB = sp.getBoolean(R.string.key_wearwizard_bolusiob, true) - val useBasalIOB = sp.getBoolean(R.string.key_wearwizard_basaliob, true) - val useCOB = sp.getBoolean(R.string.key_wearwizard_cob, true) - val useTrend = sp.getBoolean(R.string.key_wearwizard_trend, false) - val percentage = act[2].toInt() - val profile = profileFunction.getProfile() - val profileName = profileFunction.getProfileName() - if (profile == null) { - sendError(rh.gs(R.string.wizard_no_active_profile)) - return - } - val bgReading = iobCobCalculator.ads.actualBg() - if (bgReading == null) { - sendError(rh.gs(R.string.wizard_no_actual_bg)) - return - } - val cobInfo = iobCobCalculator.getCobInfo(false, "Wizard wear") - if (cobInfo.displayCob == null) { - sendError(rh.gs(R.string.wizard_no_cob)) - return - } - val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() - val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null - - val bolusWizard = BolusWizard(injector).doCalc( - profile, profileName, tempTarget, - carbsAfterConstraints, cobInfo.displayCob!!, bgReading.valueToUnits(profileFunction.getUnits()), - 0.0, percentage, useBG, useCOB, useBolusIOB, useBasalIOB, false, useTT, useTrend, false - ) - val insulinAfterConstraints = bolusWizard.insulinAfterConstraints - val minStep = pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints) - if (abs(insulinAfterConstraints - bolusWizard.calculatedTotalInsulin) >= minStep) { - sendError(rh.gs(R.string.wizard_constraint_bolus_size, bolusWizard.calculatedTotalInsulin)) - return - } - if (bolusWizard.calculatedTotalInsulin <= 0 && bolusWizard.carbs <= 0) { - rAction = "info" - rTitle = rh.gs(R.string.info) - } else { - rAction = actionString - } - rMessage += rh.gs(R.string.wizard_result, bolusWizard.calculatedTotalInsulin, bolusWizard.carbs) - rMessage += "\n_____________" - rMessage += "\n" + bolusWizard.explainShort() - lastBolusWizard = bolusWizard - } else if ("quick_wizard" == act[0]) { - val guid = act[1] - val actualBg = iobCobCalculator.ads.actualBg() - val profile = profileFunction.getProfile() - val profileName = profileFunction.getProfileName() - val quickWizardEntry = quickWizard.get(guid) - Log.i("QuickWizard", "handleInitiate: quick_wizard " + quickWizardEntry?.buttonText() + " c " + quickWizardEntry?.carbs()) - if (quickWizardEntry == null) { - sendError(rh.gs(R.string.quick_wizard_not_available)) - return - } - if (actualBg == null) { - sendError(rh.gs(R.string.wizard_no_actual_bg)) - return - } - if (profile == null) { - sendError(rh.gs(R.string.wizard_no_active_profile)) - return - } - val cobInfo = iobCobCalculator.getCobInfo(false, "QuickWizard wear") - if (cobInfo.displayCob == null) { - sendError(rh.gs(R.string.wizard_no_cob)) - return - } - val pump = activePlugin.activePump - if (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected) { - sendError(rh.gs(R.string.wizard_pump_not_available)) - return - } - - val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true) - - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() - if (carbsAfterConstraints != quickWizardEntry.carbs()) { - sendError(rh.gs(R.string.wizard_carbs_constraint)) - return - } - val insulinAfterConstraints = wizard.insulinAfterConstraints - val minStep = pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints) - if (abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= minStep) { - sendError(rh.gs(R.string.wizard_constraint_bolus_size, wizard.calculatedTotalInsulin)) - return - } - - rMessage = rh.gs(R.string.quick_wizard_message, quickWizardEntry.buttonText(), wizard.calculatedTotalInsulin, quickWizardEntry.carbs()) - rAction = "bolus $insulinAfterConstraints $carbsAfterConstraints" - Log.i("QuickWizard", "handleInitiate: quick_wizard action=$rAction") - - rMessage += "\n_____________" - rMessage += "\n" + wizard.explainShort() - - } else if ("opencpp" == act[0]) { - val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() - if (activeProfileSwitch is ValueWrapper.Existing) { // read CPP values - rTitle = "opencpp" - rMessage = "opencpp" - rAction = "opencpp" + " " + activeProfileSwitch.value.originalPercentage + " " + activeProfileSwitch.value.originalTimeshift - } else { - sendError("No active profile switch!") - return - } - } else if ("cppset" == act[0]) { - val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() - if (activeProfileSwitch is ValueWrapper.Existing) { - rMessage = "CPP:" + "\n\n" + - "Timeshift: " + act[1] + "\n" + - "Percentage: " + act[2] + "%" - rAction = actionString - } else { // read CPP values - sendError("No active profile switch!") - return - } - } else if ("tddstats" == act[0]) { - val activePump = activePlugin.activePump - // check if DB up to date - val dummies: MutableList = LinkedList() - val historyList = getTDDList(dummies) - if (isOldData(historyList)) { - rTitle = "TDD" - rAction = "statusmessage" - rMessage = "OLD DATA - " - //if pump is not busy: try to fetch data - if (activePump.isBusy()) { - rMessage += rh.gs(R.string.pumpbusy) - } else { - rMessage += "trying to fetch data from pump." - commandQueue.loadTDDs(object : Callback() { - override fun run() { - val dummies1: MutableList = LinkedList() - val historyList1 = getTDDList(dummies1) - if (isOldData(historyList1)) { - sendStatusMessage("TDD: Still old data! Cannot load from pump.\n" + generateTDDMessage(historyList1, dummies1)) - } else { - sendStatusMessage(generateTDDMessage(historyList1, dummies1)) - } - } - }) - } - } else { // if up to date: prepare, send (check if CPP is activated -> add CPP stats) - rTitle = "TDD" - rAction = "statusmessage" - rMessage = generateTDDMessage(historyList, dummies) - } - } else if ("ecarbs" == act[0]) { ////////////////////////////////////////////// ECARBS - val carbs = SafeParse.stringToInt(act[1]) - val starttime = SafeParse.stringToInt(act[2]) - val duration = SafeParse.stringToInt(act[3]) - val starttimestamp = System.currentTimeMillis() + starttime * 60 * 1000 - val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbs)).value() - rMessage += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" - rMessage += "\n" + rh.gs(R.string.time) + ": " + dateUtil.timeString(starttimestamp) - rMessage += "\n" + rh.gs(R.string.duration) + ": " + duration + "h" - if (carbsAfterConstraints - carbs != 0) { - rMessage += "\n" + rh.gs(R.string.constraintapllied) - } - if (carbsAfterConstraints <= 0) { - sendError("Carbs = 0! No action taken!") - return - } - rAction += "ecarbs $carbsAfterConstraints $starttimestamp $duration" - } else if ("changeRequest" == act[0]) { ////////////////////////////////////////////// CHANGE REQUEST - rTitle = rh.gs(R.string.openloop_newsuggestion) - rAction = "changeRequest" - loop.lastRun?.let { - rMessage += it.constraintsProcessed - wearPlugin.requestChangeConfirmation(rTitle, rMessage, rAction) - lastSentTimestamp = System.currentTimeMillis() - lastConfirmActionString = rAction - } - return - } else if ("cancelChangeRequest" == act[0]) { ////////////////////////////////////////////// CANCEL CHANGE REQUEST NOTIFICATION - rAction = "cancelChangeRequest" - wearPlugin.requestNotificationCancel(rAction) - return - } else { - sendError(rh.gs(R.string.wear_unknown_action_string) + act[0]) - return - } - // send result - wearPlugin.requestActionConfirmation(rTitle, rMessage, rAction) - lastSentTimestamp = System.currentTimeMillis() - lastConfirmActionString = rAction - } - - private fun generateTDDMessage(historyList: MutableList, dummies: MutableList): String { - val profile = profileFunction.getProfile() ?: return "No profile loaded :(" - if (historyList.isEmpty()) { - return "No history data!" - } - val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) - var message = "" - val refTDD = profile.baseBasalSum() * 2 - val pump = activePlugin.activePump - if (df.format(Date(historyList[0].timestamp)) == df.format(Date())) { - val tdd = historyList[0].total - historyList.removeAt(0) - message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" - message += "\n" - } else if (pump is DanaRPlugin) { - val tdd = danaPump.dailyTotalUnits - message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" - message += "\n" - } - var weighted03 = 0.0 - var weighted05 = 0.0 - var weighted07 = 0.0 - historyList.reverse() - for ((i, record) in historyList.withIndex()) { - val tdd = record.total - if (i == 0) { - weighted03 = tdd - weighted05 = tdd - weighted07 = tdd - } else { - weighted07 = weighted07 * 0.3 + tdd * 0.7 - weighted05 = weighted05 * 0.5 + tdd * 0.5 - weighted03 = weighted03 * 0.7 + tdd * 0.3 - } - } - message += "weighted:\n" - message += "0.3: " + DecimalFormatter.to2Decimal(weighted03) + "U " + (DecimalFormatter.to0Decimal(100 * weighted03 / refTDD) + "%") + "\n" - message += "0.5: " + DecimalFormatter.to2Decimal(weighted05) + "U " + (DecimalFormatter.to0Decimal(100 * weighted05 / refTDD) + "%") + "\n" - message += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (DecimalFormatter.to0Decimal(100 * weighted07 / refTDD) + "%") + "\n" - message += "\n" - historyList.reverse() - //add TDDs: - for (record in historyList) { - val tdd = record.total - message += df.format(Date(record.timestamp)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (if (dummies.contains(record)) "x" else "") + "\n" - } - return message - } - - private fun isOldData(historyList: List): Boolean { - val activePump = activePlugin.activePump - val startsYesterday = activePump === danaRPlugin || activePump === danaRSPlugin || activePump === danaRv2Plugin || activePump === danaRKoreanPlugin || activePump === localInsightPlugin - val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) - return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) - } - - private fun getTDDList(returnDummies: MutableList): MutableList { - var historyList = repository.getLastTotalDailyDoses(10, false).blockingGet().toMutableList() - //var historyList = databaseHelper.getTDDs().toMutableList() - historyList = historyList.subList(0, min(10, historyList.size)) - //fill single gaps - only needed for Dana*R data - val dummies: MutableList = returnDummies - val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) - for (i in 0 until historyList.size - 1) { - val elem1 = historyList[i] - val elem2 = historyList[i + 1] - if (df.format(Date(elem1.timestamp)) != df.format(Date(elem2.timestamp + 25 * 60 * 60 * 1000))) { - val dummy = TotalDailyDose(timestamp = elem1.timestamp - T.hours(24).msecs(), bolusAmount = elem1.bolusAmount / 2, basalAmount = elem1.basalAmount / 2) - dummies.add(dummy) - elem1.basalAmount /= 2.0 - elem1.bolusAmount /= 2.0 - } - } - historyList.addAll(dummies) - historyList.sortWith { lhs, rhs -> (rhs.timestamp - lhs.timestamp).toInt() } - return historyList - } - - private val pumpStatus: String - get() = activePlugin.activePump.shortStatus(false) - - // decide if enabled/disabled closed/open; what Plugin as APS? - private val loopStatus: String - get() { - var ret = "" - // decide if enabled/disabled closed/open; what Plugin as APS? - if ((loop as PluginBase).isEnabled()) { - ret += if (constraintChecker.isClosedLoopAllowed().value()) { - "CLOSED LOOP\n" - } else { - "OPEN LOOP\n" - } - val aps = activePlugin.activeAPS - ret += "APS: " + (aps as PluginBase).name - val lastRun = loop.lastRun - if (lastRun != null) { - ret += "\nLast Run: " + dateUtil.timeString(lastRun.lastAPSRun) - if (lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + dateUtil.timeString(lastRun.lastTBREnact) - } - } else { - ret += "LOOP DISABLED\n" - } - return ret - } - - //Check for Temp-Target: - private val targetsStatus: String - get() { - var ret = "" - if (!config.APS) { - return "Targets only apply in APS mode!" - } - val profile = profileFunction.getProfile() ?: return "No profile set :(" - //Check for Temp-Target: - val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() - if (tempTarget is ValueWrapper.Existing) { - ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, GlucoseUnit.MGDL, profileFunction.getUnits()) - ret += "\nuntil: " + dateUtil.timeString(tempTarget.value.end) - ret += "\n\n" - } - ret += "DEFAULT RANGE: " - ret += Profile.fromMgdlToUnits(profile.getTargetLowMgdl(), profileFunction.getUnits()).toString() + " - " + Profile.fromMgdlToUnits(profile.getTargetHighMgdl(), profileFunction.getUnits()) - ret += " target: " + Profile.fromMgdlToUnits(profile.getTargetMgdl(), profileFunction.getUnits()) - return ret - } - - private val oAPSResultStatus: String - get() { - var ret = "" - if (!config.APS) - return "Only apply in APS mode!" - val usedAPS = activePlugin.activeAPS - val result = usedAPS.lastAPSResult ?: return "Last result not available!" - ret += if (!result.isChangeRequested) { - rh.gs(R.string.nochangerequested) + "\n" - } else if (result.rate == 0.0 && result.duration == 0) { - rh.gs(R.string.canceltemp) + "\n" - } else { - rh.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + - "(" + DecimalFormatter.to2Decimal(result.rate / activePlugin.activePump.baseBasalRate * 100) + "%)\n" + - rh.gs(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration.toDouble()) + " min\n" - } - ret += "\n" + rh.gs(R.string.reason) + ": " + result.reason - return ret - } - - @Synchronized - fun handleConfirmation(actionString: String) { - if (!sp.getBoolean(R.string.key_wear_control, false)) return - //Guard from old or duplicate confirmations - if (lastConfirmActionString == null) return - if (lastConfirmActionString != actionString) return - if (System.currentTimeMillis() - lastSentTimestamp > timeout) return - lastConfirmActionString = null - // do the parsing, check constraints and enact! - val act = actionString.split("\\s+".toRegex()).toTypedArray() - if ("fill" == act[0]) { - val amount = SafeParse.stringToDouble(act[1]) - val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() - if (amount - insulinAfterConstraints != 0.0) { - ToastUtils.showToastInUiThread(context, "aborting: previously applied constraint changed") - sendError("aborting: previously applied constraint changed") - return - } - doFillBolus(amount) - } else if ("temptarget" == act[0]) { - val duration = SafeParse.stringToInt(act[2]) - val low = SafeParse.stringToDouble(act[3]) - val high = SafeParse.stringToDouble(act[4]) - generateTempTarget(duration, low, high) - } else if ("wizard2" == act[0]) { - if (lastBolusWizard != null) { //use last calculation as confirmed string matches - doBolus(lastBolusWizard!!.calculatedTotalInsulin, lastBolusWizard!!.carbs, null, 0) - lastBolusWizard = null - } - } else if ("bolus" == act[0]) { - val insulin = SafeParse.stringToDouble(act[1]) - val carbs = SafeParse.stringToInt(act[2]) - doBolus(insulin, carbs, null, 0) - } else if ("cppset" == act[0]) { - val timeshift = SafeParse.stringToInt(act[1]) - val percentage = SafeParse.stringToInt(act[2]) - setCPP(timeshift, percentage) - } else if ("ecarbs" == act[0]) { - val carbs = SafeParse.stringToInt(act[1]) - val starttime = SafeParse.stringToLong(act[2]) - val duration = SafeParse.stringToInt(act[3]) - doECarbs(carbs, starttime, duration) - } else if ("dismissoverviewnotification" == act[0]) { - rxBus.send(EventDismissNotification(SafeParse.stringToInt(act[1]))) - } else if ("changeRequest" == act[0]) { - loop.acceptChangeRequest() - val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager - notificationManager.cancel(Constants.notificationID) - } - lastBolusWizard = null - } - - private fun setCPP(timeshift: Int, percentage: Int) { - var msg = "" - //check for validity - if (percentage < Constants.CPP_MIN_PERCENTAGE || percentage > Constants.CPP_MAX_PERCENTAGE) { - msg += rh.gs(R.string.valueoutofrange, "Profile-Percentage") + "\n" - } - if (timeshift < 0 || timeshift > 23) { - msg += rh.gs(R.string.valueoutofrange, "Profile-Timeshift") + "\n" - } - val profile = profileFunction.getProfile() - if (profile == null) { - msg += rh.gs(R.string.notloadedplugins) + "\n" - } - if ("" != msg) { - msg += rh.gs(R.string.valuesnotstored) - val rTitle = "STATUS" - val rAction = "statusmessage" - wearPlugin.requestActionConfirmation(rTitle, msg, rAction) - lastSentTimestamp = System.currentTimeMillis() - lastConfirmActionString = rAction - return - } - //send profile to pump - uel.log(Action.PROFILE_SWITCH, Sources.Wear, - ValueWithUnit.Percent(percentage), - ValueWithUnit.Hour(timeshift).takeIf { timeshift != 0 }) - profileFunction.createProfileSwitch(0, percentage, timeshift) - } - - private fun generateTempTarget(duration: Int, low: Double, high: Double) { - if (duration != 0) { - disposable += repository.runTransactionForResult( - InsertAndCancelCurrentTemporaryTargetTransaction( - timestamp = System.currentTimeMillis(), - duration = TimeUnit.MINUTES.toMillis(duration.toLong()), - reason = TemporaryTarget.Reason.WEAR, - lowTarget = Profile.toMgdl(low, profileFunction.getUnits()), - highTarget = Profile.toMgdl(high, profileFunction.getUnits()) - ) - ).subscribe({ result -> - result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) - }) - uel.log( - Action.TT, Sources.Wear, - ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.WEAR), - ValueWithUnit.fromGlucoseUnit(low, profileFunction.getUnits().asText), - ValueWithUnit.fromGlucoseUnit(high, profileFunction.getUnits().asText).takeIf { low != high }, - ValueWithUnit.Minute(duration) - ) - } else { - disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(System.currentTimeMillis())) - .subscribe({ result -> - result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } - }, { - aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) - }) - uel.log( - Action.CANCEL_TT, Sources.Wear, - ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.WEAR) - ) - } - } - - private fun doFillBolus(amount: Double) { - val detailedBolusInfo = DetailedBolusInfo() - detailedBolusInfo.insulin = amount - detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.PRIMING - uel.log(Action.PRIME_BOLUS, Sources.Wear, - ValueWithUnit.Insulin(amount).takeIf { amount != 0.0 }) - commandQueue.bolus(detailedBolusInfo, object : Callback() { - override fun run() { - if (!result.success) { - sendError( - rh.gs(R.string.treatmentdeliveryerror) + - "\n" + - result.comment - ) - } - } - }) - } - - private fun doECarbs(carbs: Int, time: Long, duration: Int) { - uel.log(if (duration == 0) Action.CARBS else Action.EXTENDED_CARBS, Sources.Wear, - ValueWithUnit.Timestamp(time), - ValueWithUnit.Gram(carbs), - ValueWithUnit.Hour(duration).takeIf { duration != 0 }) - doBolus(0.0, carbs, time, duration) - } - - private fun doBolus(amount: Double, carbs: Int, carbsTime: Long?, carbsDuration: Int) { - val detailedBolusInfo = DetailedBolusInfo() - detailedBolusInfo.insulin = amount - detailedBolusInfo.carbs = carbs.toDouble() - detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.NORMAL - detailedBolusInfo.carbsTimestamp = carbsTime - detailedBolusInfo.carbsDuration = T.hours(carbsDuration.toLong()).msecs() - if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { - val action = when { - amount.equals(0.0) -> Action.CARBS - carbs.equals(0) -> Action.BOLUS - carbsDuration > 0 -> Action.EXTENDED_CARBS - else -> Action.TREATMENT - } - uel.log(action, Sources.Wear, - ValueWithUnit.Insulin(amount).takeIf { amount != 0.0 }, - ValueWithUnit.Gram(carbs).takeIf { carbs != 0 }, - ValueWithUnit.Hour(carbsDuration).takeIf { carbsDuration != 0 }) - commandQueue.bolus(detailedBolusInfo, object : Callback() { - override fun run() { - if (!result.success) { - sendError( - rh.gs(R.string.treatmentdeliveryerror) + - "\n" + - result.comment - ) - } - } - }) - } - } - - @Synchronized private fun sendError(errorMessage: String) { - wearPlugin.requestActionConfirmation("ERROR", errorMessage, "error") - lastSentTimestamp = System.currentTimeMillis() - lastConfirmActionString = null - lastBolusWizard = null - } - - @Synchronized - private fun sendStatusMessage(message: String) { - wearPlugin.requestActionConfirmation("TDD", message, "statusmessage") - lastSentTimestamp = System.currentTimeMillis() - lastConfirmActionString = null - lastBolusWizard = null - } -} diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearFragment.kt index 91ed047770..0cad0dcd55 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearFragment.kt @@ -6,14 +6,29 @@ import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.databinding.WearFragmentBinding +import info.nightscout.androidaps.events.EventMobileToWear +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.plugins.general.nsclient.events.EventNSClientUpdateGUI +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.FabricPrivacy +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.weardata.EventData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject class WearFragment : DaggerFragment() { @Inject lateinit var wearPlugin: WearPlugin + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var fabricPrivacy: FabricPrivacy + @Inject lateinit var dateUtil: DateUtil private var _binding: WearFragmentBinding? = null + private val disposable = CompositeDisposable() + // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! @@ -26,8 +41,22 @@ class WearFragment : DaggerFragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) - binding.resend.setOnClickListener { wearPlugin.resendDataToWatch() } - binding.opensettings.setOnClickListener { wearPlugin.openSettings() } + binding.resend.setOnClickListener { rxBus.send(EventData.ActionResendData("WearFragment")) } + binding.openSettings.setOnClickListener { rxBus.send(EventMobileToWear(EventData.OpenSettings(dateUtil.now()))) } + } + + override fun onResume() { + super.onResume() + disposable += rxBus + .toObservable(EventNSClientUpdateGUI::class.java) + .observeOn(aapsSchedulers.main) + .subscribe({ updateGui() }, fabricPrivacy::logException) + updateGui() + } + + override fun onPause() { + super.onPause() + disposable.clear() } @Synchronized @@ -35,4 +64,9 @@ class WearFragment : DaggerFragment() { super.onDestroyView() _binding = null } + + fun updateGui() { + _binding ?: return + binding.connectedDevice.text = wearPlugin.connectedDevice + } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt index 43b4130778..61f0558009 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/WearPlugin.kt @@ -2,25 +2,28 @@ package info.nightscout.androidaps.plugins.general.wear import android.content.Context import android.content.Intent -import dagger.Lazy import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R -import info.nightscout.androidaps.events.* -import info.nightscout.androidaps.interfaces.Loop +import info.nightscout.androidaps.events.EventAutosensCalculationFinished +import info.nightscout.androidaps.events.EventMobileToWear +import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.interfaces.PluginBase import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.androidaps.plugins.aps.events.EventOpenAPSUpdateGui +import info.nightscout.androidaps.plugins.aps.loop.events.EventLoopUpdateGui import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress -import info.nightscout.androidaps.plugins.general.wear.wearintegration.WatchUpdaterService +import info.nightscout.androidaps.plugins.general.wear.wearintegration.DataHandlerMobile +import info.nightscout.androidaps.plugins.general.wear.wearintegration.DataLayerListenerServiceMobile import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject import javax.inject.Singleton @@ -31,157 +34,66 @@ class WearPlugin @Inject constructor( rh: ResourceHelper, private val aapsSchedulers: AapsSchedulers, private val sp: SP, - private val ctx: Context, private val fabricPrivacy: FabricPrivacy, - private val loop: Loop, private val rxBus: RxBus, - private val actionStringHandler: Lazy + private val context: Context, + private val dataHandlerMobile: DataHandlerMobile -) : PluginBase(PluginDescription() - .mainType(PluginType.GENERAL) - .fragmentClass(WearFragment::class.java.name) - .pluginIcon(R.drawable.ic_watch) - .pluginName(R.string.wear) - .shortName(R.string.wear_shortname) - .preferencesId(R.xml.pref_wear) - .description(R.string.description_wear), +) : PluginBase( + PluginDescription() + .mainType(PluginType.GENERAL) + .fragmentClass(WearFragment::class.java.name) + .pluginIcon(R.drawable.ic_watch) + .pluginName(R.string.wear) + .shortName(R.string.wear_shortname) + .preferencesId(R.xml.pref_wear) + .description(R.string.description_wear), aapsLogger, rh, injector ) { private val disposable = CompositeDisposable() + + var connectedDevice = "---" + override fun onStart() { super.onStart() - disposable.add(rxBus - .toObservable(EventOpenAPSUpdateGui::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventExtendedBolusChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventTempBasalChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventTreatmentChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventEffectiveProfileSwitchChanged::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = false, basals = true, bgValue = false) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventAutosensCalculationFinished::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ sendDataToWatch(status = true, basals = true, bgValue = true) }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventPreferenceChange::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - // possibly new high or low mark - resendDataToWatch() - // status may be formatted differently - sendDataToWatch(status = true, basals = false, bgValue = false) - }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventRefreshOverview::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ - if (WatchUpdaterService.shouldReportLoopStatus((loop as PluginBase).isEnabled())) - sendDataToWatch(status = true, basals = false, bgValue = false) - }, fabricPrivacy::logException)) - disposable.add(rxBus - .toObservable(EventBolusRequested::class.java) - .observeOn(aapsSchedulers.io) - .subscribe({ event: EventBolusRequested -> - val status = rh.gs(R.string.bolusrequested, event.amount) - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) - intent.putExtra("progresspercent", 0) - intent.putExtra("progressstatus", status) - ctx.startService(intent) - }, fabricPrivacy::logException)) - disposable.add(rxBus + context.startService(Intent(context, DataLayerListenerServiceMobile::class.java)) + disposable += rxBus .toObservable(EventDismissBolusProgressIfRunning::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventDismissBolusProgressIfRunning -> - if (event.result == null) return@subscribe - val status: String = if (event.result!!.success) { - rh.gs(R.string.success) - } else { - rh.gs(R.string.nosuccess) - } - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) - intent.putExtra("progresspercent", 100) - intent.putExtra("progressstatus", status) - ctx.startService(intent) - }, fabricPrivacy::logException)) - disposable.add(rxBus + event.result?.let { + val status = + if (it.success) rh.gs(R.string.success) + else rh.gs(R.string.nosuccess) + if (isEnabled()) rxBus.send(EventMobileToWear(EventData.BolusProgress(percent = 100, status = status))) + } + }, fabricPrivacy::logException) + disposable += rxBus .toObservable(EventOverviewBolusProgress::class.java) .observeOn(aapsSchedulers.io) .subscribe({ event: EventOverviewBolusProgress -> - if (!event.isSMB() || sp.getBoolean("wear_notifySMB", true)) { - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BOLUSPROGRESS) - intent.putExtra("progresspercent", event.percent) - intent.putExtra("progressstatus", event.status) - ctx.startService(intent) - } - }, fabricPrivacy::logException)) - actionStringHandler.get().setup() + if (!event.isSMB() || sp.getBoolean("wear_notifySMB", true)) { + if (isEnabled()) rxBus.send(EventMobileToWear(EventData.BolusProgress(percent = event.percent, status = event.status))) + } + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventPreferenceChange::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ dataHandlerMobile.resendData("EventPreferenceChange") }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventAutosensCalculationFinished::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ dataHandlerMobile.resendData("EventAutosensCalculationFinished") }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventLoopUpdateGui::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ dataHandlerMobile.resendData("EventLoopUpdateGui") }, fabricPrivacy::logException) } override fun onStop() { disposable.clear() super.onStop() - actionStringHandler.get().tearDown() - } - - private fun sendDataToWatch(status: Boolean, basals: Boolean, bgValue: Boolean) { - //Log.d(TAG, "WR: WearPlugin:sendDataToWatch (status=" + status + ",basals=" + basals + ",bgValue=" + bgValue + ")"); - if (isEnabled(getType())) { - // only start service when this plugin is enabled - if (bgValue) { - ctx.startService(Intent(ctx, WatchUpdaterService::class.java)) - } - if (basals) { - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_BASALS)) - } - if (status) { - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_STATUS)) - } - } - } - - fun resendDataToWatch() { - //Log.d(TAG, "WR: WearPlugin:resendDataToWatch"); - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_RESEND)) - } - - fun openSettings() { - //Log.d(TAG, "WR: WearPlugin:openSettings"); - ctx.startService(Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_OPEN_SETTINGS)) - } - - fun requestNotificationCancel(actionString: String?) { //Log.d(TAG, "WR: WearPlugin:requestNotificationCancel"); - val intent = Intent(ctx, WatchUpdaterService::class.java) - .setAction(WatchUpdaterService.ACTION_CANCEL_NOTIFICATION) - intent.putExtra("actionstring", actionString) - ctx.startService(intent) - } - - fun requestActionConfirmation(title: String, message: String, actionString: String) { - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_ACTIONCONFIRMATIONREQUEST) - intent.putExtra("title", title) - intent.putExtra("message", message) - intent.putExtra("actionstring", actionString) - ctx.startService(intent) - } - - fun requestChangeConfirmation(title: String, message: String, actionString: String) { - val intent = Intent(ctx, WatchUpdaterService::class.java).setAction(WatchUpdaterService.ACTION_SEND_CHANGECONFIRMATIONREQUEST) - intent.putExtra("title", title) - intent.putExtra("message", message) - intent.putExtra("actionstring", actionString) - ctx.startService(intent) + context.stopService(Intent(context, DataLayerListenerServiceMobile::class.java)) } } \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearInitiateAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearInitiateAction.kt deleted file mode 100644 index 9661c4af38..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearInitiateAction.kt +++ /dev/null @@ -1,5 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear.events - -import info.nightscout.androidaps.events.Event - -class EventWearInitiateAction(val action: String) : Event() diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt similarity index 65% rename from app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt rename to app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt index 211836d27d..4736566059 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearConfirmAction.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/events/EventWearUpdateGui.kt @@ -2,4 +2,4 @@ package info.nightscout.androidaps.plugins.general.wear.events import info.nightscout.androidaps.events.Event -class EventWearConfirmAction(val action: String) : Event() \ No newline at end of file +class EventWearUpdateGui : Event() \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataHandlerMobile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataHandlerMobile.kt new file mode 100644 index 0000000000..045e147e2b --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataHandlerMobile.kt @@ -0,0 +1,1173 @@ +package info.nightscout.androidaps.plugins.general.wear.wearintegration + +import android.app.NotificationManager +import android.content.Context +import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.Constants +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.DetailedBolusInfo +import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.database.ValueWrapper +import info.nightscout.androidaps.database.entities.* +import info.nightscout.androidaps.database.interfaces.end +import info.nightscout.androidaps.database.transactions.CancelCurrentTemporaryTargetIfAnyTransaction +import info.nightscout.androidaps.database.transactions.InsertAndCancelCurrentTemporaryTargetTransaction +import info.nightscout.androidaps.events.EventMobileToWear +import info.nightscout.androidaps.extensions.convertedToAbsolute +import info.nightscout.androidaps.extensions.toStringShort +import info.nightscout.androidaps.extensions.total +import info.nightscout.androidaps.extensions.valueToUnits +import info.nightscout.androidaps.extensions.valueToUnitsString +import info.nightscout.androidaps.interfaces.* +import info.nightscout.androidaps.logging.UserEntryLogger +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker +import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus +import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint +import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider +import info.nightscout.androidaps.queue.Callback +import info.nightscout.androidaps.receivers.ReceiverStatusStore +import info.nightscout.androidaps.utils.* +import info.nightscout.androidaps.interfaces.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.wizard.BolusWizard +import info.nightscout.androidaps.utils.wizard.QuickWizard +import info.nightscout.androidaps.utils.wizard.QuickWizardEntry +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import java.text.DateFormat +import java.text.SimpleDateFormat +import java.util.* +import java.util.concurrent.TimeUnit +import java.util.stream.Collectors +import javax.inject.Inject +import javax.inject.Singleton +import kotlin.collections.ArrayList +import kotlin.math.abs +import kotlin.math.min + +@Singleton +class DataHandlerMobile @Inject constructor( + aapsSchedulers: AapsSchedulers, + private val injector: HasAndroidInjector, + private val context: Context, + private val rxBus: RxBus, + private val aapsLogger: AAPSLogger, + private val rh: ResourceHelper, + private val sp: SP, + private val config: Config, + private val iobCobCalculator: IobCobCalculator, + private val repository: AppRepository, + private val glucoseStatusProvider: GlucoseStatusProvider, + private val profileFunction: ProfileFunction, + private val loop: Loop, + private val nsDeviceStatus: NSDeviceStatus, + private val receiverStatusStore: ReceiverStatusStore, + private val quickWizard: QuickWizard, + private val defaultValueHelper: DefaultValueHelper, + private val trendCalculator: TrendCalculator, + private val dateUtil: DateUtil, + private val constraintChecker: ConstraintChecker, + private val uel: UserEntryLogger, + private val activePlugin: ActivePlugin, + private val commandQueue: CommandQueue, + private val fabricPrivacy: FabricPrivacy +) { + + private val disposable = CompositeDisposable() + + private var lastBolusWizard: BolusWizard? = null + + init { + // From Wear + disposable += rxBus + .toObservable(EventData.ActionPong::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "Pong received from ${it.sourceNodeId}") + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.CancelBolus::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "CancelBolus received from ${it.sourceNodeId}") + activePlugin.activePump.stopBolusDelivering() + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.OpenLoopRequestConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "OpenLoopRequestConfirmed received from ${it.sourceNodeId}") + loop.acceptChangeRequest() + (context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).cancel(Constants.notificationID) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionResendData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ResendData received from ${it.sourceNodeId}") + resendData(it.from) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionPumpStatus::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionPumpStatus received from ${it.sourceNodeId}") + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.medtronic_pump_status).uppercase(), + activePlugin.activePump.shortStatus(false), + returnCommand = null + ) + ) + ) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionLoopStatus::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionLoopStatus received from ${it.sourceNodeId}") + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.loop_status).uppercase(), + "TARGETS:\n$targetsStatus\n\n$loopStatus\n\nOAPS RESULT:\n$oAPSResultStatus", + returnCommand = null + ) + ) + ) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionTddStatus::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "ActionTddStatus received from ${it.sourceNodeId}") + handleTddStatus() + } + disposable += rxBus + .toObservable(EventData.ActionProfileSwitchSendInitialData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionProfileSwitchSendInitialData received $it from ${it.sourceNodeId}") + handleProfileSwitchSendInitialData() + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionProfileSwitchPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionProfileSwitchPreCheck received $it from ${it.sourceNodeId}") + handleProfileSwitchPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionProfileSwitchConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionProfileSwitchConfirmed received $it from ${it.sourceNodeId}") + doProfileSwitch(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionTempTargetPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionTempTargetPreCheck received $it from ${it.sourceNodeId}") + handleTempTargetPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionTempTargetConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionTempTargetConfirmed received $it from ${it.sourceNodeId}") + doTempTarget(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionBolusPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionBolusPreCheck received $it from ${it.sourceNodeId}") + handleBolusPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionBolusConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionBolusConfirmed received $it from ${it.sourceNodeId}") + doBolus(it.insulin, it.carbs, null, 0) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionECarbsPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionECarbsPreCheck received $it from ${it.sourceNodeId}") + handleECarbsPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionECarbsConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionECarbsConfirmed received $it from ${it.sourceNodeId}") + doECarbs(it.carbs, it.carbsTime, it.duration) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionFillPresetPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionFillPresetPreCheck received $it from ${it.sourceNodeId}") + handleFillPresetPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionFillPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionFillPreCheck received $it from ${it.sourceNodeId}") + handleFillPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionFillConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionFillConfirmed received $it from ${it.sourceNodeId}") + if (constraintChecker.applyBolusConstraints(Constraint(it.insulin)).value() - it.insulin != 0.0) { + ToastUtils.showToastInUiThread(context, "aborting: previously applied constraint changed") + sendError("aborting: previously applied constraint changed") + } else + doFillBolus(it.insulin) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionQuickWizardPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionWizardPreCheck received $it from ${it.sourceNodeId}") + handleQuickWizardPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionWizardPreCheck::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionWizardPreCheck received $it from ${it.sourceNodeId}") + handleWizardPreCheck(it) + }, fabricPrivacy::logException) + disposable += rxBus + .toObservable(EventData.ActionWizardConfirmed::class.java) + .observeOn(aapsSchedulers.io) + .subscribe({ + aapsLogger.debug(LTag.WEAR, "ActionWizardConfirmed received $it from ${it.sourceNodeId}") + if (lastBolusWizard?.timeStamp == it.timeStamp) { //use last calculation as confirmed string matches + doBolus(lastBolusWizard!!.calculatedTotalInsulin, lastBolusWizard!!.carbs, null, 0) + } + lastBolusWizard = null + }, fabricPrivacy::logException) + } + + private fun handleTddStatus() { + val activePump = activePlugin.activePump + var message: String + // check if DB up to date + val dummies: MutableList = LinkedList() + val historyList = getTDDList(dummies) + if (isOldData(historyList)) { + message = "OLD DATA - " + //if pump is not busy: try to fetch data + if (activePump.isBusy()) { + message += rh.gs(R.string.pumpbusy) + } else { + message += "trying to fetch data from pump." + commandQueue.loadTDDs(object : Callback() { + override fun run() { + val dummies1: MutableList = LinkedList() + val historyList1 = getTDDList(dummies1) + val reloadMessage = + if (isOldData(historyList1)) + "TDD: Still old data! Cannot load from pump.\n" + generateTDDMessage(historyList1, dummies1) + else + generateTDDMessage(historyList1, dummies1) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.tdd), + reloadMessage, + returnCommand = null + ) + ) + ) + } + }) + } + } else { // if up to date: prepare, send (check if CPP is activated -> add CPP stats) + message = generateTDDMessage(historyList, dummies) + } + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.tdd), + message, + returnCommand = null + ) + ) + ) + } + + private fun handleWizardPreCheck(command: EventData.ActionWizardPreCheck) { + val pump = activePlugin.activePump + if (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected) { + sendError(rh.gs(R.string.wizard_pump_not_available)) + return + } + val carbsBeforeConstraints = command.carbs + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(carbsBeforeConstraints)).value() + if (carbsAfterConstraints - carbsBeforeConstraints != 0) { + sendError(rh.gs(R.string.wizard_carbs_constraint)) + return + } + val useBG = sp.getBoolean(R.string.key_wearwizard_bg, true) + val useTT = sp.getBoolean(R.string.key_wearwizard_tt, false) + val useBolusIOB = sp.getBoolean(R.string.key_wearwizard_bolusiob, true) + val useBasalIOB = sp.getBoolean(R.string.key_wearwizard_basaliob, true) + val useCOB = sp.getBoolean(R.string.key_wearwizard_cob, true) + val useTrend = sp.getBoolean(R.string.key_wearwizard_trend, false) + val percentage = command.percentage + val profile = profileFunction.getProfile() + val profileName = profileFunction.getProfileName() + if (profile == null) { + sendError(rh.gs(R.string.wizard_no_active_profile)) + return + } + val bgReading = iobCobCalculator.ads.actualBg() + if (bgReading == null) { + sendError(rh.gs(R.string.wizard_no_actual_bg)) + return + } + val cobInfo = iobCobCalculator.getCobInfo(false, "Wizard wear") + if (cobInfo.displayCob == null) { + sendError(rh.gs(R.string.wizard_no_cob)) + return + } + val dbRecord = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() + val tempTarget = if (dbRecord is ValueWrapper.Existing) dbRecord.value else null + + val bolusWizard = BolusWizard(injector).doCalc( + profile, profileName, tempTarget, + carbsAfterConstraints, cobInfo.displayCob!!, bgReading.valueToUnits(profileFunction.getUnits()), + 0.0, percentage, useBG, useCOB, useBolusIOB, useBasalIOB, false, useTT, useTrend, false + ) + val insulinAfterConstraints = bolusWizard.insulinAfterConstraints + val minStep = pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints) + if (abs(insulinAfterConstraints - bolusWizard.calculatedTotalInsulin) >= minStep) { + sendError(rh.gs(R.string.wizard_constraint_bolus_size, bolusWizard.calculatedTotalInsulin)) + return + } + if (bolusWizard.calculatedTotalInsulin <= 0 && bolusWizard.carbs <= 0) { + sendError("No insulin required") + return + } + val message = + rh.gs(R.string.wizard_result, bolusWizard.calculatedTotalInsulin, bolusWizard.carbs) + "\n_____________\n" + bolusWizard.explainShort() + lastBolusWizard = bolusWizard + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionWizardConfirmed(bolusWizard.timeStamp) + ) + ) + ) + } + + private fun handleQuickWizardPreCheck(command: EventData.ActionQuickWizardPreCheck) { + val actualBg = iobCobCalculator.ads.actualBg() + val profile = profileFunction.getProfile() + val profileName = profileFunction.getProfileName() + val quickWizardEntry = quickWizard.get(command.guid) + //Log.i("QuickWizard", "handleInitiate: quick_wizard " + quickWizardEntry?.buttonText() + " c " + quickWizardEntry?.carbs()) + if (quickWizardEntry == null) { + sendError(rh.gs(R.string.quick_wizard_not_available)) + return + } + if (actualBg == null) { + sendError(rh.gs(R.string.wizard_no_actual_bg)) + return + } + if (profile == null) { + sendError(rh.gs(R.string.wizard_no_active_profile)) + return + } + val cobInfo = iobCobCalculator.getCobInfo(false, "QuickWizard wear") + if (cobInfo.displayCob == null) { + sendError(rh.gs(R.string.wizard_no_cob)) + return + } + val pump = activePlugin.activePump + if (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected) { + sendError(rh.gs(R.string.wizard_pump_not_available)) + return + } + + val wizard = quickWizardEntry.doCalc(profile, profileName, actualBg, true) + + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(quickWizardEntry.carbs())).value() + if (carbsAfterConstraints != quickWizardEntry.carbs()) { + sendError(rh.gs(R.string.wizard_carbs_constraint)) + return + } + val insulinAfterConstraints = wizard.insulinAfterConstraints + val minStep = pump.pumpDescription.pumpType.determineCorrectBolusStepSize(insulinAfterConstraints) + if (abs(insulinAfterConstraints - wizard.calculatedTotalInsulin) >= minStep) { + sendError(rh.gs(R.string.wizard_constraint_bolus_size, wizard.calculatedTotalInsulin)) + return + } + + val message = rh.gs(R.string.quick_wizard_message, quickWizardEntry.buttonText(), wizard.calculatedTotalInsulin, quickWizardEntry.carbs()) + + "\n_____________\n" + wizard.explainShort() + + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionBolusConfirmed(insulinAfterConstraints, carbsAfterConstraints) + ) + ) + ) + } + + private fun handleBolusPreCheck(command: EventData.ActionBolusPreCheck) { + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(command.insulin)).value() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(command.carbs)).value() + val pump = activePlugin.activePump + if (insulinAfterConstraints > 0 && (!pump.isInitialized() || pump.isSuspended() || loop.isDisconnected)) { + sendError(rh.gs(R.string.wizard_pump_not_available)) + return + } + var message = "" + message += rh.gs(R.string.bolus) + ": " + insulinAfterConstraints + "U\n" + message += rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" + if (insulinAfterConstraints - command.insulin != 0.0 || carbsAfterConstraints - command.carbs != 0) + message += "\n" + rh.gs(R.string.constraintapllied) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionBolusConfirmed(insulinAfterConstraints, carbsAfterConstraints) + ) + ) + ) + } + + private fun handleECarbsPreCheck(command: EventData.ActionECarbsPreCheck) { + val startTimeStamp = System.currentTimeMillis() + T.hours(command.carbsTimeShift.toLong()).msecs() + val carbsAfterConstraints = constraintChecker.applyCarbsConstraints(Constraint(command.carbs)).value() + var message = rh.gs(R.string.carbs) + ": " + carbsAfterConstraints + "g" + + "\n" + rh.gs(R.string.time) + ": " + dateUtil.timeString(startTimeStamp) + + "\n" + rh.gs(R.string.duration) + ": " + command.duration + "h" + if (carbsAfterConstraints - command.carbs != 0) { + message += "\n" + rh.gs(R.string.constraintapllied) + } + if (carbsAfterConstraints <= 0) { + sendError("Carbs = 0! No action taken!") + return + } + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionECarbsConfirmed(carbsAfterConstraints, startTimeStamp, command.duration) + ) + ) + ) + } + + private fun handleFillPresetPreCheck(command: EventData.ActionFillPresetPreCheck) { + val amount: Double = when (command.button) { + 1 -> sp.getDouble("fill_button1", 0.3) + 2 -> sp.getDouble("fill_button2", 0.0) + 3 -> sp.getDouble("fill_button3", 0.0) + else -> return + } + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(amount)).value() + var message = rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" + if (insulinAfterConstraints - amount != 0.0) message += "\n" + rh.gs(R.string.constraintapllied) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionFillConfirmed(insulinAfterConstraints) + ) + ) + ) + } + + private fun handleFillPreCheck(command: EventData.ActionFillPreCheck) { + val insulinAfterConstraints = constraintChecker.applyBolusConstraints(Constraint(command.insulin)).value() + var message = rh.gs(R.string.primefill) + ": " + insulinAfterConstraints + "U" + if (insulinAfterConstraints - command.insulin != 0.0) message += "\n" + rh.gs(R.string.constraintapllied) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionFillConfirmed(insulinAfterConstraints) + ) + ) + ) + } + + private fun handleProfileSwitchSendInitialData() { + val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() + if (activeProfileSwitch is ValueWrapper.Existing) { // read CPP values + rxBus.send( + EventMobileToWear(EventData.ActionProfileSwitchOpenActivity(T.msecs(activeProfileSwitch.value.originalTimeshift).hours().toInt(), activeProfileSwitch.value.originalPercentage)) + ) + } else { + sendError("No active profile switch!") + return + } + + } + + private fun handleProfileSwitchPreCheck(command: EventData.ActionProfileSwitchPreCheck) { + val activeProfileSwitch = repository.getEffectiveProfileSwitchActiveAt(dateUtil.now()).blockingGet() + if (activeProfileSwitch is ValueWrapper.Absent) { + sendError("No active profile switch!") + } + if (command.percentage < Constants.CPP_MIN_PERCENTAGE || command.percentage > Constants.CPP_MAX_PERCENTAGE) { + sendError(rh.gs(R.string.valueoutofrange, "Profile-Percentage")) + } + if (command.timeShift < 0 || command.timeShift > 23) { + sendError(rh.gs(R.string.valueoutofrange, "Profile-Timeshift")) + } + val message = "Profile:" + "\n\n" + + "Timeshift: " + command.timeShift + "\n" + + "Percentage: " + command.percentage + "%" + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + rh.gs(R.string.confirm).uppercase(), message, + returnCommand = EventData.ActionProfileSwitchConfirmed(command.timeShift, command.percentage) + ) + ) + ) + } + + private fun handleTempTargetPreCheck(action: EventData.ActionTempTargetPreCheck) { + val title = rh.gs(R.string.confirm).uppercase() + var message = "" + val presetIsMGDL = profileFunction.getUnits() == GlucoseUnit.MGDL + when (action.command) { + EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_ACTIVITY -> { + val activityTTDuration = defaultValueHelper.determineActivityTTDuration() + val activityTT = defaultValueHelper.determineActivityTT() + val reason = rh.gs(R.string.activity) + message += rh.gs(R.string.wear_action_tempt_preset_message, reason, activityTT, activityTTDuration) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(presetIsMGDL, activityTTDuration, activityTT, activityTT) + ) + ) + ) + } + + EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_HYPO -> { + val hypoTTDuration = defaultValueHelper.determineHypoTTDuration() + val hypoTT = defaultValueHelper.determineHypoTT() + val reason = rh.gs(R.string.hypo) + message += rh.gs(R.string.wear_action_tempt_preset_message, reason, hypoTT, hypoTTDuration) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(presetIsMGDL, hypoTTDuration, hypoTT, hypoTT) + ) + ) + ) + } + + EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_EATING -> { + val eatingSoonTTDuration = defaultValueHelper.determineEatingSoonTTDuration() + val eatingSoonTT = defaultValueHelper.determineEatingSoonTT() + val reason = rh.gs(R.string.eatingsoon) + message += rh.gs(R.string.wear_action_tempt_preset_message, reason, eatingSoonTT, eatingSoonTTDuration) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(presetIsMGDL, eatingSoonTTDuration, eatingSoonTT, eatingSoonTT) + ) + ) + ) + } + + EventData.ActionTempTargetPreCheck.TempTargetCommand.CANCEL -> { + message += rh.gs(R.string.wear_action_tempt_cancel_message) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(true, 0, 0.0, 0.0) + ) + ) + ) + } + + EventData.ActionTempTargetPreCheck.TempTargetCommand.MANUAL -> { + if (profileFunction.getUnits() == GlucoseUnit.MGDL != action.isMgdl) { + sendError(rh.gs(R.string.wear_action_tempt_unit_error)) + return + } + if (action.duration == 0) { + message += rh.gs(R.string.wear_action_tempt_zero_message) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(true, 0, 0.0, 0.0) + ) + ) + ) + } else { + var low = action.low + var high = action.high + if (!action.isMgdl) { + low *= Constants.MMOLL_TO_MGDL + high *= Constants.MMOLL_TO_MGDL + } + if (low < HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[0] || low > HardLimits.VERY_HARD_LIMIT_TEMP_MIN_BG[1]) { + sendError(rh.gs(R.string.wear_action_tempt_min_bg_error)) + return + } + if (high < HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[0] || high > HardLimits.VERY_HARD_LIMIT_TEMP_MAX_BG[1]) { + sendError(rh.gs(R.string.wear_action_tempt_max_bg_error)) + return + } + message += if (low == high) rh.gs(R.string.wear_action_tempt_manual_message, action.low, action.duration) + else rh.gs(R.string.wear_action_tempt_manual_range_message, action.low, action.high, action.duration) + rxBus.send( + EventMobileToWear( + EventData.ConfirmAction( + title, message, + returnCommand = EventData.ActionTempTargetConfirmed(presetIsMGDL, action.duration, action.low, action.high) + ) + ) + ) + } + } + } + } + + private fun QuickWizardEntry.toWear(): EventData.QuickWizard.QuickWizardEntry = + EventData.QuickWizard.QuickWizardEntry( + guid = guid(), + buttonText = buttonText(), + carbs = carbs(), + validFrom = validFrom(), + validTo = validTo() + ) + + fun resendData(from: String) { + aapsLogger.debug(LTag.WEAR, "Sending data to wear from $from") + // SingleBg + iobCobCalculator.ads.lastBg()?.let { rxBus.send(EventMobileToWear(getSingleBG(it))) } + // Preferences + rxBus.send( + EventMobileToWear( + EventData.Preferences( + timeStamp = System.currentTimeMillis(), + wearControl = sp.getBoolean(R.string.key_wear_control, false), + unitsMgdl = profileFunction.getUnits() == GlucoseUnit.MGDL, + bolusPercentage = sp.getInt(R.string.key_boluswizard_percentage, 100), + maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48), + maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0) + ) + ) + ) + // QuickWizard + rxBus.send( + EventMobileToWear( + EventData.QuickWizard( + ArrayList(quickWizard.list().filter { it.forDevice(QuickWizardEntry.DEVICE_WATCH) }.map { it.toWear() }) + ) + ) + ) + // GraphData + val startTime = System.currentTimeMillis() - (60000 * 60 * 5.5).toLong() + rxBus.send(EventMobileToWear(EventData.GraphData(ArrayList(repository.compatGetBgReadingsDataFromTime(startTime, true).blockingGet().map { getSingleBG(it) })))) + // Treatments + sendTreatments() + // Status + // Keep status last. Wear start refreshing after status received + sendStatus() + } + + private fun sendTreatments() { + val now = System.currentTimeMillis() + val startTimeWindow = now - (60000 * 60 * 5.5).toLong() + val basals = arrayListOf() + val temps = arrayListOf() + val boluses = arrayListOf() + val predictions = arrayListOf() + val profile = profileFunction.getProfile() ?: return + var beginBasalSegmentTime = startTimeWindow + var runningTime = startTimeWindow + var beginBasalValue = profile.getBasal(beginBasalSegmentTime) + var endBasalValue = beginBasalValue + var tb1 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime) + var tb2: TemporaryBasal? + var tbBefore = beginBasalValue + var tbAmount = beginBasalValue + var tbStart = runningTime + if (tb1 != null) { + val profileTB = profileFunction.getProfile(runningTime) + if (profileTB != null) { + tbAmount = tb1.convertedToAbsolute(runningTime, profileTB) + tbStart = runningTime + } + } + while (runningTime < now) { + val profileTB = profileFunction.getProfile(runningTime) ?: return + //basal rate + endBasalValue = profile.getBasal(runningTime) + if (endBasalValue != beginBasalValue) { + //push the segment we recently left + basals.add(EventData.TreatmentData.Basal(beginBasalSegmentTime, runningTime, beginBasalValue)) + + //begin new Basal segment + beginBasalSegmentTime = runningTime + beginBasalValue = endBasalValue + } + + //temps + tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime) + if (tb1 == null && tb2 == null) { + //no temp stays no temp + } else if (tb1 != null && tb2 == null) { + //temp is over -> push it + temps.add(EventData.TreatmentData.TempBasal(tbStart, tbBefore, runningTime, endBasalValue, tbAmount)) + tb1 = null + } else if (tb1 == null && tb2 != null) { + //temp begins + tb1 = tb2 + tbStart = runningTime + tbBefore = endBasalValue + tbAmount = tb1.convertedToAbsolute(runningTime, profileTB) + } else if (tb1 != null && tb2 != null) { + val currentAmount = tb2.convertedToAbsolute(runningTime, profileTB) + if (currentAmount != tbAmount) { + temps.add(EventData.TreatmentData.TempBasal(tbStart, tbBefore, runningTime, currentAmount, tbAmount)) + tbStart = runningTime + tbBefore = tbAmount + tbAmount = currentAmount + tb1 = tb2 + } + } + runningTime += (5 * 60 * 1000).toLong() + } + if (beginBasalSegmentTime != runningTime) { + //push the remaining segment + basals.add(EventData.TreatmentData.Basal(beginBasalSegmentTime, runningTime, beginBasalValue)) + } + if (tb1 != null) { + tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now) //use "now" to express current situation + if (tb2 == null) { + //express the cancelled temp by painting it down one minute early + temps.add(EventData.TreatmentData.TempBasal(tbStart, tbBefore, now - 60 * 1000, endBasalValue, tbAmount)) + } else { + //express currently running temp by painting it a bit into the future + val profileNow = profileFunction.getProfile(now) + val currentAmount = tb2.convertedToAbsolute(now, profileNow!!) + if (currentAmount != tbAmount) { + temps.add(EventData.TreatmentData.TempBasal(tbStart, tbBefore, now, tbAmount, tbAmount)) + temps.add(EventData.TreatmentData.TempBasal(now, tbAmount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)) + } else { + temps.add(EventData.TreatmentData.TempBasal(tbStart, tbBefore, runningTime + 5 * 60 * 1000, tbAmount, tbAmount)) + } + } + } else { + tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now) //use "now" to express current situation + if (tb2 != null) { + //onset at the end + val profileTB = profileFunction.getProfile(runningTime) + val currentAmount = tb2.convertedToAbsolute(runningTime, profileTB!!) + temps.add(EventData.TreatmentData.TempBasal(now - 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)) + } + } + repository.getBolusesIncludingInvalidFromTime(startTimeWindow, true).blockingGet() + .stream() + .filter { (_, _, _, _, _, _, _, _, _, type) -> type !== Bolus.Type.PRIMING } + .forEach { (_, _, _, isValid, _, _, timestamp, _, amount, type) -> boluses.add(EventData.TreatmentData.Treatment(timestamp, amount, 0.0, type === Bolus.Type.SMB, isValid)) } + repository.getCarbsDataFromTimeExpanded(startTimeWindow, true).blockingGet() + .forEach { (_, _, _, isValid, _, _, timestamp, _, _, amount) -> boluses.add(EventData.TreatmentData.Treatment(timestamp, 0.0, amount, false, isValid)) } + val finalLastRun = loop.lastRun + if (sp.getBoolean("wear_predictions", true) && finalLastRun?.request?.hasPredictions == true && finalLastRun.constraintsProcessed != null) { + val predArray = finalLastRun.constraintsProcessed!!.predictions + .stream().map { bg: GlucoseValue -> GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh) } + .collect(Collectors.toList()) + if (predArray.isNotEmpty()) + for (bg in predArray) if (bg.data.value > 39) + predictions.add( + EventData.SingleBg( + timeStamp = bg.data.timestamp, + glucoseUnits = Constants.MGDL, + sgv = bg.data.value, + high = 0.0, + low = 0.0, + color = bg.color(null) + ) + ) + } + rxBus.send(EventMobileToWear(EventData.TreatmentData(temps, basals, boluses, predictions))) + } + + private fun sendStatus() { + val profile = profileFunction.getProfile() + var status = rh.gs(R.string.noprofile) + var iobSum = "" + var iobDetail = "" + var cobString = "" + var currentBasal = "" + var bgiString = "" + if (profile != null) { + val bolusIob = iobCobCalculator.calculateIobFromBolus().round() + val basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round() + iobSum = DecimalFormatter.to2Decimal(bolusIob.iob + basalIob.basaliob) + iobDetail = "(${DecimalFormatter.to2Decimal(bolusIob.iob)}|${DecimalFormatter.to2Decimal(basalIob.basaliob)})" + cobString = iobCobCalculator.getCobInfo(false, "WatcherUpdaterService").generateCOBString() + currentBasal = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis())?.toStringShort() ?: DecimalFormatter.to2Decimal(profile.getBasal()) + "U/h" + + //bgi + val bgi = -(bolusIob.activity + basalIob.activity) * 5 * Profile.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()) + bgiString = "" + (if (bgi >= 0) "+" else "") + DecimalFormatter.to1Decimal(bgi) + status = generateStatusString(profile, currentBasal, iobSum, iobDetail, bgiString) + } + + //batteries + val phoneBattery = receiverStatusStore.batteryLevel + val rigBattery = nsDeviceStatus.uploaderStatus.trim { it <= ' ' } + //OpenAPS status + val openApsStatus = + if (config.APS) loop.lastRun?.let { if (it.lastTBREnact != 0L) it.lastTBREnact else -1 } ?: -1 + else nsDeviceStatus.openApsTimestamp + + rxBus.send( + EventMobileToWear( + EventData.Status( + externalStatus = status, + iobSum = iobSum, + iobDetail = iobDetail, + detailedIob = sp.getBoolean(R.string.key_wear_detailediob, false), + cob = cobString, + currentBasal = currentBasal, + battery = phoneBattery.toString(), + rigBattery = rigBattery, + openApsStatus = openApsStatus, + bgi = bgiString, + showBgi = sp.getBoolean(R.string.key_wear_showbgi, false), + batteryLevel = if (phoneBattery >= 30) 1 else 0 + ) + ) + ) + } + + private fun deltaString(deltaMGDL: Double, deltaMMOL: Double, units: GlucoseUnit): String { + val detailed = sp.getBoolean(R.string.key_wear_detailed_delta, false) + var deltaString = if (deltaMGDL >= 0) "+" else "-" + deltaString += if (units == GlucoseUnit.MGDL) { + if (detailed) DecimalFormatter.to1Decimal(abs(deltaMGDL)) else DecimalFormatter.to0Decimal(abs(deltaMGDL)) + } else { + if (detailed) DecimalFormatter.to2Decimal(abs(deltaMMOL)) else DecimalFormatter.to1Decimal(abs(deltaMMOL)) + } + return deltaString + } + + private fun getSingleBG(glucoseValue: GlucoseValue): EventData.SingleBg { + val glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(true) + val units = profileFunction.getUnits() + val lowLine = Profile.toMgdl(defaultValueHelper.determineLowLine(), units) + val highLine = Profile.toMgdl(defaultValueHelper.determineHighLine(), units) + + return EventData.SingleBg( + timeStamp = glucoseValue.timestamp, + sgvString = glucoseValue.valueToUnitsString(units), + glucoseUnits = units.asText, + slopeArrow = trendCalculator.getTrendArrow(glucoseValue).symbol, + delta = glucoseStatus?.let { deltaString(it.delta, it.delta * Constants.MGDL_TO_MMOLL, units) } ?: "--", + avgDelta = glucoseStatus?.let { deltaString(it.shortAvgDelta, it.shortAvgDelta * Constants.MGDL_TO_MMOLL, units) } ?: "--", + sgvLevel = if (glucoseValue.value > highLine) 1L else if (glucoseValue.value < lowLine) -1L else 0L, + sgv = glucoseValue.value, + high = highLine, + low = lowLine, + color = 0 + ) + } + + //Check for Temp-Target: + private + val targetsStatus: String + get() { + var ret = "" + if (!config.APS) { + return "Targets only apply in APS mode!" + } + val profile = profileFunction.getProfile() ?: return "No profile set :(" + //Check for Temp-Target: + val tempTarget = repository.getTemporaryTargetActiveAt(dateUtil.now()).blockingGet() + if (tempTarget is ValueWrapper.Existing) { + ret += "Temp Target: " + Profile.toTargetRangeString(tempTarget.value.lowTarget, tempTarget.value.lowTarget, GlucoseUnit.MGDL, profileFunction.getUnits()) + ret += "\nuntil: " + dateUtil.timeString(tempTarget.value.end) + ret += "\n\n" + } + ret += "DEFAULT RANGE: " + ret += Profile.fromMgdlToUnits(profile.getTargetLowMgdl(), profileFunction.getUnits()).toString() + " - " + Profile.fromMgdlToUnits( + profile.getTargetHighMgdl(), + profileFunction.getUnits() + ) + ret += " target: " + Profile.fromMgdlToUnits(profile.getTargetMgdl(), profileFunction.getUnits()) + return ret + } + + private + val oAPSResultStatus: String + get() { + var ret = "" + if (!config.APS) + return "Only apply in APS mode!" + val usedAPS = activePlugin.activeAPS + val result = usedAPS.lastAPSResult ?: return "Last result not available!" + ret += if (!result.isChangeRequested) { + rh.gs(R.string.nochangerequested) + "\n" + } else if (result.rate == 0.0 && result.duration == 0) { + rh.gs(R.string.canceltemp) + "\n" + } else { + rh.gs(R.string.rate) + ": " + DecimalFormatter.to2Decimal(result.rate) + " U/h " + + "(" + DecimalFormatter.to2Decimal(result.rate / activePlugin.activePump.baseBasalRate * 100) + "%)\n" + + rh.gs(R.string.duration) + ": " + DecimalFormatter.to0Decimal(result.duration.toDouble()) + " min\n" + } + ret += "\n" + rh.gs(R.string.reason) + ": " + result.reason + return ret + } + + // decide if enabled/disabled closed/open; what Plugin as APS? + private + val loopStatus: String + get() { + var ret = "" + // decide if enabled/disabled closed/open; what Plugin as APS? + if ((loop as PluginBase).isEnabled()) { + ret += if (constraintChecker.isClosedLoopAllowed().value()) { + "CLOSED LOOP\n" + } else { + "OPEN LOOP\n" + } + val aps = activePlugin.activeAPS + ret += "APS: " + (aps as PluginBase).name + val lastRun = loop.lastRun + if (lastRun != null) { + ret += "\nLast Run: " + dateUtil.timeString(lastRun.lastAPSRun) + if (lastRun.lastTBREnact != 0L) ret += "\nLast Enact: " + dateUtil.timeString(lastRun.lastTBREnact) + } + } else { + ret += "LOOP DISABLED\n" + } + return ret + } + + private fun isOldData(historyList: List): Boolean { + val startsYesterday = activePlugin.activePump.pumpDescription.supportsTDDs + val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) + return historyList.size < 3 || df.format(Date(historyList[0].timestamp)) != df.format(Date(System.currentTimeMillis() - if (startsYesterday) 1000 * 60 * 60 * 24 else 0)) + } + + private fun getTDDList(returnDummies: MutableList): MutableList { + var historyList = repository.getLastTotalDailyDoses(10, false).blockingGet().toMutableList() + //var historyList = databaseHelper.getTDDs().toMutableList() + historyList = historyList.subList(0, min(10, historyList.size)) + //fill single gaps - only needed for Dana*R data + val dummies: MutableList = returnDummies + val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) + for (i in 0 until historyList.size - 1) { + val elem1 = historyList[i] + val elem2 = historyList[i + 1] + if (df.format(Date(elem1.timestamp)) != df.format(Date(elem2.timestamp + 25 * 60 * 60 * 1000))) { + val dummy = TotalDailyDose(timestamp = elem1.timestamp - T.hours(24).msecs(), bolusAmount = elem1.bolusAmount / 2, basalAmount = elem1.basalAmount / 2) + dummies.add(dummy) + elem1.basalAmount /= 2.0 + elem1.bolusAmount /= 2.0 + } + } + historyList.addAll(dummies) + historyList.sortWith { lhs, rhs -> (rhs.timestamp - lhs.timestamp).toInt() } + return historyList + } + + private fun generateTDDMessage(historyList: MutableList, dummies: MutableList): String { + val profile = profileFunction.getProfile() ?: return "No profile loaded :(" + if (historyList.isEmpty()) { + return "No history data!" + } + val df: DateFormat = SimpleDateFormat("dd.MM.", Locale.getDefault()) + var message = "" + val refTDD = profile.baseBasalSum() * 2 + if (df.format(Date(historyList[0].timestamp)) == df.format(Date())) { + val tdd = historyList[0].total + historyList.removeAt(0) + message += "Today: " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + "\n" + message += "\n" + } + var weighted03 = 0.0 + var weighted05 = 0.0 + var weighted07 = 0.0 + historyList.reverse() + for ((i, record) in historyList.withIndex()) { + val tdd = record.total + if (i == 0) { + weighted03 = tdd + weighted05 = tdd + weighted07 = tdd + } else { + weighted07 = weighted07 * 0.3 + tdd * 0.7 + weighted05 = weighted05 * 0.5 + tdd * 0.5 + weighted03 = weighted03 * 0.7 + tdd * 0.3 + } + } + message += "weighted:\n" + message += "0.3: " + DecimalFormatter.to2Decimal(weighted03) + "U " + (DecimalFormatter.to0Decimal(100 * weighted03 / refTDD) + "%") + "\n" + message += "0.5: " + DecimalFormatter.to2Decimal(weighted05) + "U " + (DecimalFormatter.to0Decimal(100 * weighted05 / refTDD) + "%") + "\n" + message += "0.7: " + DecimalFormatter.to2Decimal(weighted07) + "U " + (DecimalFormatter.to0Decimal(100 * weighted07 / refTDD) + "%") + "\n" + message += "\n" + historyList.reverse() + //add TDDs: + for (record in historyList) { + val tdd = record.total + message += df.format(Date(record.timestamp)) + " " + DecimalFormatter.to2Decimal(tdd) + "U " + (DecimalFormatter.to0Decimal(100 * tdd / refTDD) + "%") + (if (dummies.contains( + record + ) + ) "x" else "") + "\n" + } + return message + } + + private fun generateStatusString(profile: Profile?, currentBasal: String, iobSum: String, iobDetail: String, bgiString: String): String { + var status = "" + profile ?: return rh.gs(R.string.noprofile) + if (!(loop as PluginBase).isEnabled()) status += rh.gs(R.string.disabledloop) + "\n" + + val iobString = + if (sp.getBoolean(R.string.key_wear_detailediob, false)) "$iobSum $iobDetail" + else iobSum + "U" + + status += "$currentBasal $iobString" + + //add BGI if shown, otherwise return + if (sp.getBoolean(R.string.key_wear_showbgi, false)) status += " $bgiString" + return status + } + + private fun doTempTarget(command: EventData.ActionTempTargetConfirmed) { + if (command.duration != 0) { + disposable += repository.runTransactionForResult( + InsertAndCancelCurrentTemporaryTargetTransaction( + timestamp = System.currentTimeMillis(), + duration = TimeUnit.MINUTES.toMillis(command.duration.toLong()), + reason = TemporaryTarget.Reason.WEAR, + lowTarget = Profile.toMgdl(command.low, profileFunction.getUnits()), + highTarget = Profile.toMgdl(command.high, profileFunction.getUnits()) + ) + ).subscribe({ result -> + result.inserted.forEach { aapsLogger.debug(LTag.DATABASE, "Inserted temp target $it") } + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } + }, { + aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) + }) + uel.log( + UserEntry.Action.TT, UserEntry.Sources.Wear, + ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.WEAR), + ValueWithUnit.fromGlucoseUnit(command.low, profileFunction.getUnits().asText), + ValueWithUnit.fromGlucoseUnit(command.high, profileFunction.getUnits().asText).takeIf { command.low != command.high }, + ValueWithUnit.Minute(command.duration) + ) + } else { + disposable += repository.runTransactionForResult(CancelCurrentTemporaryTargetIfAnyTransaction(System.currentTimeMillis())) + .subscribe({ result -> + result.updated.forEach { aapsLogger.debug(LTag.DATABASE, "Updated temp target $it") } + }, { + aapsLogger.error(LTag.DATABASE, "Error while saving temporary target", it) + }) + uel.log( + UserEntry.Action.CANCEL_TT, UserEntry.Sources.Wear, + ValueWithUnit.TherapyEventTTReason(TemporaryTarget.Reason.WEAR) + ) + } + } + + private fun doBolus(amount: Double, carbs: Int, carbsTime: Long?, carbsDuration: Int) { + val detailedBolusInfo = DetailedBolusInfo() + detailedBolusInfo.insulin = amount + detailedBolusInfo.carbs = carbs.toDouble() + detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.NORMAL + detailedBolusInfo.carbsTimestamp = carbsTime + detailedBolusInfo.carbsDuration = T.hours(carbsDuration.toLong()).msecs() + if (detailedBolusInfo.insulin > 0 || detailedBolusInfo.carbs > 0) { + val action = when { + amount == 0.0 -> UserEntry.Action.CARBS + carbs == 0 -> UserEntry.Action.BOLUS + carbsDuration > 0 -> UserEntry.Action.EXTENDED_CARBS + else -> UserEntry.Action.TREATMENT + } + uel.log(action, UserEntry.Sources.Wear, + ValueWithUnit.Insulin(amount).takeIf { amount != 0.0 }, + ValueWithUnit.Gram(carbs).takeIf { carbs != 0 }, + ValueWithUnit.Hour(carbsDuration).takeIf { carbsDuration != 0 }) + commandQueue.bolus(detailedBolusInfo, object : Callback() { + override fun run() { + if (!result.success) + sendError(rh.gs(R.string.treatmentdeliveryerror) + "\n" + result.comment) + } + }) + } + } + + private fun doFillBolus(amount: Double) { + val detailedBolusInfo = DetailedBolusInfo() + detailedBolusInfo.insulin = amount + detailedBolusInfo.bolusType = DetailedBolusInfo.BolusType.PRIMING + uel.log( + UserEntry.Action.PRIME_BOLUS, UserEntry.Sources.Wear, + ValueWithUnit.Insulin(amount).takeIf { amount != 0.0 }) + commandQueue.bolus(detailedBolusInfo, object : Callback() { + override fun run() { + if (!result.success) { + sendError(rh.gs(R.string.treatmentdeliveryerror) + "\n" + result.comment) + } + } + }) + } + + private fun doECarbs(carbs: Int, carbsTime: Long, duration: Int) { + uel.log(if (duration == 0) UserEntry.Action.CARBS else UserEntry.Action.EXTENDED_CARBS, UserEntry.Sources.Wear, + ValueWithUnit.Timestamp(carbsTime), + ValueWithUnit.Gram(carbs), + ValueWithUnit.Hour(duration).takeIf { duration != 0 }) + doBolus(0.0, carbs, carbsTime, duration) + } + + private fun doProfileSwitch(command: EventData.ActionProfileSwitchConfirmed) { + //check for validity + if (command.percentage < Constants.CPP_MIN_PERCENTAGE || command.percentage > Constants.CPP_MAX_PERCENTAGE) + return + if (command.timeShift < 0 || command.timeShift > 23) + return + profileFunction.getProfile() ?: return + //send profile to pump + uel.log( + UserEntry.Action.PROFILE_SWITCH, UserEntry.Sources.Wear, + ValueWithUnit.Percent(command.percentage), + ValueWithUnit.Hour(command.timeShift).takeIf { command.timeShift != 0 }) + profileFunction.createProfileSwitch(0, command.percentage, command.timeShift) + } + + @Synchronized private fun sendError(errorMessage: String) { + rxBus.send(EventData.ConfirmAction(rh.gs(R.string.error), errorMessage, returnCommand = EventData.Error(dateUtil.now()))) // ignore return path + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt new file mode 100644 index 0000000000..3bc626cd22 --- /dev/null +++ b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/DataLayerListenerServiceMobile.kt @@ -0,0 +1,200 @@ +package info.nightscout.androidaps.plugins.general.wear.wearintegration + +import android.os.Handler +import android.os.HandlerThread +import com.google.android.gms.tasks.Tasks +import com.google.android.gms.wearable.* +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.database.AppRepository +import info.nightscout.androidaps.events.EventMobileToWear +import info.nightscout.androidaps.interfaces.ActivePlugin +import info.nightscout.androidaps.interfaces.Config +import info.nightscout.androidaps.interfaces.IobCobCalculator +import info.nightscout.androidaps.interfaces.Loop +import info.nightscout.androidaps.interfaces.ProfileFunction +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus +import info.nightscout.androidaps.plugins.general.wear.WearPlugin +import info.nightscout.androidaps.plugins.general.wear.events.EventWearUpdateGui +import info.nightscout.androidaps.receivers.ReceiverStatusStore +import info.nightscout.androidaps.utils.DefaultValueHelper +import info.nightscout.androidaps.interfaces.ResourceHelper +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.wizard.QuickWizard +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import kotlinx.coroutines.* +import kotlinx.coroutines.tasks.await +import javax.inject.Inject + +class DataLayerListenerServiceMobile : WearableListenerService() { + + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var profileFunction: ProfileFunction + @Inject lateinit var iobCobCalculator: IobCobCalculator + @Inject lateinit var rh: ResourceHelper + @Inject lateinit var loop: Loop + @Inject lateinit var wearPlugin: WearPlugin + @Inject lateinit var sp: SP + @Inject lateinit var quickWizard: QuickWizard + @Inject lateinit var config: Config + @Inject lateinit var nsDeviceStatus: NSDeviceStatus + @Inject lateinit var receiverStatusStore: ReceiverStatusStore + @Inject lateinit var repository: AppRepository + @Inject lateinit var defaultValueHelper: DefaultValueHelper + @Inject lateinit var activePlugin: ActivePlugin + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + + private val dataClient by lazy { Wearable.getDataClient(this) } + private val messageClient by lazy { Wearable.getMessageClient(this) } + private val capabilityClient by lazy { Wearable.getCapabilityClient(this) } + //private val nodeClient by lazy { Wearable.getNodeClient(this) } + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) + + private val disposable = CompositeDisposable() + + private val rxPath get() = getString(R.string.path_rx_bridge) + + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + aapsLogger.debug(LTag.WEAR, "onCreate") + handler.post { updateTranscriptionCapability() } + disposable += rxBus + .toObservable(EventMobileToWear::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { sendMessage(rxPath, it.payload.serialize()) } + } + + override fun onCapabilityChanged(p0: CapabilityInfo) { + super.onCapabilityChanged(p0) + handler.post { updateTranscriptionCapability() } + aapsLogger.debug(LTag.WEAR, "onCapabilityChanged: ${p0.name} ${p0.nodes.joinToString(", ") { it.displayName + "(" + it.id + ")" }}") + } + + override fun onDestroy() { + super.onDestroy() + disposable.clear() + scope.cancel() + } + + @Suppress("ControlFlowWithEmptyBody", "UNUSED_EXPRESSION") + override fun onDataChanged(dataEvents: DataEventBuffer) { + //aapsLogger.debug(LTag.WEAR, "onDataChanged") + + if (wearPlugin.isEnabled()) { + dataEvents.forEach { event -> + if (event.type == DataEvent.TYPE_CHANGED) { + val path = event.dataItem.uri.path + + aapsLogger.debug(LTag.WEAR, "onDataChanged: Path: $path, EventDataItem=${event.dataItem}") + try { + when (path) { + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, "Message failed", exception) + } + } + } + } + super.onDataChanged(dataEvents) + } + + override fun onMessageReceived(messageEvent: MessageEvent) { + super.onMessageReceived(messageEvent) + + if (wearPlugin.isEnabled()) { + when (messageEvent.path) { + rxPath -> { + aapsLogger.debug(LTag.WEAR, "onMessageReceived: ${String(messageEvent.data)}") + val command = EventData.deserialize(String(messageEvent.data)) + rxBus.send(command.also { it.sourceNodeId = messageEvent.sourceNodeId }) + } + } + } + } + + private var transcriptionNodeId: String? = null + + private fun updateTranscriptionCapability() { + val capabilityInfo: CapabilityInfo = Tasks.await( + capabilityClient.getCapability(WEAR_CAPABILITY, CapabilityClient.FILTER_REACHABLE) + ) + aapsLogger.debug(LTag.WEAR, "Nodes: ${capabilityInfo.nodes.joinToString(", ") { it.displayName + "(" + it.id + ")" }}") + val bestNode = pickBestNodeId(capabilityInfo.nodes) + transcriptionNodeId = bestNode?.id + wearPlugin.connectedDevice = bestNode?.displayName ?: "---" + rxBus.send(EventWearUpdateGui()) + aapsLogger.debug(LTag.WEAR, "Selected node: ${bestNode?.displayName} $transcriptionNodeId") + rxBus.send(EventMobileToWear(EventData.ActionPing(System.currentTimeMillis()))) + rxBus.send(EventData.ActionResendData("WatchUpdaterService")) + } + + // Find a nearby node or pick one arbitrarily + private fun pickBestNodeId(nodes: Set): Node? = + nodes.firstOrNull { it.isNearby } ?: nodes.firstOrNull() + + @Suppress("unused") + private fun sendData(path: String, vararg params: DataMap) { + if (wearPlugin.isEnabled()) { + scope.launch { + try { + for (dm in params) { + val request = PutDataMapRequest.create(path).apply { + dataMap.putAll(dm) + } + .asPutDataRequest() + .setUrgent() + + val result = dataClient.putDataItem(request).await() + aapsLogger.debug(LTag.WEAR, "sendData: ${result.uri} ${params.joinToString()}") + } + } catch (cancellationException: CancellationException) { + throw cancellationException + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, "DataItem failed: $exception") + } + } + } + } + + private fun sendMessage(path: String, data: String?) { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path $data") + transcriptionNodeId?.also { nodeId -> + messageClient + .sendMessage(nodeId, path, data?.toByteArray() ?: byteArrayOf()).apply { + addOnSuccessListener { } + addOnFailureListener { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure") + } + } + } + } + + @Suppress("unused") + private fun sendMessage(path: String, data: ByteArray) { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path") + transcriptionNodeId?.also { nodeId -> + messageClient + .sendMessage(nodeId, path, data).apply { + addOnSuccessListener { } + addOnFailureListener { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure") + } + } + } + } + + companion object { + + const val WEAR_CAPABILITY = "androidaps_wear" + } +} \ No newline at end of file diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java b/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java deleted file mode 100644 index 0852b0a6aa..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/SendToDataLayerThread.java +++ /dev/null @@ -1,139 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear.wearintegration; - -import android.os.AsyncTask; -import android.util.Log; - -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.wearable.DataApi; -import com.google.android.gms.wearable.DataMap; -import com.google.android.gms.wearable.Node; -import com.google.android.gms.wearable.NodeApi; -import com.google.android.gms.wearable.PutDataMapRequest; -import com.google.android.gms.wearable.PutDataRequest; -import com.google.android.gms.wearable.Wearable; - -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.ReentrantLock; - -/** - * Created by emmablack on 12/26/14. - */ -class SendToDataLayerThread extends AsyncTask { - private final GoogleApiClient googleApiClient; - private static final String TAG = "SendToDataLayerThread"; - private final String path; - private final String logPrefix = ""; // "WR: "; - private static int concurrency = 0; - private static int state = 0; - private static final ReentrantLock lock = new ReentrantLock(); - private static long lastlock = 0; - private static final boolean testlockup = false; // always false in production - - - SendToDataLayerThread(String path, GoogleApiClient pGoogleApiClient) { - // Log.d(TAG, logPrefix + "SendToDataLayerThread: " + path); - this.path = path; - googleApiClient = pGoogleApiClient; - } - - - @Override - protected void onPreExecute() { - concurrency++; - if ((concurrency > 12) || ((concurrency > 3 && (lastlock != 0) && (tsl() - lastlock) > 300000))) { - // error if 9 concurrent threads or lock held for >5 minutes with concurrency of 4 - final String err = "Wear Integration deadlock detected!! " + ((lastlock != 0) ? "locked" : "") + " state:" - + state + " @" + hourMinuteString(tsl()); - // Home.toaststaticnext(err); - Log.e(TAG, logPrefix + err); - } - if (concurrency < 0) - Log.d(TAG, logPrefix + "Wear Integration impossible concurrency!!"); - - Log.d(TAG, logPrefix + "SendDataToLayerThread pre-execute concurrency: " + concurrency); - } - - - @Override - protected Void doInBackground(DataMap... params) { - if (testlockup) { - try { - Log.e(TAG, logPrefix + "WARNING RUNNING TEST LOCK UP CODE - NEVER FOR PRODUCTION"); - Thread.sleep(1000000); // DEEEBBUUGGGG - } catch (Exception e) { - } - } - sendToWear(params); - concurrency--; - Log.d(TAG, logPrefix + "SendDataToLayerThread post-execute concurrency: " + concurrency); - return null; - } - - - // Debug function to expose where it might be locking up - private synchronized void sendToWear(final DataMap... params) { - if (!lock.tryLock()) { - Log.d(TAG, logPrefix + "Concurrent access - waiting for thread unlock"); - lock.lock(); // enforce single threading - Log.d(TAG, logPrefix + "Thread unlocked - proceeding"); - } - lastlock = tsl(); - try { - if (state != 0) { - Log.e(TAG, logPrefix + "WEAR STATE ERROR: state=" + state); - } - state = 1; - final NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(15, - TimeUnit.SECONDS); - - Log.d(TAG, logPrefix + "Nodes: " + nodes); - - state = 2; - for (Node node : nodes.getNodes()) { - state = 3; - for (DataMap dataMap : params) { - state = 4; - PutDataMapRequest putDMR = PutDataMapRequest.create(path); - state = 5; - putDMR.getDataMap().putAll(dataMap); - putDMR.setUrgent(); - state = 6; - PutDataRequest request = putDMR.asPutDataRequest(); - state = 7; - DataApi.DataItemResult result = Wearable.DataApi.putDataItem(googleApiClient, request).await(15, - TimeUnit.SECONDS); - state = 8; - if (result.getStatus().isSuccess()) { - Log.d(TAG, logPrefix + "DataMap: " + dataMap + " sent to: " + node.getDisplayName()); - } else { - Log.e(TAG, logPrefix + "ERROR: failed to send DataMap"); - result = Wearable.DataApi.putDataItem(googleApiClient, request).await(30, TimeUnit.SECONDS); - if (result.getStatus().isSuccess()) { - Log.d(TAG, logPrefix + "DataMap retry: " + dataMap + " sent to: " + node.getDisplayName()); - } else { - Log.e(TAG, logPrefix + "ERROR on retry: failed to send DataMap: " - + result.getStatus().toString()); - } - } - state = 9; - } - } - state = 0; - } catch (Exception e) { - Log.e(TAG, logPrefix + "Got exception in sendToWear: " + e); - } finally { - lastlock = 0; - lock.unlock(); - } - } - - - private static long tsl() { - return System.currentTimeMillis(); - } - - - private static String hourMinuteString(long timestamp) { - return android.text.format.DateFormat.format("kk:mm", timestamp).toString(); - } -} 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 deleted file mode 100644 index 85d08c142c..0000000000 --- a/app/src/main/java/info/nightscout/androidaps/plugins/general/wear/wearintegration/WatchUpdaterService.java +++ /dev/null @@ -1,843 +0,0 @@ -package info.nightscout.androidaps.plugins.general.wear.wearintegration; - -import android.content.Intent; -import android.os.AsyncTask; -import android.os.Bundle; -import android.os.Handler; -import android.os.HandlerThread; -import android.util.Log; - -import androidx.annotation.NonNull; - -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.wearable.CapabilityApi; -import com.google.android.gms.wearable.CapabilityInfo; -import com.google.android.gms.wearable.DataMap; -import com.google.android.gms.wearable.MessageEvent; -import com.google.android.gms.wearable.Node; -import com.google.android.gms.wearable.PutDataMapRequest; -import com.google.android.gms.wearable.PutDataRequest; -import com.google.android.gms.wearable.Wearable; -import com.google.android.gms.wearable.WearableListenerService; - -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.Constants; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.IobTotal; -import info.nightscout.androidaps.database.AppRepository; -import info.nightscout.androidaps.database.entities.Bolus; -import info.nightscout.androidaps.database.entities.GlucoseValue; -import info.nightscout.androidaps.database.entities.TemporaryBasal; -import info.nightscout.androidaps.extensions.GlucoseValueExtensionKt; -import info.nightscout.androidaps.extensions.TemporaryBasalExtensionKt; -import info.nightscout.androidaps.interfaces.ActivePlugin; -import info.nightscout.androidaps.interfaces.Config; -import info.nightscout.androidaps.interfaces.GlucoseUnit; -import info.nightscout.androidaps.interfaces.IobCobCalculator; -import info.nightscout.androidaps.interfaces.Loop; -import info.nightscout.androidaps.interfaces.PluginBase; -import info.nightscout.androidaps.interfaces.Profile; -import info.nightscout.androidaps.interfaces.ProfileFunction; -import info.nightscout.androidaps.plugins.aps.loop.LoopPlugin; -import info.nightscout.androidaps.plugins.bus.RxBus; -import info.nightscout.androidaps.plugins.general.nsclient.data.NSDeviceStatus; -import info.nightscout.androidaps.plugins.general.overview.graphExtensions.GlucoseValueDataPoint; -import info.nightscout.androidaps.plugins.general.wear.WearPlugin; -import info.nightscout.androidaps.plugins.general.wear.events.EventWearConfirmAction; -import info.nightscout.androidaps.plugins.general.wear.events.EventWearInitiateAction; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatus; -import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider; -import info.nightscout.androidaps.receivers.ReceiverStatusStore; -import info.nightscout.androidaps.utils.DecimalFormatter; -import info.nightscout.androidaps.utils.DefaultValueHelper; -import info.nightscout.androidaps.utils.TrendCalculator; -import info.nightscout.androidaps.utils.resources.ResourceHelper; -import info.nightscout.androidaps.utils.wizard.QuickWizard; -import info.nightscout.androidaps.utils.wizard.QuickWizardEntry; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; -import info.nightscout.shared.sharedPreferences.SP; -import info.nightscout.shared.weardata.WearUris; - -public class WatchUpdaterService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { - @Inject public GlucoseStatusProvider glucoseStatusProvider; - @Inject public AAPSLogger aapsLogger; - @Inject public WearPlugin wearPlugin; - @Inject public ResourceHelper rh; - @Inject public SP sp; - @Inject public RxBus rxBus; - @Inject public ProfileFunction profileFunction; - @Inject public DefaultValueHelper defaultValueHelper; - @Inject public NSDeviceStatus nsDeviceStatus; - @Inject public ActivePlugin activePlugin; - @Inject public Loop loop; - @Inject public IobCobCalculator iobCobCalculator; - @Inject public AppRepository repository; - @Inject ReceiverStatusStore receiverStatusStore; - @Inject Config config; - @Inject public TrendCalculator trendCalculator; - @Inject public QuickWizard quickWizard; - - public static final String ACTION_RESEND = WatchUpdaterService.class.getName().concat(".Resend"); - public static final String ACTION_OPEN_SETTINGS = WatchUpdaterService.class.getName().concat(".OpenSettings"); - public static final String ACTION_SEND_STATUS = WatchUpdaterService.class.getName().concat(".SendStatus"); - public static final String ACTION_SEND_BASALS = WatchUpdaterService.class.getName().concat(".SendBasals"); - public static final String ACTION_SEND_BOLUSPROGRESS = WatchUpdaterService.class.getName().concat(".BolusProgress"); - public static final String ACTION_SEND_ACTIONCONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ActionConfirmationRequest"); - public static final String ACTION_SEND_CHANGECONFIRMATIONREQUEST = WatchUpdaterService.class.getName().concat(".ChangeConfirmationRequest"); - public static final String ACTION_CANCEL_NOTIFICATION = WatchUpdaterService.class.getName().concat(".CancelNotification"); - - private GoogleApiClient googleApiClient; - - String TAG = "WatchUpdateService"; - - private static boolean lastLoopStatus; - - private Handler handler; - - // Phone - private static final String CAPABILITY_PHONE_APP = "phone_app_sync_bgs"; - private static final String MESSAGE_PATH_PHONE = "/phone_message_path"; - // Wear - private static final String CAPABILITY_WEAR_APP = "wear_app_sync_bgs"; - private static final String MESSAGE_PATH_WEAR = "/wear_message_path"; - - - @Override - public void onCreate() { - AndroidInjection.inject(this); - if (wearIntegration()) { - googleApiConnect(); - } - if (handler == null) { - HandlerThread handlerThread = new HandlerThread(this.getClass().getSimpleName() + "Handler"); - handlerThread.start(); - handler = new Handler(handlerThread.getLooper()); - } - } - - private boolean wearIntegration() { - return wearPlugin.isEnabled(); - } - - private void googleApiConnect() { - if (googleApiClient != null && (googleApiClient.isConnected() || googleApiClient.isConnecting())) { - googleApiClient.disconnect(); - } - googleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this) - .addOnConnectionFailedListener(this).addApi(Wearable.API).build(); - Wearable.MessageApi.addListener(googleApiClient, this); - if (googleApiClient.isConnected()) { - aapsLogger.debug(LTag.WEAR, "API client is connected"); - } else { - // Log.d("WatchUpdater", logPrefix + "API client is not connected and is trying to connect"); - googleApiClient.connect(); - } - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - String action = intent != null ? intent.getAction() : null; - - // Log.d(TAG, "onStartCommand: " + action); - - if (wearIntegration()) { - handler.post(() -> { - if (googleApiClient != null && googleApiClient.isConnected()) { - if (ACTION_RESEND.equals(action)) { - resendData(); - } else if (ACTION_OPEN_SETTINGS.equals(action)) { - sendNotification(); - } else if (ACTION_SEND_STATUS.equals(action)) { - sendStatus(); - } else if (ACTION_SEND_BASALS.equals(action)) { - sendBasals(); - } else if (ACTION_SEND_BOLUSPROGRESS.equals(action)) { - sendBolusProgress(intent.getIntExtra("progresspercent", 0), intent.hasExtra("progressstatus") ? intent.getStringExtra("progressstatus") : ""); - } else if (ACTION_SEND_ACTIONCONFIRMATIONREQUEST.equals(action)) { - String title = intent.getStringExtra("title"); - String message = intent.getStringExtra("message"); - String actionstring = intent.getStringExtra("actionstring"); - sendActionConfirmationRequest(title, message, actionstring); - } else if (ACTION_SEND_CHANGECONFIRMATIONREQUEST.equals(action)) { - String title = intent.getStringExtra("title"); - String message = intent.getStringExtra("message"); - String actionstring = intent.getStringExtra("actionstring"); - sendChangeConfirmationRequest(title, message, actionstring); - } else if (ACTION_CANCEL_NOTIFICATION.equals(action)) { - String actionstring = intent.getStringExtra("actionstring"); - sendCancelNotificationRequest(actionstring); - } else { - sendData(); - } - } else { - if (googleApiClient != null) googleApiClient.connect(); - } - }); - } - - return START_STICKY; - } - - - private void updateWearSyncBgsCapability(CapabilityInfo capabilityInfo) { - Log.d("WatchUpdaterService", "CabilityInfo: " + capabilityInfo); - Set connectedNodes = capabilityInfo.getNodes(); - String mWearNodeId = pickBestNodeId(connectedNodes); - } - - - private String pickBestNodeId(Set nodes) { - String bestNodeId = null; - // Find a nearby node or pick one arbitrarily - for (Node node : nodes) { - if (node.isNearby()) { - return node.getId(); - } - bestNodeId = node.getId(); - } - return bestNodeId; - } - - - @Override - public void onConnected(Bundle connectionHint) { - CapabilityApi.CapabilityListener capabilityListener = capabilityInfo -> { - updateWearSyncBgsCapability(capabilityInfo); - // Log.d(TAG, logPrefix + "onConnected onCapabilityChanged mWearNodeID:" + mWearNodeId); - // new CheckWearableConnected().execute(); - }; - - Wearable.CapabilityApi.addCapabilityListener(googleApiClient, capabilityListener, CAPABILITY_WEAR_APP); - sendData(); - } - - - @Override - public void onPeerConnected(com.google.android.gms.wearable.Node peer) {// KS - super.onPeerConnected(peer); - String id = peer.getId(); - String name = peer.getDisplayName(); - Log.d(TAG, "onPeerConnected peer name & ID: " + name + "|" + id); - } - - - @Override - public void onPeerDisconnected(com.google.android.gms.wearable.Node peer) {// KS - super.onPeerDisconnected(peer); - String id = peer.getId(); - String name = peer.getDisplayName(); - Log.d(TAG, "onPeerDisconnected peer name & ID: " + name + "|" + id); - } - - - @Override - public void onMessageReceived(MessageEvent event) { - - // Log.d(TAG, "onMessageRecieved: " + event); - - if (wearIntegration()) { - if (event != null && event.getPath().equals(WearUris.WEARABLE_RESEND_PATH)) { - resendData(); - } - - if (event != null && event.getPath().equals(WearUris.WEARABLE_CANCELBOLUS_PATH)) { - cancelBolus(); - } - - if (event != null && event.getPath().equals(WearUris.WEARABLE_INITIATE_ACTIONSTRING_PATH)) { - String actionstring = new String(event.getData()); - aapsLogger.debug(LTag.WEAR, "Wear: " + actionstring); - rxBus.send(new EventWearInitiateAction(actionstring)); - } - - if (event != null && event.getPath().equals(WearUris.WEARABLE_CONFIRM_ACTIONSTRING_PATH)) { - String actionstring = new String(event.getData()); - aapsLogger.debug(LTag.WEAR, "Wear Confirm: " + actionstring); - rxBus.send(new EventWearConfirmAction(actionstring)); - } - } - } - - private void cancelBolus() { - activePlugin.getActivePump().stopBolusDelivering(); - } - - private void sendData() { - - GlucoseValue lastBG = iobCobCalculator.getAds().lastBg(); - // Log.d(TAG, "LastBg=" + lastBG); - if (lastBG != null) { - GlucoseStatus glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(); - - if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { - googleApiConnect(); - } - if (wearIntegration()) { - - final DataMap dataMap = dataMapSingleBG(lastBG, glucoseStatus); - - (new SendToDataLayerThread(WearUris.WEARABLE_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dataMap); - } - } - } - - - private DataMap dataMapSingleBG(GlucoseValue lastBG, GlucoseStatus glucoseStatus) { - GlucoseUnit units = profileFunction.getUnits(); - double convert2MGDL = 1.0; - if (units.equals(GlucoseUnit.MMOL)) - convert2MGDL = Constants.MMOLL_TO_MGDL; - double lowLine = defaultValueHelper.determineLowLine() * convert2MGDL; - double highLine = defaultValueHelper.determineHighLine() * convert2MGDL; - - long sgvLevel = 0L; - if (lastBG.getValue() > highLine) { - sgvLevel = 1; - } else if (lastBG.getValue() < lowLine) { - sgvLevel = -1; - } - - DataMap dataMap = new DataMap(); - dataMap.putString("sgvString", GlucoseValueExtensionKt.valueToUnitsString(lastBG, units)); - dataMap.putString("glucoseUnits", units.getAsText()); - dataMap.putLong("timestamp", lastBG.getTimestamp()); - if (glucoseStatus == null) { - dataMap.putString("slopeArrow", ""); - dataMap.putString("delta", "--"); - dataMap.putString("avgDelta", "--"); - } else { - dataMap.putString("slopeArrow", trendCalculator.getTrendArrow(lastBG).getSymbol()); - dataMap.putString("delta", deltastring(glucoseStatus.getDelta(), glucoseStatus.getDelta() * Constants.MGDL_TO_MMOLL, units)); - dataMap.putString("avgDelta", deltastring(glucoseStatus.getShortAvgDelta(), glucoseStatus.getShortAvgDelta() * Constants.MGDL_TO_MMOLL, units)); - } - dataMap.putLong("sgvLevel", sgvLevel); - dataMap.putDouble("sgvDouble", lastBG.getValue()); - dataMap.putDouble("high", highLine); - dataMap.putDouble("low", lowLine); - return dataMap; - } - - private String deltastring(double deltaMGDL, double deltaMMOL, GlucoseUnit units) { - String deltastring = ""; - if (deltaMGDL >= 0) { - deltastring += "+"; - } else { - deltastring += "-"; - } - - boolean detailed = sp.getBoolean(R.string.key_wear_detailed_delta, false); - if (units.equals(GlucoseUnit.MGDL)) { - if (detailed) { - deltastring += DecimalFormatter.INSTANCE.to1Decimal(Math.abs(deltaMGDL)); - } else { - deltastring += DecimalFormatter.INSTANCE.to0Decimal(Math.abs(deltaMGDL)); - } - } else { - if (detailed) { - deltastring += DecimalFormatter.INSTANCE.to2Decimal(Math.abs(deltaMMOL)); - } else { - deltastring += DecimalFormatter.INSTANCE.to1Decimal(Math.abs(deltaMMOL)); - } - } - return deltastring; - } - - private void resendData() { - if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { - googleApiConnect(); - } - - sendPreferences(); - sendQuickWizard(); - - long startTime = System.currentTimeMillis() - (long) (60000 * 60 * 5.5); - GlucoseValue last_bg = iobCobCalculator.getAds().lastBg(); - - if (last_bg == null) return; - - List graph_bgs = repository.compatGetBgReadingsDataFromTime(startTime, true).blockingGet(); - GlucoseStatus glucoseStatus = glucoseStatusProvider.getGlucoseStatusData(true); - - if (!graph_bgs.isEmpty()) { - DataMap entries = dataMapSingleBG(last_bg, glucoseStatus); - final ArrayList dataMaps = new ArrayList<>(graph_bgs.size()); - for (GlucoseValue bg : graph_bgs) { - DataMap dataMap = dataMapSingleBG(bg, glucoseStatus); - dataMaps.add(dataMap); - } - entries.putDataMapArrayList("entries", dataMaps); - (new SendToDataLayerThread(WearUris.WEARABLE_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, entries); - } - sendBasals(); - sendStatus(); - } - - private void sendBasals() { - if (googleApiClient != null && !googleApiClient.isConnected() && !googleApiClient.isConnecting()) { - googleApiConnect(); - } - - long now = System.currentTimeMillis(); - final long startTimeWindow = now - (long) (60000 * 60 * 5.5); - - - ArrayList basals = new ArrayList<>(); - ArrayList temps = new ArrayList<>(); - ArrayList boluses = new ArrayList<>(); - ArrayList predictions = new ArrayList<>(); - - - Profile profile = profileFunction.getProfile(); - - if (profile == null) { - return; - } - - long beginBasalSegmentTime = startTimeWindow; - long runningTime = startTimeWindow; - - double beginBasalValue = profile.getBasal(beginBasalSegmentTime); - double endBasalValue = beginBasalValue; - - TemporaryBasal tb1 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime); - TemporaryBasal tb2; - double tb_before = beginBasalValue; - double tb_amount = beginBasalValue; - long tb_start = runningTime; - - if (tb1 != null) { - Profile profileTB = profileFunction.getProfile(runningTime); - if (profileTB != null) { - tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB); - tb_start = runningTime; - } - } - - - for (; runningTime < now; runningTime += 5 * 60 * 1000) { - Profile profileTB = profileFunction.getProfile(runningTime); - if (profileTB == null) - return; - //basal rate - endBasalValue = profile.getBasal(runningTime); - if (endBasalValue != beginBasalValue) { - //push the segment we recently left - basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue)); - - //begin new Basal segment - beginBasalSegmentTime = runningTime; - beginBasalValue = endBasalValue; - } - - //temps - tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(runningTime); - - if (tb1 == null && tb2 == null) { - ; //no temp stays no temp - - } else if (tb1 != null && tb2 == null) { - //temp is over -> push it - temps.add(tempDatamap(tb_start, tb_before, runningTime, endBasalValue, tb_amount)); - tb1 = null; - - } else if (tb1 == null && tb2 != null) { - //temp begins - tb1 = tb2; - tb_start = runningTime; - tb_before = endBasalValue; - tb_amount = TemporaryBasalExtensionKt.convertedToAbsolute(tb1, runningTime, profileTB); - - } else if (tb1 != null && tb2 != null) { - double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, runningTime, profileTB); - if (currentAmount != tb_amount) { - temps.add(tempDatamap(tb_start, tb_before, runningTime, currentAmount, tb_amount)); - tb_start = runningTime; - tb_before = tb_amount; - tb_amount = currentAmount; - tb1 = tb2; - } - } - } - if (beginBasalSegmentTime != runningTime) { - //push the remaining segment - basals.add(basalMap(beginBasalSegmentTime, runningTime, beginBasalValue)); - } - if (tb1 != null) { - tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now); //use "now" to express current situation - if (tb2 == null) { - //express the cancelled temp by painting it down one minute early - temps.add(tempDatamap(tb_start, tb_before, now - 60 * 1000, endBasalValue, tb_amount)); - } else { - //express currently running temp by painting it a bit into the future - Profile profileNow = profileFunction.getProfile(now); - double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, now, profileNow); - if (currentAmount != tb_amount) { - temps.add(tempDatamap(tb_start, tb_before, now, tb_amount, tb_amount)); - temps.add(tempDatamap(now, tb_amount, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); - } else { - temps.add(tempDatamap(tb_start, tb_before, runningTime + 5 * 60 * 1000, tb_amount, tb_amount)); - } - } - } else { - tb2 = iobCobCalculator.getTempBasalIncludingConvertedExtended(now); //use "now" to express current situation - if (tb2 != null) { - //onset at the end - Profile profileTB = profileFunction.getProfile(runningTime); - double currentAmount = TemporaryBasalExtensionKt.convertedToAbsolute(tb2, runningTime, profileTB); - temps.add(tempDatamap(now - 60 * 1000, endBasalValue, runningTime + 5 * 60 * 1000, currentAmount, currentAmount)); - } - } - - repository.getBolusesIncludingInvalidFromTime(startTimeWindow, true).blockingGet() - .stream() - .filter(bolus -> bolus.getType() != Bolus.Type.PRIMING) - .forEach(bolus -> boluses.add(treatmentMap(bolus.getTimestamp(), bolus.getAmount(), 0, bolus.getType() == Bolus.Type.SMB, bolus.isValid()))); - repository.getCarbsDataFromTimeExpanded(startTimeWindow, true).blockingGet() - .forEach(carb -> boluses.add(treatmentMap(carb.getTimestamp(), 0, carb.getAmount(), false, carb.isValid()))); - - final LoopPlugin.LastRun finalLastRun = loop.getLastRun(); - if (sp.getBoolean("wear_predictions", true) && finalLastRun != null && finalLastRun.getRequest().getHasPredictions() && finalLastRun.getConstraintsProcessed() != null) { - List predArray = - finalLastRun.getConstraintsProcessed().getPredictions() - .stream().map(bg -> new GlucoseValueDataPoint(bg, defaultValueHelper, profileFunction, rh)) - .collect(Collectors.toList()); - - if (!predArray.isEmpty()) { - for (GlucoseValueDataPoint bg : predArray) { - if (bg.getData().getValue() < 40) continue; - predictions.add(predictionMap(bg.getData().getTimestamp(), - bg.getData().getValue(), bg.color(null))); - } - } - } - - - DataMap dm = new DataMap(); - dm.putDataMapArrayList("basals", basals); - dm.putDataMapArrayList("temps", temps); - dm.putDataMapArrayList("boluses", boluses); - dm.putDataMapArrayList("predictions", predictions); - (new SendToDataLayerThread(WearUris.BASAL_DATA_PATH, googleApiClient)).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dm); - } - - private DataMap tempDatamap(long startTime, double startBasal, long to, double toBasal, double amount) { - DataMap dm = new DataMap(); - dm.putLong("starttime", startTime); - dm.putDouble("startBasal", startBasal); - dm.putLong("endtime", to); - dm.putDouble("endbasal", toBasal); - dm.putDouble("amount", amount); - return dm; - } - - private DataMap basalMap(long startTime, long endTime, double amount) { - DataMap dm = new DataMap(); - dm.putLong("starttime", startTime); - dm.putLong("endtime", endTime); - dm.putDouble("amount", amount); - return dm; - } - - private DataMap treatmentMap(long date, double bolus, double carbs, boolean isSMB, boolean isValid) { - DataMap dm = new DataMap(); - dm.putLong("date", date); - dm.putDouble("bolus", bolus); - dm.putDouble("carbs", carbs); - dm.putBoolean("isSMB", isSMB); - dm.putBoolean("isValid", isValid); - return dm; - } - - private DataMap predictionMap(long timestamp, double sgv, int color) { - DataMap dm = new DataMap(); - dm.putLong("timestamp", timestamp); - dm.putDouble("sgv", sgv); - dm.putInt("color", color); - return dm; - } - - - private void sendNotification() { - if (googleApiClient != null && googleApiClient.isConnected()) { - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.OPEN_SETTINGS_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putString("openSettings", "openSettings"); - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("OpenSettings", "No connection to wearable available!"); - } - } - - private void sendBolusProgress(int progresspercent, String status) { - if (googleApiClient != null && googleApiClient.isConnected()) { - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.BOLUS_PROGRESS_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putString("bolusProgress", "bolusProgress"); - dataMapRequest.getDataMap().putString("progressstatus", status); - dataMapRequest.getDataMap().putInt("progresspercent", progresspercent); - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("BolusProgress", "No connection to wearable available!"); - } - } - - private void sendActionConfirmationRequest(String title, String message, String actionstring) { - if (googleApiClient != null && googleApiClient.isConnected()) { - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.ACTION_CONFIRMATION_REQUEST_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putString("actionConfirmationRequest", "actionConfirmationRequest"); - dataMapRequest.getDataMap().putString("title", title); - dataMapRequest.getDataMap().putString("message", message); - dataMapRequest.getDataMap().putString("actionstring", actionstring); - - aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: " + actionstring); - - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("confirmationRequest", "No connection to wearable available!"); - } - } - - private void sendChangeConfirmationRequest(String title, String message, String actionstring) { - if (googleApiClient != null && googleApiClient.isConnected()) { - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.ACTION_CHANGECONFIRMATION_REQUEST_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putString("changeConfirmationRequest", "changeConfirmationRequest"); - dataMapRequest.getDataMap().putString("title", title); - dataMapRequest.getDataMap().putString("message", message); - dataMapRequest.getDataMap().putString("actionstring", actionstring); - - aapsLogger.debug(LTag.WEAR, "Requesting confirmation from wear: " + actionstring); - - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("changeConfirmRequest", "No connection to wearable available!"); - } - } - - private void sendCancelNotificationRequest(String actionstring) { - if (googleApiClient != null && googleApiClient.isConnected()) { - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.ACTION_CANCELNOTIFICATION_REQUEST_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putString("cancelNotificationRequest", "cancelNotificationRequest"); - dataMapRequest.getDataMap().putString("actionstring", actionstring); - - aapsLogger.debug(LTag.WEAR, "Canceling notification on wear: " + actionstring); - - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("cancelNotificationReq", "No connection to wearable available!"); - } - } - - private void sendStatus() { - - if (googleApiClient != null && googleApiClient.isConnected()) { - Profile profile = profileFunction.getProfile(); - String status = rh.gs(R.string.noprofile); - String iobSum, iobDetail, cobString, currentBasal, bgiString; - iobSum = iobDetail = cobString = currentBasal = bgiString = ""; - if (profile != null) { - IobTotal bolusIob = iobCobCalculator.calculateIobFromBolus().round(); - IobTotal basalIob = iobCobCalculator.calculateIobFromTempBasalsIncludingConvertedExtended().round(); - - iobSum = DecimalFormatter.INSTANCE.to2Decimal(bolusIob.getIob() + basalIob.getBasaliob()); - iobDetail = - "(" + DecimalFormatter.INSTANCE.to2Decimal(bolusIob.getIob()) + "|" + DecimalFormatter.INSTANCE.to2Decimal(basalIob.getBasaliob()) + ")"; - cobString = iobCobCalculator.getCobInfo(false, "WatcherUpdaterService").generateCOBString(); - currentBasal = generateBasalString(); - - //bgi - double bgi = - -(bolusIob.getActivity() + basalIob.getActivity()) * 5 * Profile.Companion.fromMgdlToUnits(profile.getIsfMgdl(), profileFunction.getUnits()); - bgiString = "" + ((bgi >= 0) ? "+" : "") + DecimalFormatter.INSTANCE.to1Decimal(bgi); - - status = generateStatusString(profile, currentBasal, iobSum, iobDetail, bgiString); - } - - - //batteries - int phoneBattery = receiverStatusStore.getBatteryLevel(); - String rigBattery = nsDeviceStatus.getUploaderStatus().trim(); - - - long openApsStatus; - //OpenAPS status - if (config.getAPS()) { - //we are AndroidAPS - openApsStatus = loop.getLastRun() != null && loop.getLastRun().getLastTBREnact() != 0 ? loop.getLastRun().getLastTBREnact() : -1; - } else { - //NSClient or remote - openApsStatus = nsDeviceStatus.getOpenApsTimestamp(); - } - - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.NEW_STATUS_PATH); - //unique content - dataMapRequest.getDataMap().putString("externalStatusString", status); - dataMapRequest.getDataMap().putString("iobSum", iobSum); - dataMapRequest.getDataMap().putString("iobDetail", iobDetail); - dataMapRequest.getDataMap().putBoolean("detailedIob", sp.getBoolean(R.string.key_wear_detailediob, false)); - dataMapRequest.getDataMap().putString("cob", cobString); - dataMapRequest.getDataMap().putString("currentBasal", currentBasal); - dataMapRequest.getDataMap().putString("battery", "" + phoneBattery); - dataMapRequest.getDataMap().putString("rigBattery", rigBattery); - dataMapRequest.getDataMap().putLong("openApsStatus", openApsStatus); - dataMapRequest.getDataMap().putString("bgi", bgiString); - dataMapRequest.getDataMap().putBoolean("showBgi", sp.getBoolean(R.string.key_wear_showbgi, false)); - dataMapRequest.getDataMap().putInt("batteryLevel", (phoneBattery >= 30) ? 1 : 0); - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("SendStatus", "No connection to wearable available!"); - } - } - - private void sendPreferences() { - if (googleApiClient != null && googleApiClient.isConnected()) { - - GlucoseUnit units = profileFunction.getUnits(); - boolean wearcontrol = sp.getBoolean(R.string.key_wear_control, false); - boolean mgdl = units.equals(GlucoseUnit.MGDL); - int percentage = sp.getInt(R.string.key_boluswizard_percentage, 100); - int maxCarbs = sp.getInt(R.string.key_treatmentssafety_maxcarbs, 48); - double maxBolus = sp.getDouble(R.string.key_treatmentssafety_maxbolus, 3.0); - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.NEW_PREFERENCES_PATH); - //unique content - dataMapRequest.getDataMap().putLong("timestamp", System.currentTimeMillis()); - dataMapRequest.getDataMap().putBoolean(rh.gs(R.string.key_wear_control), wearcontrol); - dataMapRequest.getDataMap().putBoolean(rh.gs(R.string.key_units_mgdl), mgdl); - dataMapRequest.getDataMap().putInt(rh.gs(R.string.key_boluswizard_percentage), percentage); - dataMapRequest.getDataMap().putInt(rh.gs(R.string.key_treatmentssafety_maxcarbs), maxCarbs); - dataMapRequest.getDataMap().putDouble(rh.gs(R.string.key_treatmentssafety_maxbolus), maxBolus); - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("SendPreferences", "No connection to wearable available!"); - } - } - - private void sendQuickWizard() { - if (googleApiClient != null && googleApiClient.isConnected()) { - int size = quickWizard.size(); - ArrayList entities = new ArrayList<>(); - for (int i = 0; i < size; i++) { - QuickWizardEntry q = quickWizard.get(i); - if (q.forDevice(QuickWizardEntry.DEVICE_WATCH)) { - entities.add(quickMap(q)); - } - } - - PutDataMapRequest dataMapRequest = PutDataMapRequest.create(WearUris.QUICK_WIZARD_PATH); - - DataMap dm = dataMapRequest.getDataMap(); - dm.putLong("timestamp", System.currentTimeMillis()); - dm.putDataMapArrayList("quick_wizard", entities); - - PutDataRequest putDataRequest = dataMapRequest.asPutDataRequest(); - Log.i(TAG, "sendQuickWizard: " + putDataRequest); - Wearable.DataApi.putDataItem(googleApiClient, putDataRequest); - } else { - Log.e("sendQuickWizard", "No connection to wearable available!"); - } - } - - private DataMap quickMap(QuickWizardEntry q) { - DataMap dm = new DataMap(); - dm.putString("guid", q.guid()); - dm.putString("button_text", q.buttonText()); - dm.putInt("carbs", q.carbs()); - dm.putInt("from", q.validFrom()); - dm.putInt("to", q.validTo()); - return dm; - } - - @NonNull - private String generateStatusString(Profile profile, String currentBasal, String iobSum, String iobDetail, String bgiString) { - - String status = ""; - - if (profile == null) { - status = rh.gs(R.string.noprofile); - return status; - } - - if (!((PluginBase) loop).isEnabled()) { - status += rh.gs(R.string.disabledloop) + "\n"; - lastLoopStatus = false; - } else { - lastLoopStatus = true; - } - - String iobString; - if (sp.getBoolean(R.string.key_wear_detailediob, false)) { - iobString = iobSum + " " + iobDetail; - } else { - iobString = iobSum + "U"; - } - - status += currentBasal + " " + iobString; - - //add BGI if shown, otherwise return - if (sp.getBoolean(R.string.key_wear_showbgi, false)) { - status += " " + bgiString; - } - - return status; - } - - @NonNull - private String generateBasalString() { - - String basalStringResult; - - Profile profile = profileFunction.getProfile(); - if (profile == null) - return ""; - - TemporaryBasal activeTemp = iobCobCalculator.getTempBasalIncludingConvertedExtended(System.currentTimeMillis()); - if (activeTemp != null) { - basalStringResult = TemporaryBasalExtensionKt.toStringShort(activeTemp); - } else { - basalStringResult = DecimalFormatter.INSTANCE.to2Decimal(profile.getBasal()) + "U/h"; - } - return basalStringResult; - } - - @Override - public void onDestroy() { - if (googleApiClient != null && googleApiClient.isConnected()) { - googleApiClient.disconnect(); - } - } - - @Override - public void onConnectionSuspended(int cause) { - } - - @Override - public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { - } - - public static boolean shouldReportLoopStatus(boolean enabled) { - return (lastLoopStatus != enabled); - } -} 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 825ae8ad5a..104949730d 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 @@ -12,7 +12,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt index 080fbd41fe..3302f21a51 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinFragment.kt @@ -8,7 +8,7 @@ import dagger.android.support.DaggerFragment import info.nightscout.androidaps.R import info.nightscout.androidaps.databinding.InsulinFragmentBinding import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class InsulinFragment : DaggerFragment() { diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt index 45b8e84309..4ca7c6f91e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPlugin.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import javax.inject.Inject import javax.inject.Singleton 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 8300c9147a..a13f3e467e 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 @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import kotlin.math.exp import kotlin.math.pow 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 4f07b5117c..c9588c493b 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 @@ -9,7 +9,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject 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 1403530d66..8abb4619cc 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 @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject 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 8a81c50608..4f944b4674 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 @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt index cf38b3e857..6d76621a6d 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobCalculatorPlugin.kt @@ -26,9 +26,10 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.workflow.CalculationWorkflow +import info.nightscout.androidaps.events.Event import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Worker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Worker.kt index 69a3b58d5c..9540a0d871 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Worker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOref1Worker.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.workflow.CalculationWorkflow import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOrefWorker.kt b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOrefWorker.kt index 832de3fe58..e29c68676e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOrefWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/IobCobOrefWorker.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.Profiler import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.workflow.CalculationWorkflow import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag 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 63312f8df9..7e0e29fc8f 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 @@ -3,7 +3,6 @@ package info.nightscout.androidaps.plugins.profile.local import android.os.Bundle import android.text.Editable import android.text.TextWatcher -import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup @@ -33,11 +32,12 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.utils.ui.TimeListEdit import info.nightscout.shared.SafeParse import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.math.RoundingMode @@ -196,7 +196,7 @@ class LocalProfileFragment : DaggerFragment() { roundUp(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[0], GlucoseUnit.MMOL)), roundDown(Profile.fromMgdlToUnits(HardLimits.VERY_HARD_LIMIT_MAX_BG[1], GlucoseUnit.MMOL)) ) - Log.i("TimeListEdit", "build: range1" + range1[0] + " " + range1[1] + " range2" + range2[0] + " " + range2[1]) + aapsLogger.info(LTag.CORE, "TimeListEdit", "build: range1" + range1[0] + " " + range1[1] + " range2" + range2[0] + " " + range2[1]) TimeListEdit( context, aapsLogger, 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 f131a22122..687ca5adc3 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 @@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.profile.local.events.EventLocalProfile import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt index c7e9ee9b9b..f03c4f7da7 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/pump/mdi/MDIPlugin.kt @@ -5,13 +5,13 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.* -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.InstanceId.instanceId -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.utils.InstanceId +import info.nightscout.androidaps.interfaces.ResourceHelper +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag import org.json.JSONException import org.json.JSONObject import javax.inject.Inject @@ -152,7 +152,7 @@ class MDIPlugin @Inject constructor( override fun manufacturer(): ManufacturerType = ManufacturerType.AndroidAPS override fun model(): PumpType = PumpType.MDI - override fun serialNumber(): String = instanceId() + override fun serialNumber(): String = InstanceId.instanceId override fun shortStatus(veryShort: Boolean): String = model().model override fun canHandleDST(): Boolean = true } \ No newline at end of file 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 d36c5225ea..1f3d8b1f29 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 @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUp 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign 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 f900d942da..0284ce9259 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 @@ -11,8 +11,6 @@ import info.nightscout.androidaps.events.EventPreferenceChange import info.nightscout.androidaps.extensions.convertedToAbsolute import info.nightscout.androidaps.extensions.plannedRemainingMinutes import info.nightscout.androidaps.interfaces.* -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification @@ -22,11 +20,13 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.plugins.pump.virtual.events.EventVirtualPumpUpdateGui import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.InstanceId.instanceId +import info.nightscout.androidaps.utils.InstanceId import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.TimeChangeType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -365,7 +365,7 @@ open class VirtualPumpPlugin @Inject constructor( override fun model(): PumpType = pumpDescription.pumpType - override fun serialNumber(): String = instanceId() + override fun serialNumber(): String = InstanceId.instanceId override fun shortStatus(veryShort: Boolean): String = "Virtual Pump" 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 a8132a5c2f..a942d50f94 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 @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.utils.Round import info.nightscout.shared.SafeParse -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import kotlin.math.max import kotlin.math.min diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt index 4902118b8d..dee4efb932 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityAAPSPlugin.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt index df5dbe68f5..cccd3cbeff 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityOref1Plugin.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.plugins.iob.iobCobCalculator.IobCobCalculatorPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt index 868ac4ac7a..aa3033733e 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/sensitivity/SensitivityWeightedAveragePlugin.kt @@ -19,7 +19,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/AidexPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/AidexPlugin.kt index 650579811c..b782832f30 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/AidexPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/AidexPlugin.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.interfaces.PluginDescription import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.services.Intents -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import javax.inject.Inject 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 ad6e0f867d..b04b104a01 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 @@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt index 0255209c5e..7df9fe9729 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/DexcomPlugin.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP 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 8ba0d66e30..05715e8e12 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 @@ -20,7 +20,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt index fb938e764a..8efc9651df 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlimpPlugin.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlunovoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlunovoPlugin.kt index 818951fff1..239a317781 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/GlunovoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/GlunovoPlugin.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt index db01f9d7c0..dd70a31e99 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/MM640gPlugin.kt @@ -18,7 +18,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException 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 a640df98fa..91d313b5a7 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 @@ -25,7 +25,7 @@ import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt index d39a1d89a7..072d1953bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/PoctechPlugin.kt @@ -18,7 +18,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.JsonHelper.safeGetString import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt index 9f149f7a7b..6558d1a71a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/RandomBgPlugin.kt @@ -16,7 +16,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt index 7558878a5a..da48d8f46a 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/TomatoPlugin.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.interfaces.PluginType import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.utils.XDripBroadcast -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt index c9ce4a2123..98298f5272 100644 --- a/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt +++ b/app/src/main/java/info/nightscout/androidaps/plugins/source/XdripPlugin.kt @@ -17,7 +17,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.services.Intents -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt index 1bf2891a81..caf4bc9f49 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/CommandQueueImplementation.kt @@ -19,12 +19,10 @@ import info.nightscout.androidaps.database.entities.EffectiveProfileSwitch import info.nightscout.androidaps.database.entities.ProfileSwitch import info.nightscout.androidaps.database.interfaces.end import info.nightscout.androidaps.dialogs.BolusProgressDialog -import info.nightscout.androidaps.events.EventBolusRequested +import info.nightscout.androidaps.events.EventMobileToWear import info.nightscout.androidaps.events.EventProfileSwitchChanged import info.nightscout.androidaps.extensions.getCustomizedName import info.nightscout.androidaps.interfaces.* -import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning @@ -38,9 +36,12 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import io.reactivex.rxjava3.kotlin.subscribeBy @@ -297,7 +298,7 @@ class CommandQueueImplementation @Inject constructor( // not when the Bolus command is starting. The command closes the dialog upon completion). showBolusProgressDialog(detailedBolusInfo) // Notify Wear about upcoming bolus - rxBus.send(EventBolusRequested(detailedBolusInfo.insulin)) + rxBus.send(EventMobileToWear(EventData.BolusProgress(percent = 0, status = rh.gs(R.string.bolusrequested, detailedBolusInfo.insulin)))) } } notifyAboutNewCommand() diff --git a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt index 3bf816ade2..ee3d8e188c 100644 --- a/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt +++ b/app/src/main/java/info/nightscout/androidaps/queue/QueueThread.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBo import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveWorker.kt b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveWorker.kt index 3370908ea2..ff64871b33 100644 --- a/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/receivers/KeepAliveWorker.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.LocalAlertUtils import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.widget.updateWidget import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag 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 aad9ac4d0b..147e93b636 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWDefinition.kt @@ -30,7 +30,7 @@ import info.nightscout.androidaps.utils.AndroidPermission import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.extensions.isRunningTest -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt index c840b0c38a..bb82acec9a 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/SWScreen.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.setupwizard import dagger.android.HasAndroidInjector import info.nightscout.androidaps.setupwizard.elements.SWItem -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt index dcd71f41f9..4db19af5d0 100644 --- a/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt +++ b/app/src/main/java/info/nightscout/androidaps/setupwizard/elements/SWItem.kt @@ -13,7 +13,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.setupwizard.events.EventSWUpdate import info.nightscout.androidaps.utils.protection.PasswordCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.concurrent.Executors import java.util.concurrent.ScheduledFuture diff --git a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt index f1352441b4..1b099697f5 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt @@ -11,7 +11,7 @@ import android.widget.TableLayout import android.widget.TableRow import android.widget.TextView import info.nightscout.androidaps.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.SafeParse import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt index 6d32d15594..6262e552bc 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/AndroidPermission.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.general.overview.notifications.NotificationWithAction import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt b/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt index 3d8f75f2ab..a582bfa40c 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/BolusTimer.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputDelta import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBg import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDelta -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt b/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt index 1db8839916..0652e312db 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/CarbTimer.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputDelta import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerBg import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDelta -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import javax.inject.Inject import javax.inject.Singleton 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 063fd3137e..cf96415ef2 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/LocalAlertUtils.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNo import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/app/src/main/java/info/nightscout/androidaps/utils/TrendCalculator.kt b/app/src/main/java/info/nightscout/androidaps/utils/TrendCalculator.kt index 869feb2fe8..2d161808a6 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/TrendCalculator.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/TrendCalculator.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.entities.GlucoseValue import info.nightscout.androidaps.database.entities.GlucoseValue.TrendArrow.* -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt b/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt index e862fdcb6b..e688556d03 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/XDripBroadcast.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.services.Intents -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONArray import org.json.JSONException diff --git a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt index 4345775d02..9aebb55ccb 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/androidNotification/NotificationHolderImpl.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.MainActivity import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.IconsProvider import info.nightscout.androidaps.interfaces.NotificationHolder -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton 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 6f316e0ae8..2874cb7676 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 @@ -7,7 +7,7 @@ import android.widget.TableRow import android.widget.TextView import info.nightscout.androidaps.R import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class TIR(val date: Long, val lowThreshold: Double, val highThreshold: Double) { 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 6334d5bb91..91ef25a1f8 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 @@ -22,7 +22,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction 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 info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import javax.inject.Inject 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 22cd19e030..628c131788 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 @@ -16,7 +16,7 @@ import info.nightscout.androidaps.interfaces.ProfileFunction 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 info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton 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 4b691ec932..78b736b36c 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 @@ -31,7 +31,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProv import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign @@ -65,10 +65,14 @@ class BolusWizard @Inject constructor( private val disposable = CompositeDisposable() + var timeStamp : Long + init { injector.androidInjector().inject(this) + timeStamp = dateUtil.now() } + // Intermediate var sens = 0.0 private set @@ -236,7 +240,7 @@ class BolusWizard @Inject constructor( // Total calculatedTotalInsulin = insulinFromBG + insulinFromTrend + insulinFromCarbs + insulinFromBolusIOB + insulinFromBasalIOB + insulinFromCorrection + insulinFromSuperBolus + insulinFromCOB - var percentage = if (usePercentage) totalPercentage else percentageCorrection.toDouble() + val percentage = if (usePercentage) totalPercentage else percentageCorrection.toDouble() // Percentage adjustment totalBeforePercentageAdjustment = calculatedTotalInsulin diff --git a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizard.kt b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizard.kt index b48d44c9cc..88a4d4edc5 100644 --- a/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizard.kt +++ b/app/src/main/java/info/nightscout/androidaps/utils/wizard/QuickWizard.kt @@ -1,6 +1,5 @@ package info.nightscout.androidaps.utils.wizard -import android.util.Log import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.shared.sharedPreferences.SP @@ -9,6 +8,7 @@ import org.json.JSONObject import java.util.* import javax.inject.Inject import javax.inject.Singleton +import kotlin.collections.ArrayList @Singleton class QuickWizard @Inject constructor( @@ -55,6 +55,11 @@ class QuickWizard @Inject constructor( operator fun get(position: Int): QuickWizardEntry = QuickWizardEntry(injector).from(storage.get(position) as JSONObject, position) + fun list(): ArrayList = + ArrayList().also { + for (i in 0 until size()) it.add(get(i)) + } + fun get(guid: String): QuickWizardEntry? { for (i in 0 until storage.length()) { val entry = QuickWizardEntry(injector).from(storage.get(i) as JSONObject, i) @@ -66,7 +71,7 @@ class QuickWizard @Inject constructor( } fun move(from: Int, to: Int) { - Log.i("QuickWizard", "moveItem: $from $to") + //Log.i("QuickWizard", "moveItem: $from $to") val fromEntry = storage[from] as JSONObject storage.remove(from) addToPos(to, fromEntry, storage) diff --git a/app/src/main/java/info/nightscout/androidaps/widget/Widget.kt b/app/src/main/java/info/nightscout/androidaps/widget/Widget.kt index e123a4cc0e..b8b60ad34f 100644 --- a/app/src/main/java/info/nightscout/androidaps/widget/Widget.kt +++ b/app/src/main/java/info/nightscout/androidaps/widget/Widget.kt @@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.TrendCalculator -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/CalculationWorkflow.kt b/app/src/main/java/info/nightscout/androidaps/workflow/CalculationWorkflow.kt index d6a84cf8e5..ddae280577 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/CalculationWorkflow.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/CalculationWorkflow.kt @@ -22,7 +22,7 @@ import info.nightscout.androidaps.plugins.sensitivity.SensitivityOref1Plugin import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBasalDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBasalDataWorker.kt index 3310638636..b2bff7a245 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBasalDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBasalDataWorker.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.general.overview.OverviewData import info.nightscout.androidaps.plugins.general.overview.graphExtensions.ScaledDataPoint import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.receivers.DataWorker -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.ArrayList import javax.inject.Inject import kotlin.math.max diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBgDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBgDataWorker.kt index eb9941b419..16ad858693 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBgDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBgDataWorker.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Point import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.ArrayList import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBucketedDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBucketedDataWorker.kt index 54e98ec316..db2d6af09d 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBucketedDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareBucketedDataWorker.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.DataP import info.nightscout.androidaps.plugins.general.overview.graphExtensions.InMemoryGlucoseValueDataPoint import info.nightscout.androidaps.plugins.general.overview.graphExtensions.PointsWithLabelGraphSeries import info.nightscout.androidaps.receivers.DataWorker -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import javax.inject.Inject diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareIobAutosensGraphDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareIobAutosensGraphDataWorker.kt index 35046e295b..98d44743f0 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareIobAutosensGraphDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareIobAutosensGraphDataWorker.kt @@ -29,7 +29,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCa import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import java.util.ArrayList diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PreparePredictionsWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PreparePredictionsWorker.kt index ff57c4260c..0e94ce025a 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PreparePredictionsWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PreparePredictionsWorker.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Point import info.nightscout.androidaps.receivers.DataWorker import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject import kotlin.math.ceil diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTemporaryTargetDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTemporaryTargetDataWorker.kt index 49bedb98e2..db0fe96e2c 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTemporaryTargetDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTemporaryTargetDataWorker.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.OverviewData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.receivers.DataWorker -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import kotlin.math.max diff --git a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTreatmentsDataWorker.kt b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTreatmentsDataWorker.kt index f56e2056e6..6fa3f667e8 100644 --- a/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTreatmentsDataWorker.kt +++ b/app/src/main/java/info/nightscout/androidaps/workflow/PrepareTreatmentsDataWorker.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.Round import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.Translator -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class PrepareTreatmentsDataWorker( diff --git a/app/src/main/res/layout/wear_fragment.xml b/app/src/main/res/layout/wear_fragment.xml index a5eba31c66..059c85125e 100644 --- a/app/src/main/res/layout/wear_fragment.xml +++ b/app/src/main/res/layout/wear_fragment.xml @@ -10,29 +10,38 @@ android:layout_height="wrap_content" android:orientation="vertical"> - + + diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 2f37a9e9a6..d2eea647d5 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1211,6 +1211,7 @@ Hide loop records AndroidAPS widget Configure opacity + Loop status QR Code for setup one time password open settings diff --git a/app/src/main/res/values/wear.xml b/app/src/main/res/values/wear.xml new file mode 100644 index 0000000000..cc1a357cba --- /dev/null +++ b/app/src/main/res/values/wear.xml @@ -0,0 +1,25 @@ + + + + + + + androidaps_mobile + + diff --git a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 60788036e4..fb7412a3f3 100644 --- a/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/app/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.ArgumentMatchers.anyDouble diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt index 8c6c3186bb..ceb9141b7b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/aps/loop/LoopPluginTest.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt index 8f5500f6fa..2bd044ae26 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/configBuilder/ConfigBuilderPluginTest.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Before import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt index a512a2ce5f..6416d07307 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/bgQualityCheck/BgQualityCheckPluginTest.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore 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.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt index 69117ed385..986367bf2e 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/dstHelper/DstHelperPluginTest.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.Loop import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt index 540a0f038a..61a6e47654 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/objectives/ObjectivesPluginTest.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.constraints.objectives.objectives.Objective import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt index e3b723104a..0c70b07980 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/signatureVerifier/SignatureVerifierPluginTest.kt @@ -5,7 +5,7 @@ import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt index 605943e6d9..376f2f2474 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/constraints/storage/StorageConstraintPluginTest.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt index 7b1c3b9909..02ae75b90c 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/MaintenancePluginTest.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.Config 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.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt index 57f27309ec..aac7fc9774 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/nsclient/NsClientReceiverDelegateTest.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.events.EventChargingState import info.nightscout.androidaps.events.EventNetworkChange import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.receivers.ReceiverStatusStore -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt index 8d44fc6677..c29ca22e65 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/general/smsCommunicator/AuthRequestTest.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePas import info.nightscout.androidaps.plugins.general.smsCommunicator.otp.OneTimePasswordValidationResult import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt index c3437428ac..c906ad4b27 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinLyumjevPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt index 89397a2f31..1aada50c74 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefBasePluginTest.kt @@ -13,7 +13,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.insulin.InsulinOrefBasePlugin.Companion.MIN_DIA import info.nightscout.androidaps.utils.DefaultValueHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt index 52174ece95..c71c61655b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefFreePeakPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert.assertEquals import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt index f3539b9d5f..fb2a5f91da 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefRapidActingPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt index 2af78bd43b..2de46cf16b 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/insulin/InsulinOrefUltraRapidActingPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.interfaces.Insulin import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt index c9f1edf7f2..1f844ec3e7 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/pump/virtual/VirtualPumpPluginUTest.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt index f67b00b91d..d2985f7450 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/sensitivity/AbstractSensitivityPluginTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.interfaces.Sensitivity import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import org.junit.Assert diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt index e8719daa23..065a7d0d7f 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/GlimpPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt index f8822c7115..4c6a487343 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/MM640GPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt index c3dc928913..c7b5047c98 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/NSClientPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.interfaces.Config -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt b/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt index 120bbcd235..cc6e66c095 100644 --- a/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/plugins/source/XdripPluginTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.source import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector import info.nightscout.androidaps.TestBase -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test diff --git a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt index 88b8075457..be0eb00790 100644 --- a/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/queue/CommandQueueImplementationTest.kt @@ -4,9 +4,9 @@ import android.content.Context import android.os.PowerManager import dagger.android.AndroidInjector import dagger.android.HasAndroidInjector +import info.nightscout.androidaps.R import info.nightscout.androidaps.TestBaseWithProfile import info.nightscout.androidaps.TestPumpPlugin -import info.nightscout.androidaps.core.R import info.nightscout.androidaps.data.DetailedBolusInfo import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.database.AppRepository @@ -27,7 +27,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.buildHelper.BuildHelperImpl -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.core.Single @@ -138,6 +138,7 @@ class CommandQueueImplementationTest : TestBaseWithProfile() { `when`(constraintChecker.applyBasalPercentConstraints(anyObject(), anyObject())).thenReturn(percentageConstraint) `when`(rh.gs(R.string.connectiontimedout)).thenReturn("Connection timed out") `when`(rh.gs(R.string.formatinsulinunits)).thenReturn("%1\$.2f U") + `when`(rh.gs(R.string.bolusrequested)).thenReturn("Going to deliver %1\$.2f U") } @Test diff --git a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt index 6cec97fb42..97872fc3d2 100644 --- a/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt +++ b/app/src/test/java/info/nightscout/androidaps/utils/wizard/BolusWizardTest.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensDataStore import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.plugins.pump.virtual.VirtualPumpPlugin import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Test import org.mockito.Mock @@ -48,6 +48,7 @@ class BolusWizardTest : TestBase() { it.activePlugin = activePlugin it.commandQueue = commandQueue it.loop = loop + it.dateUtil = dateUtil it.iobCobCalculator = iobCobCalculator it.glucoseStatusProvider = GlucoseStatusProvider(aapsLogger = aapsLogger, iobCobCalculator = iobCobCalculator, dateUtil = dateUtil) } diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt index 4ca817fae2..0ab10c0cba 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationFragment.kt @@ -34,7 +34,7 @@ import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.dragHelpers.ItemTouchHelperAdapter import info.nightscout.androidaps.utils.dragHelpers.OnStartDragListener import info.nightscout.androidaps.utils.dragHelpers.SimpleItemTouchHelperCallback -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt index 80e07910f1..3335aad5c5 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/AutomationPlugin.kt @@ -24,7 +24,7 @@ import info.nightscout.androidaps.services.LocationServiceHelper 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt index 1161601056..a12ba56a7e 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/Action.kt @@ -6,7 +6,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONException import org.json.JSONObject import javax.inject.Inject diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt index c20789e4d0..4570c3e005 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/dialogs/ChooseOperationDialog.kt @@ -8,7 +8,7 @@ import android.widget.RadioButton import info.nightscout.androidaps.automation.databinding.AutomationDialogChooseOperationBinding import info.nightscout.androidaps.dialogs.DialogFragmentWithDate import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class ChooseOperationDialog : DialogFragmentWithDate() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt index c7f7149757..93f3827f55 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/Comparator.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class Comparator(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt index 6b18559767..4ce4d00a69 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorConnect.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class ComparatorConnect(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt index c9b1b421de..071388dab1 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/ComparatorExists.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class ComparatorExists(private val rh: ResourceHelper, var value: Compare = Compare.EXISTS) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt index ab82beffe0..f0c63f6415 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputCarePortalMenu.kt @@ -10,7 +10,7 @@ import androidx.annotation.DrawableRes import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.database.entities.TherapyEvent -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class InputCarePortalMenu(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt index d63cf0452c..54c97699af 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDateTime.kt @@ -14,7 +14,7 @@ import com.google.android.material.timepicker.MaterialTimePicker import com.google.android.material.timepicker.TimeFormat import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* class InputDateTime(private val rh: ResourceHelper, private val dateUtil: DateUtil, var value: Long = dateUtil.now()) : Element() { @@ -40,7 +40,7 @@ class InputDateTime(private val rh: ResourceHelper, private val dateUtil: DateUt getFragmentManager(root.context)?.let { fm -> MaterialDatePicker.Builder.datePicker() .setTheme(R.style.DatePicker) - .setSelection(dateUtil.timeStampToUtcDateMilis(value)) + .setSelection(dateUtil.timeStampToUtcDateMillis(value)) .build() .apply { addOnPositiveButtonClickListener { selection -> diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt index 946c0576e1..79ae4548a4 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDelta.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.ui.NumberPicker import java.text.DecimalFormat diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt index 4929bb3278..6c6fc96059 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputDropdownMenu.kt @@ -7,7 +7,7 @@ import android.widget.ArrayAdapter import android.widget.LinearLayout import android.widget.Spinner import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* class InputDropdownMenu(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt index 0a4200aae9..23c2167749 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputLocationMode.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import androidx.annotation.StringRes import info.nightscout.androidaps.automation.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class InputLocationMode(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt index d28a78408f..14f6bf46c7 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputProfileName.kt @@ -8,7 +8,7 @@ import android.widget.LinearLayout import android.widget.Spinner import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.interfaces.ActivePlugin -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class InputProfileName(private val rh: ResourceHelper, private val activePlugin: ActivePlugin, val name: String = "") : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt index 5ea6c66ff0..60175253ac 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTime.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* class InputTime(private val rh: ResourceHelper, private val dateUtil: DateUtil) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt index a417c1891b..7a953519bb 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputTimeRange.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.MidnightTime -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* class InputTimeRange(private val rh: ResourceHelper, private val dateUtil: DateUtil) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt index 648ee6a397..01ec8d00e9 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/LabelWithElement.kt @@ -4,7 +4,7 @@ import android.graphics.Typeface import android.view.Gravity import android.widget.LinearLayout import android.widget.TextView -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class LabelWithElement( private val rh: ResourceHelper, diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt index 2e31509ff8..60552f655b 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/StaticLabel.kt @@ -6,7 +6,7 @@ import android.widget.LinearLayout import android.widget.TextView import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class StaticLabel(private val rh: ResourceHelper) : Element() { diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt index 7946fccacd..c71eb696bd 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/Trigger.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.plugins.general.automation.events.EventTrigger import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.services.LastLocationDataContainer import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject diff --git a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt index d9cafef22e..3a7ff9258f 100644 --- a/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt +++ b/automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerConnector.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.automation.R import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.general.automation.dialogs.ChooseOperationDialog import info.nightscout.androidaps.utils.JsonHelper.safeGetString -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.ui.VerticalTextView import org.json.JSONArray import org.json.JSONObject diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt index 5b7b42b2f9..874077109b 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/AutomationEventTest.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.automation.actions.ActionLoopE import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnector import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerConnectorTest import info.nightscout.androidaps.plugins.general.automation.triggers.TriggerDummy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Assert import org.junit.Test diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt index 37e7e01ad7..84cda9cefb 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestBaseWithProfile.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.Mock diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt index b23fdcbb0e..134ffc7446 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/TestPumpPlugin.kt @@ -13,7 +13,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.TimeChangeType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject @Suppress("MemberVisibilityCanBePrivate") diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt index d49a9fcc83..ebdc64227a 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionAlarmTest.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputStrin import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.TimerUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Before import org.junit.Test diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt index a43794571e..7d607b32d0 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionNotificationTest.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.database.transactions.Transaction import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import io.reactivex.rxjava3.core.Completable import org.junit.Assert import org.junit.Before diff --git a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt index d1abc821dc..783fcbb2e6 100644 --- a/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt +++ b/automation/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionsTestBase.kt @@ -11,7 +11,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.general.automation.TestBaseWithProfile import info.nightscout.androidaps.plugins.general.automation.triggers.Trigger -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Before import org.mockito.Mock diff --git a/build.gradle b/build.gradle index 485c840d99..d2b9b12afb 100644 --- a/build.gradle +++ b/build.gradle @@ -10,7 +10,7 @@ buildscript { room_version = '2.4.2' lifecycle_version = '2.4.1' dagger_version = '2.41' - coroutines_version = '1.4.1' + coroutines_version = '1.6.1' activity_version = '1.3.1' fragmentktx_version = '1.3.6' ormLite_version = '4.46' @@ -19,12 +19,13 @@ buildscript { material_version = '1.4.0' constraintlayout_version = '2.1.0' preferencektx_version = '1.2.0' - commonslang3_version = '3.11' + commonslang3_version = '3.12.0' commonscodec_version = '1.15' jodatime_version = '2.10.14' work_version = '2.5.0' tink_version = '1.5.0' json_version = '20220320' + joga_version = '2.10.14' junit_version = '4.13.2' mockito_version = '4.4.0' @@ -51,6 +52,7 @@ buildscript { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-allopen:$kotlin_version" + classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version" classpath 'com.hiya:jacoco-android:0.2' } } diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.kt b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.kt index 91b6a34aa0..726b169505 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.kt +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboFragment.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.events.EventQueueChanged import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java index db413a0130..c0d416679a 100644 --- a/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java +++ b/combo/src/main/java/info/nightscout/androidaps/plugins/pump/combo/ComboPlugin.java @@ -61,7 +61,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.InstanceId; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.shared.logging.AAPSLogger; import info.nightscout.shared.logging.LTag; import info.nightscout.shared.sharedPreferences.SP; @@ -1343,7 +1343,7 @@ public class ComboPlugin extends PumpPluginBase implements Pump, Constraints { } private String fakeSerialNumber() { - return InstanceId.INSTANCE.instanceId(); + return InstanceId.INSTANCE.getInstanceId(); } @NonNull @Override diff --git a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt index debaf34b2d..cbf204c960 100644 --- a/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt +++ b/combo/src/test/java/info/nightscout/androidaps/plugins/pump/combo/ComboPluginTest.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.RuffyScripter import info.nightscout.androidaps.plugins.pump.combo.ruffyscripter.history.Bolus import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert import org.junit.Before diff --git a/core/core_dependencies.gradle b/core/core_dependencies.gradle index a84479cf9f..c88b6f4d48 100644 --- a/core/core_dependencies.gradle +++ b/core/core_dependencies.gradle @@ -5,6 +5,8 @@ dependencies { api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" + api "org.jetbrains.kotlinx:kotlinx-coroutines-guava:$coroutines_version" + api "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:$coroutines_version" api "androidx.core:core-ktx:$core_version" api 'androidx.legacy:legacy-support-v13:1.0.0' api 'androidx.legacy:legacy-support-v4:1.0.0' @@ -25,7 +27,7 @@ dependencies { api "com.google.dagger:dagger-android-support:$dagger_version" //Firebase - api platform('com.google.firebase:firebase-bom:25.12.0') + api platform('com.google.firebase:firebase-bom:29.3.0') api "com.google.firebase:firebase-analytics-ktx" api "com.google.firebase:firebase-crashlytics-ktx" api "com.google.firebase:firebase-messaging-ktx" @@ -73,7 +75,6 @@ dependencies { api "com.squareup.retrofit2:converter-gson:$retrofit2_version" api "com.joanzapata.iconify:android-iconify-fontawesome:2.2.2" - api 'net.danlew:android.joda:2.10.6' api "androidx.fragment:fragment-ktx:$fragmentktx_version" api "androidx.constraintlayout:constraintlayout:$constraintlayout_version" diff --git a/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt b/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt index 554f4a959c..ea418995aa 100644 --- a/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/activities/DaggerAppCompatActivityWithResult.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.interfaces.ImportExportPrefs import info.nightscout.androidaps.plugins.general.maintenance.PrefsFileContract import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.permissions.OptimizationPermissionContract -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import javax.inject.Inject diff --git a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt index 57f95bfc74..6c3e5b29db 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/ProfileSealed.kt @@ -21,7 +21,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONArray import org.json.JSONObject import java.text.DecimalFormat @@ -376,7 +376,7 @@ sealed class ProfileSealed( var elapsedSec = 0 array.shiftBlock(multiplier, timeshift).forEach { if (elapsedSec != 0) sb.append("\n") - sb.append(dateUtil.format_HH_MM(elapsedSec)) + sb.append(dateUtil.formatHHMM(elapsedSec)) .append(" ") .append(format.format(it.amount * multiplier)) .append(" $units") @@ -389,7 +389,7 @@ sealed class ProfileSealed( var elapsedSec = 0 array.shiftTargetBlock(timeshift).forEach { if (elapsedSec != 0) sb.append("\n") - sb.append(dateUtil.format_HH_MM(elapsedSec)) + sb.append(dateUtil.formatHHMM(elapsedSec)) .append(" ") .append(format.format(it.lowTarget)) .append(" - ") diff --git a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt index 77985485bb..fd0f0fe33f 100644 --- a/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/data/PumpEnactResult.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import javax.inject.Inject diff --git a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt index c714474d6b..5f50f0c4c1 100644 --- a/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt +++ b/core/src/main/java/info/nightscout/androidaps/di/CoreModule.kt @@ -5,7 +5,7 @@ import android.telephony.SmsManager import dagger.Module import dagger.Provides import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.resources.ResourceHelperImplementation import javax.inject.Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt index aef283c223..8b6368bc0c 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/BolusProgressDialog.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventDismissBolusProgressIfRunning import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt index a7bff8e52b..d034427cc9 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/DialogFragmentWithDate.kt @@ -81,7 +81,7 @@ abstract class DialogFragmentWithDate : DaggerDialogFragment() { eventDateView = view.findViewById(R.id.eventdate) as TextView? eventDateView?.text = dateUtil.dateString(eventTime) eventDateView?.setOnClickListener { - val selection = dateUtil.timeStampToUtcDateMilis(eventTime) + val selection = dateUtil.timeStampToUtcDateMillis(eventTime) MaterialDatePicker.Builder.datePicker() .setTheme(R.style.DatePicker) .setSelection(selection) diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt index cce02ab08d..1b542c181e 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/NtpProgressDialog.kt @@ -13,7 +13,7 @@ import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt index 2a174bf545..99fdc2f917 100644 --- a/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt +++ b/core/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt @@ -26,7 +26,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.HtmlHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import java.text.DecimalFormat import javax.inject.Inject @@ -231,7 +231,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = profile1.getBasalTimeFromMidnight(hour * 60 * 60) val val2 = profile2.getBasalTimeFromMidnight(hour * 60 * 60) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.00"), " " + rh.gs(R.string.profile_ins_units_per_hour))) + s.append(formatColors(dateUtil.formatHHMM(hour * 60 * 60), val1, val2, DecimalFormat("0.00"), " " + rh.gs(R.string.profile_ins_units_per_hour))) s.append("
") } prev1 = val1 @@ -254,7 +254,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = profile1.getIcTimeFromMidnight(hour * 60 * 60) val val2 = profile2.getIcTimeFromMidnight(hour * 60 * 60) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), " " + rh.gs(R.string.profile_carbs_per_unit))) + s.append(formatColors(dateUtil.formatHHMM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), " " + rh.gs(R.string.profile_carbs_per_unit))) s.append("
") } prev1 = val1 @@ -272,7 +272,7 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1 = Profile.fromMgdlToUnits(profile1.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) val val2 = Profile.fromMgdlToUnits(profile2.getIsfMgdlTimeFromMidnight(hour * 60 * 60), units) if (val1 != prev1 || val2 != prev2) { - s.append(formatColors(dateUtil.format_HH_MM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), units.asText + " " + rh.gs(R.string.profile_per_unit))) + s.append(formatColors(dateUtil.formatHHMM(hour * 60 * 60), val1, val2, DecimalFormat("0.0"), units.asText + " " + rh.gs(R.string.profile_per_unit))) s.append("
") } prev1 = val1 @@ -293,8 +293,8 @@ class ProfileViewerDialog : DaggerDialogFragment() { val val1h = profile1.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60) val val2l = profile2.getTargetLowMgdlTimeFromMidnight(hour * 60 * 60) val val2h = profile2.getTargetHighMgdlTimeFromMidnight(hour * 60 * 60) - val txt1 = dateUtil.format_HH_MM(hour * 60 * 60) + " " + Profile.toUnitsString(val1l, val1l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString(val1h, val1h * Constants.MGDL_TO_MMOLL, units) + " " + units.asText - val txt2 = dateUtil.format_HH_MM(hour * 60 * 60) + " " + Profile.toUnitsString(val2l, val2l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString(val2h, val2h * Constants.MGDL_TO_MMOLL, units) + " " + units.asText + val txt1 = dateUtil.formatHHMM(hour * 60 * 60) + " " + Profile.toUnitsString(val1l, val1l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString(val1h, val1h * Constants.MGDL_TO_MMOLL, units) + " " + units.asText + val txt2 = dateUtil.formatHHMM(hour * 60 * 60) + " " + Profile.toUnitsString(val2l, val2l * Constants.MGDL_TO_MMOLL, units) + " - " + Profile.toUnitsString(val2h, val2h * Constants.MGDL_TO_MMOLL, units) + " " + units.asText if (val1l != prev1l || val1h != prev1h || val2l != prev2l || val2h != prev2h) { s.append(formatColors(txt1, txt2)) s.append("
") diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt b/core/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt index 716b2b1810..36650f1838 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventNetworkChange.kt @@ -1,7 +1,5 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.utils.StringUtils - class EventNetworkChange : Event() { var mobileConnected = false diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventNtpStatus.kt b/core/src/main/java/info/nightscout/androidaps/events/EventNtpStatus.kt index 0ad455836a..46b90b33f4 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventNtpStatus.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventNtpStatus.kt @@ -1,5 +1,3 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.events.Event - class EventNtpStatus(val status: String, val percent: Int) : Event() \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt b/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt index 04afc9e486..c285193dfc 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventPreferenceChange.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class EventPreferenceChange : Event { diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt b/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt index 1b6332a6d3..935ef1d008 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventPumpStatusChanged.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.events import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class EventPumpStatusChanged : EventStatus { diff --git a/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt b/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt index bb88f3529a..abd89071d3 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt +++ b/core/src/main/java/info/nightscout/androidaps/events/EventStatus.kt @@ -1,6 +1,6 @@ package info.nightscout.androidaps.events -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper // pass string to startup wizard abstract class EventStatus : Event() { diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt b/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt index 44b1f04c8a..f22227f657 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/HtmlString.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.extensions import android.content.Context import androidx.annotation.AttrRes import androidx.annotation.ColorRes -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper fun String.formatBold(): String = "$this" diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt b/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt index f4c9d40271..acbccbb4e5 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/JSONObjectExt.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.extensions import androidx.annotation.StringRes -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt index d4455ceb80..3df0a31f2e 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TemporaryTargetExtension.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import java.util.concurrent.TimeUnit diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt index 15cc907285..017267d7c9 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TherapyEventExtension.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.general.nsclient.data.NSMbg import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import java.util.concurrent.TimeUnit diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt index 5d722ad2ab..4b469c7395 100644 --- a/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt +++ b/core/src/main/java/info/nightscout/androidaps/extensions/TotalDailyDoseExtension.kt @@ -8,7 +8,7 @@ import android.widget.TextView import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.TotalDailyDose import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper val TotalDailyDose.total get() = if (totalAmount > 0) totalAmount else basalAmount + bolusAmount diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt index 6855a814bc..c57fc847ba 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PluginBase.kt @@ -5,7 +5,7 @@ import androidx.preference.PreferenceFragmentCompat import dagger.android.HasAndroidInjector import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper /** * Created by mike on 09.06.2016. diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt index 7c808c3bbc..d935495eb8 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/Profile.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter.to0Decimal import info.nightscout.androidaps.utils.DecimalFormatter.to1Decimal import info.nightscout.androidaps.utils.HardLimits import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.joda.time.DateTime import org.json.JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt index ff11f79612..3e3e239216 100644 --- a/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt +++ b/core/src/main/java/info/nightscout/androidaps/interfaces/PumpPluginBase.kt @@ -4,7 +4,7 @@ import android.os.SystemClock import dagger.android.HasAndroidInjector import info.nightscout.androidaps.core.R import info.nightscout.shared.logging.AAPSLogger -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper abstract class PumpPluginBase( pluginDescription: PluginDescription, diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt index 210141202d..c96b0b405b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/aps/loop/APSResult.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HtmlHelper.fromHtml -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt index fa06aae7f6..37ff0a5983 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/configBuilder/RunningConfiguration.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.JsonHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.json.JSONException import org.json.JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt index 485d2e7c5a..d1b50c3871 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt @@ -11,7 +11,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.io.IOException import java.net.URL diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt index e7234602b0..0154bca89b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/PrefFileListProvider.kt @@ -6,7 +6,7 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.Config import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionCheckerUtils import info.nightscout.androidaps.plugins.general.maintenance.formats.* -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage import org.joda.time.DateTime import org.joda.time.Days diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt index 040a3d65cd..2bc71881ef 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/activities/PrefImportListActivity.kt @@ -20,7 +20,7 @@ import info.nightscout.androidaps.plugins.general.maintenance.PrefsFileContract import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsMetadataKey import info.nightscout.androidaps.plugins.general.maintenance.formats.PrefsStatus import info.nightscout.androidaps.utils.locale.LocaleHelper -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class PrefImportListActivity : DaggerAppCompatActivity() { diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt index 39f7c2f550..1f14541e0a 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormat.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.utils.CryptoUtil import info.nightscout.androidaps.extensions.hexStringToByteArray import info.nightscout.androidaps.extensions.toHex -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.storage.Storage import org.json.JSONException import org.json.JSONObject diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt index 7f83f953d6..d37ec7f2c8 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/CobInfo.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.iob.iobCobCalculator import info.nightscout.androidaps.core.R import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper /** All COB up to now, including carbs not yet processed by IobCob calculation. */ class CobInfo(val timestamp: Long, val displayCob: Double?, val futureCarbs: Double) { diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt index 9174afced3..5da825a6d5 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/iob/iobCobCalculator/data/AutosensData.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Point import info.nightscout.androidaps.plugins.general.overview.graphExtensions.Scale import info.nightscout.androidaps.plugins.iob.iobCobCalculator.AutosensResult import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt index 8913f54436..20d93069a3 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/PumpSyncImplementation.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt index 6e836a077b..716aad98ce 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/ble/BlePreCheck.kt @@ -14,7 +14,7 @@ import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import info.nightscout.androidaps.core.R import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt index 10740a2b52..cd59d1413b 100644 --- a/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt +++ b/core/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpType.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.database.embedments.InterfaceIDs import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.plugins.common.ManufacturerType import info.nightscout.androidaps.utils.Round -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import kotlin.math.min @Suppress("unused") diff --git a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt index 080360f9ff..c180436adb 100644 --- a/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt +++ b/core/src/main/java/info/nightscout/androidaps/queue/commands/Command.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.queue.Callback -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject abstract class Command( diff --git a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt index e48d2836a5..5fbe786c73 100644 --- a/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt +++ b/core/src/main/java/info/nightscout/androidaps/services/AlarmSoundService.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.NotificationHolder import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject import kotlin.math.ln diff --git a/core/src/main/java/info/nightscout/androidaps/utils/ActionModeHelper.kt b/core/src/main/java/info/nightscout/androidaps/utils/ActionModeHelper.kt index 5a928bc8eb..ce417be71b 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/ActionModeHelper.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/ActionModeHelper.kt @@ -8,7 +8,7 @@ import android.view.MenuItem import androidx.fragment.app.FragmentActivity import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class ActionModeHelper(val rh: ResourceHelper, val activity: FragmentActivity?) { diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt b/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt index 7c2a96f46b..864e0153ba 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/DecimalFormatter.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.utils import info.nightscout.androidaps.core.R import info.nightscout.androidaps.interfaces.Pump -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat object DecimalFormatter { diff --git a/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt b/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt index 9c6fc45c17..254342a880 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/HardLimits.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction import info.nightscout.shared.logging.AAPSLogger import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/core/src/main/java/info/nightscout/androidaps/utils/InstanceId.kt b/core/src/main/java/info/nightscout/androidaps/utils/InstanceId.kt index 64c84fcaa9..a5cd3187f0 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/InstanceId.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/InstanceId.kt @@ -1,10 +1,13 @@ package info.nightscout.androidaps.utils -import com.google.firebase.iid.FirebaseInstanceId +import com.google.firebase.installations.FirebaseInstallations object InstanceId { - fun instanceId(): String { - var id = FirebaseInstanceId.getInstance().id - return id + var instanceId : String = "" + + init { + FirebaseInstallations.getInstance().id.addOnCompleteListener { + instanceId = it.result + } } } \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt index cea0d146de..ea6874a79e 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/TimerUtil.kt @@ -4,7 +4,7 @@ import android.content.Context import android.content.Intent import android.provider.AlarmClock import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt b/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt index c386e0703c..c65eea32a1 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/Translator.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt b/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt index bde450ec77..58b3a439e1 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/WarnColors.kt @@ -4,7 +4,7 @@ import android.widget.TextView import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.entities.TherapyEvent import info.nightscout.androidaps.extensions.isOlderThan -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import javax.inject.Singleton diff --git a/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt b/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt index 75db45e99d..d6e070f85b 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelperImplementation.kt @@ -14,6 +14,7 @@ import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.view.ContextThemeWrapper import androidx.core.content.ContextCompat import info.nightscout.androidaps.core.R +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.FabricPrivacy import java.util.* import javax.inject.Inject diff --git a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt index 9f2daa57b4..7ec9e11440 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt +++ b/core/src/main/java/info/nightscout/androidaps/utils/userEntry/UserEntryPresentationHelper.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.Translator -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject @Reusable diff --git a/core/src/main/res/values/strings.xml b/core/src/main/res/values/strings.xml index 4c4a0f2322..fc94c704ef 100644 --- a/core/src/main/res/values/strings.xml +++ b/core/src/main/res/values/strings.xml @@ -210,34 +210,6 @@ Location Is Not Enabled For Bluetooth discovery to work on newer devices, location must be enabled. AAPS does not track your location and it can be disabled after pairing is successful. - - %1$d m ago - %1$d minutes ago - %1$.1f h ago - %1$.1f days ago - %1$.0f days ago - in %1$.0f days - in %1$.0f days - h - days - hours - second - minute - hour - day - week - seconds - minutes - hours - days - weeks - m - d - Later today - Tomorrow - Today - Yesterday - Wrong password Wrong PIN diff --git a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index edc280d55e..d2b0723d59 100644 --- a/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/core/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.Mock diff --git a/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt index aa0b66ab55..fd28bdb158 100644 --- a/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/data/ProfileTest.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.HardLimits -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject @@ -78,7 +78,7 @@ class ProfileTest : TestBase() { // JSONAssert.assertEquals(JSONObject(okProfile), p.toPureNsJson(dateUtil), false) Assert.assertEquals(5.0, p.dia, 0.01) // Assert.assertEquals(TimeZone.getTimeZone("UTC"), p.timeZone) - Assert.assertEquals("00:30", dateUtil.format_HH_MM(30 * 60)) + Assert.assertEquals("00:30", dateUtil.formatHHMM(30 * 60)) val c = Calendar.getInstance() c[Calendar.HOUR_OF_DAY] = 1 c[Calendar.MINUTE] = 0 diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt index 0bc70c0345..da7413d2b5 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/contraints/versionChecker/VersionCheckerUtilsKtTest.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.constraints.versionChecker.VersionChec import info.nightscout.androidaps.plugins.constraints.versionChecker.numericVersionPart import info.nightscout.androidaps.receivers.ReceiverStatusStore import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals diff --git a/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt b/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt index 5b063a69f0..c2dba9041a 100644 --- a/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/plugins/general/maintenance/formats/EncryptedPrefsFormatTest.kt @@ -2,7 +2,7 @@ package info.nightscout.androidaps.plugins.general.maintenance.formats import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.utils.CryptoUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.hamcrest.CoreMatchers import org.junit.Assert diff --git a/core/src/test/java/info/nightscout/androidaps/pump/common/utils/DateTimeUtilUTest.java b/core/src/test/java/info/nightscout/androidaps/pump/common/utils/DateTimeUtilUTest.java index f5557f5eff..8a8bc558b7 100644 --- a/core/src/test/java/info/nightscout/androidaps/pump/common/utils/DateTimeUtilUTest.java +++ b/core/src/test/java/info/nightscout/androidaps/pump/common/utils/DateTimeUtilUTest.java @@ -1,7 +1,5 @@ package info.nightscout.androidaps.pump.common.utils; -import android.util.Log; - import org.junit.Assert; import org.junit.Test; @@ -19,7 +17,7 @@ public class DateTimeUtilUTest { Assert.assertEquals(65, aTechDateDifferenceAsMinutes); - Log.d("DateTimeUtilUTest", "Time difference: " + aTechDateDifferenceAsMinutes); + //Log.d("DateTimeUtilUTest", "Time difference: " + aTechDateDifferenceAsMinutes); } } \ No newline at end of file diff --git a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt index bdd23eec47..793aa2241b 100644 --- a/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt +++ b/core/src/test/java/info/nightscout/androidaps/utils/DateUtilTest.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.utils import android.content.Context import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.junit.Assert import org.junit.Test import org.mockito.Mock diff --git a/crowdin.yml b/crowdin.yml index d310b71a91..ec9551d875 100644 --- a/crowdin.yml +++ b/crowdin.yml @@ -13,6 +13,8 @@ files: translation: /core/src/main/res/values-%android_code%/validator.xml - source: /core/src/main/res/values/strings.xml translation: /core/src/main/res/values-%android_code%/strings.xml + - source: /shared/src/main/res/values/strings.xml + translation: /shared/src/main/res/values-%android_code%/strings.xml - source: /combo/src/main/res/values/strings.xml translation: /combo/src/main/res/values-%android_code%/strings.xml - source: /dana/src/main/res/values/strings.xml diff --git a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt index 5c05c66ac9..6f3f374774 100644 --- a/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt +++ b/dana/src/main/java/info/nightscout/androidaps/dana/DanaFragment.kt @@ -38,7 +38,7 @@ import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.interfaces.Dana -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 87720e4950..9f7ca05400 100644 --- a/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/dana/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.Mock diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt index ca26113831..55e4139aae 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/DanaRKoreanPlugin.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType 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 +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java index cb5992d77e..56efea9bea 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRKorean/services/DanaRKoreanExecutionService.java @@ -58,7 +58,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; public class DanaRKoreanExecutionService extends AbstractDanaRExecutionService { @Inject AAPSLogger aapsLogger; diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java index b08d7ec6f1..fe56e12d89 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/DanaRv2Plugin.java @@ -36,7 +36,7 @@ import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java index 8000770e7a..19debd1571 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danaRv2/services/DanaRv2ExecutionService.java @@ -72,7 +72,7 @@ import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.shared.sharedPreferences.SP; public class DanaRv2ExecutionService extends AbstractDanaRExecutionService { diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java index b048e0a0ee..a290c4e520 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/AbstractDanaRPlugin.java @@ -37,7 +37,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.Round; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java index 3c6a76fc65..90fd97ed88 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/DanaRPlugin.java @@ -33,7 +33,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; 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; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt index 571db17cbf..491bb0b040 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt +++ b/danar/src/main/java/info/nightscout/androidaps/danar/comm/MessageBase.kt @@ -17,7 +17,7 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInf import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage import info.nightscout.androidaps.utils.CRC.getCrc16 import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import org.joda.time.DateTime diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java index f0a45f95f6..a1b7cbf09a 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/AbstractDanaRExecutionService.java @@ -50,7 +50,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.ToastUtils; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java index 76682b9690..623eae8ec5 100644 --- a/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java +++ b/danar/src/main/java/info/nightscout/androidaps/danar/services/DanaRExecutionService.java @@ -62,7 +62,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.plugins.pump.common.defs.PumpType; import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.queue.commands.Command; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.shared.sharedPreferences.SP; public class DanaRExecutionService extends AbstractDanaRExecutionService { diff --git a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index 0f4afa0fe6..2f763bb49d 100644 --- a/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danar/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.interfaces.ProfileStore import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.ArgumentMatchers.anyDouble diff --git a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt index a55c10eb14..2f198bafb4 100644 --- a/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt +++ b/danar/src/test/java/info/nightscout/androidaps/plugins/pump/danaR/comm/DanaRTestBase.kt @@ -19,7 +19,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Before import org.mockito.ArgumentMatchers diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt index a7fa909d6d..8d7a08cce6 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/DanaRSPlugin.kt @@ -34,7 +34,7 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalSt import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.* import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt index 2eb9674763..12e5fb594f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketAPSHistoryEvents.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.joda.time.DateTime import org.joda.time.DateTimeZone diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt index 4aadd6074a..8a2f944c6f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBasalGetBasalRate.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt index edd932e62f..26eedd9d47 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusGetBolusOption.kt @@ -9,7 +9,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class DanaRSPacketBolusGetBolusOption( diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt index e8a0e25780..17ee4ca4c3 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketBolusSetStepBolusStop.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject open class DanaRSPacketBolusSetStepBolusStop( diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt index f7f38d9878..160bbfa12c 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketGeneralGetPumpCheck.kt @@ -8,7 +8,7 @@ import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotifi import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class DanaRSPacketGeneralGetPumpCheck( diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt index 43c694c49f..d68e90f8ca 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyAlarm.kt @@ -9,7 +9,7 @@ import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class DanaRSPacketNotifyAlarm( diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt index b1c0b5f53a..b98ab5a35b 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryComplete.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import kotlin.math.min diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt index f121e6349c..34408da245 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRSPacketNotifyDeliveryRateDisplay.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.danars.encryption.BleEncryption -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import kotlin.math.min diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java index 3c6eecd72c..e54d3b2a3f 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java +++ b/danars/src/main/java/info/nightscout/androidaps/danars/dialogs/PairingProgressDialog.java @@ -21,7 +21,7 @@ import info.nightscout.androidaps.danars.databinding.DanarsPairingProgressDialog import info.nightscout.androidaps.danars.events.EventDanaRSPairingSuccess; import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt index b7fd9fe286..248583eb66 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/BLEComm.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.ToastUtils -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt index a75ec48fd4..7510b9f7a3 100644 --- a/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt +++ b/danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt @@ -40,7 +40,7 @@ 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable diff --git a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt index edc280d55e..d2b0723d59 100644 --- a/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt +++ b/danars/src/test/java/info/nightscout/androidaps/TestBaseWithProfile.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.json.JSONObject import org.junit.Before import org.mockito.Mock diff --git a/database/build.gradle b/database/build.gradle index 85fec1fec0..a524196d9e 100644 --- a/database/build.gradle +++ b/database/build.gradle @@ -18,8 +18,11 @@ android { } dependencies { + // shared needed for OpenForTesting + implementation project(':shared') + api "androidx.core:core-ktx:$core_version" - api "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" + api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" api "io.reactivex.rxjava3:rxjava:$rxjava_version" api "io.reactivex.rxjava3:rxandroid:$rxandroid_version" diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt index 417b436421..5a503a2247 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Fragment.kt @@ -27,7 +27,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.WarnColors -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt index 518d31b723..86bb00221a 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/DiaconnG8Plugin.kt @@ -31,7 +31,7 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInf import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.* -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt index 12e2bcbcab..f0da17ea6c 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BasalLimitInquireResponsePacket.kt @@ -4,7 +4,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.androidaps.diaconn.R import info.nightscout.androidaps.diaconn.pumplog.PumplogUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt index e65ef691cb..a209046b96 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigAPSMainInfoInquireResponsePacket.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.androidaps.diaconn.R import info.nightscout.androidaps.diaconn.pumplog.PumplogUtil import info.nightscout.shared.logging.LTag -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.joda.time.DateTime import javax.inject.Inject diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt index f224d7d834..fe347adbf0 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigLogInquireResponsePacket.kt @@ -23,7 +23,7 @@ import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInf import info.nightscout.androidaps.plugins.pump.common.bolusInfo.TemporaryBasalStorage import info.nightscout.androidaps.plugins.pump.common.defs.PumpType import info.nightscout.androidaps.utils.T -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import org.apache.commons.lang3.time.DateUtils diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt index 72ba65f70b..42c8146661 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/BigMainInfoInquireResponsePacket.kt @@ -7,7 +7,7 @@ import info.nightscout.androidaps.diaconn.pumplog.PumplogUtil import info.nightscout.androidaps.interfaces.PumpDescription import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.pump.common.defs.PumpType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.joda.time.DateTime import javax.inject.Inject diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt index 9dd4a5f315..1571c53b44 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/IncarnationInquireResponsePacket.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.diaconn.packet import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import javax.inject.Inject diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt index 9866222bb5..19bdd92f46 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionExtendedBolusResultReportPacket.kt @@ -4,7 +4,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject /** diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt index 83a2c19675..8a9fde09c0 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/packet/InjectionSnackResultReportPacket.kt @@ -4,7 +4,7 @@ import dagger.android.HasAndroidInjector import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject /** diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt index 4cff23153c..be2969ea4b 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/BLECommonService.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.extensions.waitMillis import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import java.util.concurrent.ScheduledFuture import javax.inject.Inject diff --git a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt index 43caae85d4..85e84d4b29 100644 --- a/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt +++ b/diaconn/src/main/java/info/nightscout/androidaps/diaconn/service/DiaconnG8Service.kt @@ -42,7 +42,7 @@ 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java index daf72b78db..1a48c9d960 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/InsightAlertService.java @@ -38,7 +38,7 @@ import info.nightscout.androidaps.plugins.pump.insight.exceptions.app_layer_erro import info.nightscout.androidaps.plugins.pump.insight.utils.AlertUtils; import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator; import info.nightscout.androidaps.utils.HtmlHelper; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; public class InsightAlertService extends DaggerService implements InsightConnectionService.StateCallback { diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java index ecf8638a36..b591f2f4c2 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightFragment.java @@ -35,7 +35,7 @@ import info.nightscout.androidaps.queue.Callback; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DecimalFormatter; import info.nightscout.androidaps.utils.FabricPrivacy; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java index 7e94fd760d..65ee805c6a 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/LocalInsightPlugin.java @@ -130,7 +130,7 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.ExceptionTranslator import info.nightscout.androidaps.plugins.pump.insight.utils.ParameterBlockUtil; import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.shared.sharedPreferences.SP; @Singleton diff --git a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt index 9227816104..bb30687792 100644 --- a/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt +++ b/insight/src/main/java/info/nightscout/androidaps/plugins/pump/insight/utils/AlertUtils.kt @@ -4,7 +4,7 @@ import info.nightscout.androidaps.insight.R import info.nightscout.androidaps.plugins.pump.insight.descriptors.Alert import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertCategory import info.nightscout.androidaps.plugins.pump.insight.descriptors.AlertType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import javax.inject.Inject import javax.inject.Singleton diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt index 24d6904f2f..e3e0642a70 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicFragment.kt @@ -42,7 +42,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.WarnColors import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt index 27e53ba7c5..a4e660fe4c 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/MedtronicPumpPlugin.kt @@ -54,7 +54,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil.Comp 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.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt index 3ab64f8c3d..b92ce04b36 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/ui/MedtronicUIPostprocessor.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificat import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicUIResponseType import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.joda.time.DateTimeZone import org.joda.time.Duration import java.util.* diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt index cfc7b95da6..a1b672e506 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryData.kt @@ -28,7 +28,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.PumpBolusType 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.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.apache.commons.lang3.StringUtils import org.joda.time.LocalDateTime diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt index 92eee8f170..4cf5637b3f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/data/dto/RLHistoryItemMedtronic.kt @@ -3,7 +3,7 @@ package info.nightscout.androidaps.plugins.pump.medtronic.data.dto import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.joda.time.LocalDateTime class RLHistoryItemMedtronic(private val medtronicCommandType: MedtronicCommandType) : diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt index 70ddb70c91..0ca333fd3b 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/dialog/MedtronicHistoryActivity.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpHistoryEntryGroup import info.nightscout.androidaps.plugins.pump.medtronic.R import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry import info.nightscout.androidaps.plugins.pump.medtronic.data.MedtronicHistoryData -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* import javax.inject.Inject diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt index af528a521e..504994800f 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/driver/MedtronicPumpStatus.kt @@ -12,7 +12,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.BasalProfileStatus import info.nightscout.androidaps.plugins.pump.medtronic.defs.BatteryType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicConst -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import java.util.* import javax.inject.Inject diff --git a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt index bd646bafb8..31a2e8c150 100644 --- a/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt +++ b/medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/util/MedtronicUtil.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicCommandTy import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicNotificationType import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import org.joda.time.LocalTime import java.nio.ByteBuffer import java.nio.ByteOrder diff --git a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt index 89130376b9..14d3a7e1b2 100644 --- a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt +++ b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/pump/MedtronicPumpHistoryDecoderUTest.kt @@ -10,7 +10,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RawHistory import info.nightscout.androidaps.plugins.pump.medtronic.defs.MedtronicDeviceType import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import info.nightscout.shared.sharedPreferences.SP import org.junit.Assert diff --git a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryDataUTest.kt b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryDataUTest.kt index 7b093e3a5b..fb14af8230 100644 --- a/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryDataUTest.kt +++ b/medtronic/src/test/java/info/nightscout/androidaps/plugins/pump/medtronic/data/MedtronicHistoryDataUTest.kt @@ -16,7 +16,7 @@ import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpH import info.nightscout.androidaps.plugins.pump.medtronic.data.dto.TempBasalPair import info.nightscout.androidaps.plugins.pump.medtronic.driver.MedtronicPumpStatus import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import org.junit.Test diff --git a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/fragment/WizardFragmentBase.kt b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/fragment/WizardFragmentBase.kt index cff60a0a1d..1781757032 100644 --- a/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/fragment/WizardFragmentBase.kt +++ b/omnipod-common/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/common/ui/wizard/common/fragment/WizardFragmentBase.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.Omnipo import info.nightscout.androidaps.plugins.pump.omnipod.common.databinding.OmnipodCommonWizardProgressIndicationBinding import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.activity.OmnipodWizardActivityBase import info.nightscout.androidaps.plugins.pump.omnipod.common.ui.wizard.common.viewmodel.ViewModelBase -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject import kotlin.math.roundToInt diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt index 0050a23481..571eda4c40 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/OmnipodDashPumpPlugin.kt @@ -48,7 +48,7 @@ import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.TimeChangeType -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt index f8d0588455..98fc46781c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/OmnipodDashOverviewFragment.kt @@ -41,7 +41,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.buildHelper.BuildHelper import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.UIRunnable diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt index 081be0d0f4..7b022089ab 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInitializePodViewModel.kt @@ -15,7 +15,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.DashHistory import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.InitialResult import info.nightscout.androidaps.plugins.pump.omnipod.dash.history.data.ResolvedResult import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.I8n -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.core.Single diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt index bcb1e04e2d..30704e755b 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/ui/wizard/activation/viewmodel/action/DashInsertCannulaViewModel.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.Constants import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.I8n import info.nightscout.androidaps.plugins.pump.omnipod.dash.util.mapProfileToBasalProgram import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.core.Single diff --git a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/I8n.kt b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/I8n.kt index 744a426772..534a6ee45c 100644 --- a/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/I8n.kt +++ b/omnipod-dash/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/dash/util/I8n.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptio import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.NotConnectedException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanException import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.ScanFailFoundTooManyException -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper class I8n { companion object { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java index 8070aa6d2a..4483eab747 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPlugin.java @@ -103,7 +103,7 @@ import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.Round; import info.nightscout.androidaps.utils.T; import info.nightscout.androidaps.utils.TimeChangeType; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.rxjava3.disposables.CompositeDisposable; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java index 9ef3767205..46a04949bf 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/data/RLHistoryItemOmnipod.java @@ -8,7 +8,7 @@ import dagger.android.HasAndroidInjector; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; import info.nightscout.androidaps.plugins.pump.omnipod.common.definition.OmnipodCommandType; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; public class RLHistoryItemOmnipod extends RLHistoryItem { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java index 1a14a05abc..ea3402f356 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/manager/AapsOmnipodErosManager.java @@ -79,7 +79,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.rileylink.manager.Om import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.OmnipodAlertUtil; import info.nightscout.androidaps.utils.T; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.shared.sharedPreferences.SP; import io.reactivex.subjects.SingleSubject; diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java index 3bb98d2fb4..d795fc1455 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/ErosPodHistoryActivity.java @@ -35,7 +35,7 @@ import info.nightscout.androidaps.plugins.pump.common.utils.ProfileUtil; import info.nightscout.androidaps.plugins.pump.omnipod.eros.R; import info.nightscout.androidaps.plugins.pump.omnipod.eros.definition.PodHistoryEntryType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.util.AapsOmnipodUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; public class ErosPodHistoryActivity extends NoSplashAppCompatActivity { diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt index cccb5a0d33..d67636cda0 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/ui/OmnipodErosOverviewFragment.kt @@ -48,7 +48,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.protection.ProtectionCheck -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.sharedPreferences.SP import info.nightscout.androidaps.utils.ui.UIRunnable diff --git a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java index 28aef360fa..72df66c023 100644 --- a/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java +++ b/omnipod-eros/src/main/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/util/AapsOmnipodUtil.java @@ -21,7 +21,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.Al import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertSlot; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.definition.AlertType; import info.nightscout.androidaps.plugins.pump.omnipod.eros.driver.manager.ErosPodStateManager; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; /** * Created by andy on 4/8/19. diff --git a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt index af93b117ea..1940baeb14 100644 --- a/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt +++ b/omnipod-eros/src/test/java/info/nightscout/androidaps/plugins/pump/omnipod/eros/OmnipodErosPumpPluginTest.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.TempBasalPair import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil import info.nightscout.androidaps.plugins.pump.omnipod.eros.history.ErosHistory import info.nightscout.androidaps.plugins.pump.omnipod.eros.manager.AapsOmnipodErosManager -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.TestAapsSchedulers import org.joda.time.DateTimeZone import org.joda.time.tz.UTCProvider diff --git a/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt b/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt index 0d4ab2eeaf..943fbfec88 100644 --- a/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt +++ b/openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/OpenHumansUploader.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.plugin.general.openhumans.delegates.OHStateDel import info.nightscout.androidaps.plugin.general.openhumans.ui.OHFragment import info.nightscout.androidaps.plugin.general.openhumans.ui.OHLoginActivity import info.nightscout.androidaps.plugins.bus.RxBus -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt index 7488846730..85dc56b946 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/PumpPluginAbstract.kt @@ -25,7 +25,7 @@ import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DecimalFormatter.to0Decimal import info.nightscout.androidaps.utils.DecimalFormatter.to2Decimal import info.nightscout.androidaps.utils.FabricPrivacy -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag diff --git a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt index fd62104314..4a98471dc4 100644 --- a/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt +++ b/pump-common/src/main/java/info/nightscout/androidaps/plugins/pump/common/defs/PumpHistoryEntryGroup.kt @@ -1,7 +1,7 @@ package info.nightscout.androidaps.plugins.pump.common.defs import info.nightscout.androidaps.plugins.pump.common.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import java.util.* /** diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.kt index a07bae6138..ad9c82bbb4 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/dialog/RileyLinkBLEConfigActivity.kt @@ -32,7 +32,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileyLinkBleConfigActivityBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice import info.nightscout.androidaps.utils.alertDialogs.OKDialog -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt index d49d5c9529..d0e45dc576 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/events/EventRileyLinkDeviceStatusChange.kt @@ -5,7 +5,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper open class EventRileyLinkDeviceStatusChange : EventStatus { diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java index 4d6e7bb477..abd0bd5d83 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/RFSpy.java @@ -38,7 +38,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.Riley import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil; import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil; import info.nightscout.androidaps.plugins.pump.common.utils.ThreadUtil; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; import info.nightscout.shared.sharedPreferences.SP; /** diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java index 8ade0413e1..a6e0f11e30 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/ble/defs/RileyLinkEncodingType.java @@ -4,7 +4,7 @@ import java.util.HashMap; import java.util.Map; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; public enum RileyLinkEncodingType { diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java index 155021f457..fbc77b5fc4 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/data/RLHistoryItem.java @@ -6,7 +6,7 @@ import info.nightscout.androidaps.plugins.pump.common.defs.PumpDeviceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState; import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice; -import info.nightscout.androidaps.utils.resources.ResourceHelper; +import info.nightscout.androidaps.interfaces.ResourceHelper; /** diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.kt index 4d0688e985..115849b46d 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusGeneralFragment.kt @@ -13,7 +13,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLin import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service.RileyLinkServiceData import info.nightscout.androidaps.plugins.pump.common.utils.StringUtil import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.sharedPreferences.SP import org.joda.time.LocalDateTime diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.kt index eeaf5bc11a..63605c1a7e 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/dialog/RileyLinkStatusHistoryFragment.kt @@ -14,7 +14,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistor import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileylinkStatusHistoryItemBinding import info.nightscout.androidaps.utils.DateUtil -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import javax.inject.Inject class RileyLinkStatusHistoryFragment : DaggerFragment() { diff --git a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.kt b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.kt index fbb624f5ef..4b61ecec25 100644 --- a/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.kt +++ b/rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkService.kt @@ -18,7 +18,7 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.Rile import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP diff --git a/shared/build.gradle b/shared/build.gradle index 12354733b6..c4f3cfb88a 100644 --- a/shared/build.gradle +++ b/shared/build.gradle @@ -3,6 +3,7 @@ apply plugin: 'kotlin-android' apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-allopen' apply plugin: 'com.hiya.jacoco-android' +apply plugin: 'kotlinx-serialization' apply from: "${project.rootDir}/gradle/android_dependencies.gradle" apply from: "${project.rootDir}/gradle/android_module_dependencies.gradle" @@ -17,6 +18,7 @@ android { dependencies { api "androidx.preference:preference-ktx:$preferencektx_version" + api "net.danlew:android.joda:$joga_version" // for old fashioned support-app version (wear) api "com.google.dagger:dagger:$dagger_version" @@ -29,6 +31,9 @@ dependencies { exclude group: "com.google.android", module: "android" } + api "org.jetbrains.kotlinx:kotlinx-serialization-json:1.3.2" + api "org.apache.commons:commons-lang3:$commonslang3_version" + //RxBus api "io.reactivex.rxjava3:rxjava:$rxjava_version" api "io.reactivex.rxjava3:rxkotlin:$rxkotlin_version" diff --git a/database/src/debug/java/info/nightscout/androidaps/annotations/OpenForTesting.kt b/shared/src/debug/java/info/nightscout/androidaps/annotations/OpenForTesting.kt similarity index 100% rename from database/src/debug/java/info/nightscout/androidaps/annotations/OpenForTesting.kt rename to shared/src/debug/java/info/nightscout/androidaps/annotations/OpenForTesting.kt diff --git a/core/src/main/java/info/nightscout/androidaps/events/Event.kt b/shared/src/main/java/info/nightscout/androidaps/events/Event.kt similarity index 99% rename from core/src/main/java/info/nightscout/androidaps/events/Event.kt rename to shared/src/main/java/info/nightscout/androidaps/events/Event.kt index a44f65e836..5c06afcc15 100644 --- a/core/src/main/java/info/nightscout/androidaps/events/Event.kt +++ b/shared/src/main/java/info/nightscout/androidaps/events/Event.kt @@ -15,4 +15,4 @@ abstract class Event { ReflectionToStringBuilder.setDefaultStyle(ToStringStyle.SHORT_PREFIX_STYLE) } } -} +} \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventMobileToWear.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventMobileToWear.kt new file mode 100644 index 0000000000..c13bd0b2fe --- /dev/null +++ b/shared/src/main/java/info/nightscout/androidaps/events/EventMobileToWear.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.events + +import info.nightscout.shared.weardata.EventData + +class EventMobileToWear(val payload: EventData) : Event() \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobile.kt b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobile.kt new file mode 100644 index 0000000000..3967cebaa9 --- /dev/null +++ b/shared/src/main/java/info/nightscout/androidaps/events/EventWearToMobile.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.events + +import info.nightscout.shared.weardata.EventData + +class EventWearToMobile(val payload: EventData) : Event() \ No newline at end of file diff --git a/core/src/main/java/info/nightscout/androidaps/extensions/UIUtils.kt b/shared/src/main/java/info/nightscout/androidaps/extensions/UIUtils.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/extensions/UIUtils.kt rename to shared/src/main/java/info/nightscout/androidaps/extensions/UIUtils.kt diff --git a/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt b/shared/src/main/java/info/nightscout/androidaps/interfaces/ResourceHelper.kt similarity index 96% rename from core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt rename to shared/src/main/java/info/nightscout/androidaps/interfaces/ResourceHelper.kt index 2c259946fa..4c93cc58ff 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/resources/ResourceHelper.kt +++ b/shared/src/main/java/info/nightscout/androidaps/interfaces/ResourceHelper.kt @@ -1,4 +1,4 @@ -package info.nightscout.androidaps.utils.resources +package info.nightscout.androidaps.interfaces import android.content.Context import android.content.res.AssetFileDescriptor diff --git a/core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt b/shared/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt rename to shared/src/main/java/info/nightscout/androidaps/plugins/bus/RxBus.kt diff --git a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt similarity index 84% rename from core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt rename to shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt index a4b072057b..5578a94a92 100644 --- a/core/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt +++ b/shared/src/main/java/info/nightscout/androidaps/utils/DateUtil.kt @@ -1,15 +1,18 @@ package info.nightscout.androidaps.utils import android.content.Context +import android.os.Build +import androidx.annotation.RequiresApi import androidx.collection.LongSparseArray import info.nightscout.androidaps.annotations.OpenForTesting -import info.nightscout.androidaps.core.R -import info.nightscout.androidaps.utils.resources.ResourceHelper +import info.nightscout.androidaps.interfaces.ResourceHelper +import info.nightscout.shared.R import info.nightscout.shared.SafeParse import org.apache.commons.lang3.time.DateUtils.isSameDay import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.joda.time.format.ISODateTimeFormat +import java.security.SecureRandom import java.text.DateFormat import java.text.DecimalFormat import java.text.DecimalFormatSymbols @@ -23,7 +26,6 @@ import java.util.regex.Pattern import java.util.stream.Collectors import javax.inject.Inject import javax.inject.Singleton -import kotlin.math.abs import kotlin.math.ceil import kotlin.math.floor @@ -38,7 +40,7 @@ class DateUtil @Inject constructor(private val context: Context) { /** * The date format in iso. */ - @Suppress("PrivatePropertyName") + @Suppress("PrivatePropertyName", "SpellCheckingInspection") private val FORMAT_DATE_ISO_OUT = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" /** @@ -66,12 +68,14 @@ class DateUtil @Inject constructor(private val context: Context) { return f.format(date) } + @Suppress("SpellCheckingInspection") fun toISOAsUTC(timestamp: Long): String { val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'", Locale.US) format.timeZone = TimeZone.getTimeZone("UTC") return format.format(timestamp) } + @Suppress("SpellCheckingInspection") fun toISONoZone(timestamp: Long): String { val format = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US) format.timeZone = TimeZone.getDefault() @@ -90,13 +94,13 @@ class DateUtil @Inject constructor(private val context: Context) { fun toSeconds(hh_colon_mm: String): Int { val p = Pattern.compile("(\\d+):(\\d+)( a.m.| p.m.| AM| PM|AM|PM|)") val m = p.matcher(hh_colon_mm) - var retval = 0 + var retVal = 0 if (m.find()) { - retval = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60 - if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") retval -= 12 * 60 * 60 - if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") retval += 12 * 60 * 60 + retVal = SafeParse.stringToInt(m.group(1)) * 60 * 60 + SafeParse.stringToInt(m.group(2)) * 60 + if ((m.group(3) == " a.m." || m.group(3) == " AM" || m.group(3) == "AM") && m.group(1) == "12") retVal -= 12 * 60 * 60 + if ((m.group(3) == " p.m." || m.group(3) == " PM" || m.group(3) == "PM") && m.group(1) != "12") retVal += 12 * 60 * 60 } - return retval + return retVal } fun dateString(mills: Long): String { @@ -110,10 +114,10 @@ class DateUtil @Inject constructor(private val context: Context) { val beginOfToday = beginOfDay(now()) return if (mills < now()) // Past when { - mills > beginOfToday -> rh.gs(R.string.today) + mills > beginOfToday -> rh.gs(R.string.today) mills > beginOfToday - T.days(1).msecs() -> rh.gs(R.string.yesterday) mills > beginOfToday - T.days(7).msecs() -> dayAgo(mills, rh, true) - else -> day + else -> day } else // Future when { @@ -132,6 +136,7 @@ class DateUtil @Inject constructor(private val context: Context) { return DateTime(mills).toString(DateTimeFormat.forPattern(format)) } + fun timeString(): String = timeString(now()) fun timeString(mills: Long): String { var format = "hh:mma" if (android.text.format.DateFormat.is24HourFormat(context)) { @@ -140,6 +145,35 @@ class DateUtil @Inject constructor(private val context: Context) { return DateTime(mills).toString(DateTimeFormat.forPattern(format)) } + fun minuteString(): String = minuteString(now()) + fun minuteString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("mm")) + + fun hourString(): String = hourString(now()) + fun hourString(mills: Long): String { + var format = "hha" + if (android.text.format.DateFormat.is24HourFormat(context)) { + format = "HH" + } + return DateTime(mills).toString(DateTimeFormat.forPattern(format)) + } + + fun dayNameString(): String = minuteString(now()) + fun dayNameString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("E")) + + fun dayString(): String = minuteString(now()) + fun dayString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("dd")) + + fun monthString(): String = monthString(now()) + fun monthString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("MMM")) + + fun weekString(): String = weekString(now()) + fun weekString(mills: Long): String = + DateTime(mills).toString(DateTimeFormat.forPattern("ww")) + fun timeStringWithSeconds(mills: Long): String { var format = "hh:mm:ssa" if (android.text.format.DateFormat.is24HourFormat(context)) { @@ -166,20 +200,20 @@ class DateUtil @Inject constructor(private val context: Context) { fun minAgo(rh: ResourceHelper, time: Long?): String { if (time == null) return "" - val mins = ((now() - time) / 1000 / 60).toInt() - return rh.gs(R.string.minago, mins) + val minutes = ((now() - time) / 1000 / 60).toInt() + return rh.gs(R.string.minago, minutes) } fun minAgoShort(time: Long?): String { if (time == null) return "" - val mins = ((time - now()) / 1000 / 60).toInt() - return (if (mins > 0) "+" else "") + mins + val minutes = ((time - now()) / 1000 / 60).toInt() + return (if (minutes > 0) "+" else "") + minutes } fun minAgoLong(rh: ResourceHelper, time: Long?): String { if (time == null) return "" - val mins = ((now() - time) / 1000 / 60).toInt() - return rh.gs(R.string.minago_long, mins) + val minutes = ((now() - time) / 1000 / 60).toInt() + return rh.gs(R.string.minago_long, minutes) } fun hourAgo(time: Long, rh: ResourceHelper): String { @@ -190,12 +224,12 @@ class DateUtil @Inject constructor(private val context: Context) { fun dayAgo(time: Long, rh: ResourceHelper, round: Boolean = false): String { var days = (now() - time) / 1000.0 / 60 / 60 / 24 if (round) { - if (now() > time) { + return if (now() > time) { days = ceil(days) - return rh.gs(R.string.days_ago_round, days) + rh.gs(R.string.days_ago_round, days) } else { days = floor(days) - return rh.gs(R.string.in_days_round, days) + rh.gs(R.string.in_days_round, days) } } return if (now() > time) @@ -247,11 +281,6 @@ class DateUtil @Inject constructor(private val context: Context) { return n } - fun isCloseToNow(date: Long): Boolean { - val diff = abs(date - now()) - return diff < T.mins(2L).msecs() - } - fun isOlderThan(date: Long, minutes: Long): Boolean { val diff = now() - date return diff > T.mins(minutes).msecs() @@ -269,7 +298,7 @@ class DateUtil @Inject constructor(private val context: Context) { fun isSameDayGroup(timestamp1: Long, timestamp2: Long): Boolean { val now = now() - if (timestamp1 < now && timestamp2 > now || timestamp1 > now && timestamp2 < now) + if (now in (timestamp1 + 1) until timestamp2 || now in (timestamp2 + 1) until timestamp1) return false return isSameDay(Date(timestamp1), Date(timestamp2)) } @@ -368,13 +397,14 @@ class DateUtil @Inject constructor(private val context: Context) { return thisDf.format(x) } - fun format_HH_MM(timeAsSeconds: Int): String { + fun formatHHMM(timeAsSeconds: Int): String { val hour = timeAsSeconds / 60 / 60 val minutes = (timeAsSeconds - hour * 60 * 60) / 60 val df = DecimalFormat("00") return df.format(hour.toLong()) + ":" + df.format(minutes.toLong()) } + @RequiresApi(Build.VERSION_CODES.O) fun timeZoneByOffset(offsetInMilliseconds: Long): TimeZone = TimeZone.getTimeZone( if (offsetInMilliseconds == 0L) ZoneId.of("UTC") @@ -386,7 +416,7 @@ class DateUtil @Inject constructor(private val context: Context) { .firstOrNull() ?: ZoneId.of("UTC") ) - fun timeStampToUtcDateMilis(timestamp: Long): Long { + fun timeStampToUtcDateMillis(timestamp: Long): Long { val current = Calendar.getInstance().apply { timeInMillis = timestamp } return Calendar.getInstance().apply { set(Calendar.YEAR, current.get(Calendar.YEAR)) @@ -395,8 +425,8 @@ class DateUtil @Inject constructor(private val context: Context) { }.timeInMillis } - fun mergeUtcDateToTimestamp(timestamp: Long, dateUtcMilis: Long): Long { - val selected = Calendar.getInstance().apply { timeInMillis = dateUtcMilis } + fun mergeUtcDateToTimestamp(timestamp: Long, dateUtcMillis: Long): Long { + val selected = Calendar.getInstance().apply { timeInMillis = dateUtcMillis } return Calendar.getInstance().apply { timeInMillis = timestamp set(Calendar.YEAR, selected.get(Calendar.YEAR)) @@ -417,7 +447,8 @@ class DateUtil @Inject constructor(private val context: Context) { companion object { private val timeStrings = LongSparseArray() - private var seconds: Int = (Math.random() * 59.0).toInt() + private var seconds: Int = (SecureRandom().nextDouble() * 59.0).toInt() + // singletons to avoid repeated allocation private var dfs: DecimalFormatSymbols? = null private var df: DecimalFormat? = null diff --git a/core/src/main/java/info/nightscout/androidaps/utils/T.kt b/shared/src/main/java/info/nightscout/androidaps/utils/T.kt similarity index 100% rename from core/src/main/java/info/nightscout/androidaps/utils/T.kt rename to shared/src/main/java/info/nightscout/androidaps/utils/T.kt diff --git a/shared/src/main/java/info/nightscout/shared/weardata/EventData.kt b/shared/src/main/java/info/nightscout/shared/weardata/EventData.kt new file mode 100644 index 0000000000..45db4cd8fc --- /dev/null +++ b/shared/src/main/java/info/nightscout/shared/weardata/EventData.kt @@ -0,0 +1,237 @@ +package info.nightscout.shared.weardata + +import info.nightscout.androidaps.events.Event +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json +import java.util.* + +@Serializable +sealed class EventData : Event() { + + var sourceNodeId = "" + + fun serialize() = Json.encodeToString(serializer(), this) + + companion object { + + fun deserialize(json: String) = Json.decodeFromString(serializer(), json) + } + + // Mobile <- Wear + @Serializable + data class ActionPong(val timeStamp: Long) : EventData() + + @Serializable + data class Error(val timeStamp: Long) : EventData() // ignored + + @Serializable + data class CancelBolus(val timeStamp: Long) : EventData() + + @Serializable + data class ActionResendData(val from: String) : EventData() + + @Serializable + data class ActionPumpStatus(val timeStamp: Long) : EventData() + + @Serializable + data class ActionLoopStatus(val timeStamp: Long) : EventData() + + @Serializable + data class ActionTddStatus(val timeStamp: Long) : EventData() + + @Serializable + data class ActionECarbsPreCheck(val carbs: Int, val carbsTimeShift: Int, val duration: Int) : EventData() + + @Serializable + data class ActionBolusPreCheck(val insulin: Double, val carbs: Int) : EventData() + + @Serializable + data class ActionFillPreCheck(val insulin: Double) : EventData() + + @Serializable + data class ActionFillPresetPreCheck(val button: Int) : EventData() + + @Serializable + data class ActionProfileSwitchSendInitialData(val timeStamp: Long) : EventData() + + @Serializable + data class ActionProfileSwitchPreCheck(val timeShift: Int, val percentage: Int) : EventData() + + @Serializable + data class ActionWizardPreCheck(val carbs: Int, val percentage: Int) : EventData() + + @Serializable + data class ActionQuickWizardPreCheck(val guid: String) : EventData() + + @Serializable + data class ActionTempTargetPreCheck( + val command: TempTargetCommand, + val isMgdl: Boolean = true, val duration: Int = 0, val low: Double = 0.0, val high: Double = 0.0 // manual + ) : EventData() { + + @Serializable + enum class TempTargetCommand { + + PRESET_ACTIVITY, PRESET_HYPO, PRESET_EATING, CANCEL, MANUAL + } + + } + + // Mobile <- Wear return + + @Serializable + data class ActionWizardConfirmed(val timeStamp: Long) : EventData() + + @Serializable + data class ActionTempTargetConfirmed(val isMgdl: Boolean = true, val duration: Int = 0, val low: Double = 0.0, val high: Double = 0.0) : EventData() + + @Serializable + data class ActionBolusConfirmed(val insulin: Double, val carbs: Int) : EventData() + + @Serializable + data class ActionECarbsConfirmed(val carbs: Int, val carbsTime: Long, val duration: Int) : EventData() + + @Serializable + data class ActionFillConfirmed(val insulin: Double) : EventData() + + @Serializable + data class ActionProfileSwitchConfirmed(val timeShift: Int, val percentage: Int) : EventData() + + @Serializable + data class OpenLoopRequestConfirmed(val timeStamp: Long) : EventData() + + // Mobile -> Wear + @Serializable + data class CancelNotification(val timeStamp: Long) : EventData() + + @Serializable + data class ActionPing(val timeStamp: Long) : EventData() + + @Serializable + data class OpenSettings(val timeStamp: Long) : EventData() + + @Serializable + data class BolusProgress(val percent: Int, val status: String) : EventData() + + @Serializable + data class SingleBg @JvmOverloads constructor( + var timeStamp: Long, + val sgvString: String = "---", + val glucoseUnits: String = "-", + val slopeArrow: String = "--", + val delta: String = "--", + val avgDelta: String = "--", + val sgvLevel: Long = 0, + val sgv: Double, + val high: Double, // highLine + val low: Double, // lowLine + val color: Int = 0 + ) : EventData(), Comparable { + + override fun equals(other: Any?): Boolean = + when { + other !is SingleBg -> false + color != other.color -> false + else -> timeStamp == other.timeStamp + } + + override fun hashCode(): Int { + return Objects.hash(timeStamp, color) + } + + override fun compareTo(other: SingleBg): Int { + // reverse order endTime get latest first + if (this.timeStamp < other.timeStamp) return 1 + return if (this.timeStamp > other.timeStamp) -1 else 0 + } + } + + @Serializable + data class GraphData( + val entries: ArrayList + ) : EventData() + + @Serializable + data class TreatmentData( + val temps: ArrayList, + val basals: ArrayList, + val boluses: ArrayList, + val predictions: ArrayList + ) : EventData() { + + @Serializable + data class TempBasal( + val startTime: Long, + val startBasal: Double, + val endTime: Long, + val endBasal: Double, + val amount: Double + ) + + @Serializable + data class Basal( + val startTime: Long, + val endTime: Long, + val amount: Double + ) + + @Serializable + data class Treatment( + val date: Long, + val bolus: Double, + val carbs: Double, + val isSMB: Boolean, + val isValid: Boolean, + ) + } + + @Serializable + data class Status( + val externalStatus: String, + val iobSum: String, + val iobDetail: String, + val detailedIob: Boolean, + val cob: String, + val currentBasal: String, + val battery: String, + val rigBattery: String, + val openApsStatus: Long, + val bgi: String, + val showBgi: Boolean, + val batteryLevel: Int + ) : EventData() + + @Serializable + data class Preferences( + val timeStamp: Long, + val wearControl: Boolean, + val unitsMgdl: Boolean, + val bolusPercentage: Int, + val maxCarbs: Int, + val maxBolus: Double + ) : EventData() + + @Serializable + data class QuickWizard( + val entries: ArrayList + ) : EventData() { + + @Serializable + data class QuickWizardEntry( + val guid: String, + val buttonText: String, + val carbs: Int, + val validFrom: Int, + val validTo: Int + ) : EventData() + } + + @Serializable + data class ActionProfileSwitchOpenActivity(val timeShift: Int, val percentage: Int) : EventData() + + @Serializable + data class OpenLoopRequest(val title: String, val message: String, val returnCommand: EventData?) : EventData() + + @Serializable // returnCommand is sent back to Mobile after confirmation + data class ConfirmAction(val title: String, val message: String, val returnCommand: EventData?) : EventData() +} \ No newline at end of file diff --git a/shared/src/main/java/info/nightscout/shared/weardata/WearUris.kt b/shared/src/main/java/info/nightscout/shared/weardata/WearUris.kt deleted file mode 100644 index 2e16f8e459..0000000000 --- a/shared/src/main/java/info/nightscout/shared/weardata/WearUris.kt +++ /dev/null @@ -1,21 +0,0 @@ -package info.nightscout.shared.weardata - -object WearUris { - - const val WEARABLE_DATA_PATH = "/nightscout_watch_data" - const val WEARABLE_RESEND_PATH = "/nightscout_watch_data_resend" - const val WEARABLE_CANCELBOLUS_PATH = "/nightscout_watch_cancel_bolus" - const val WEARABLE_CONFIRM_ACTIONSTRING_PATH = "/nightscout_watch_confirmactionstring" - const val WEARABLE_INITIATE_ACTIONSTRING_PATH = "/nightscout_watch_initiateactionstring" - - const val OPEN_SETTINGS_PATH = "/openwearsettings" - const val NEW_STATUS_PATH = "/sendstatustowear" - const val NEW_PREFERENCES_PATH = "/sendpreferencestowear" - const val QUICK_WIZARD_PATH = "/send_quick_wizard" - const val BASAL_DATA_PATH = "/nightscout_watch_basal" - const val BOLUS_PROGRESS_PATH = "/nightscout_watch_bolusprogress" - const val ACTION_CONFIRMATION_REQUEST_PATH = "/nightscout_watch_actionconfirmationrequest" - const val ACTION_CHANGECONFIRMATION_REQUEST_PATH = "/nightscout_watch_changeconfirmationrequest" - const val ACTION_CANCELNOTIFICATION_REQUEST_PATH = "/nightscout_watch_cancelnotificationrequest" - -} \ No newline at end of file diff --git a/shared/src/main/res/values/strings.xml b/shared/src/main/res/values/strings.xml new file mode 100644 index 0000000000..0d9b555567 --- /dev/null +++ b/shared/src/main/res/values/strings.xml @@ -0,0 +1,30 @@ + + + + %1$d m ago + %1$d minutes ago + %1$.1f h ago + %1$.1f days ago + %1$.0f days ago + in %1$.0f days + in %1$.0f days + h + days + hours + second + minute + hour + day + week + seconds + minutes + hours + days + weeks + m + d + Later today + Tomorrow + Today + Yesterday + \ No newline at end of file diff --git a/shared/src/main/res/values/wear_paths.xml b/shared/src/main/res/values/wear_paths.xml new file mode 100644 index 0000000000..36d7325849 --- /dev/null +++ b/shared/src/main/res/values/wear_paths.xml @@ -0,0 +1,4 @@ + + + /rx_bridge + \ No newline at end of file diff --git a/database/src/release/java/info/nightscout/androidaps/annotations/OpenForTesting.kt b/shared/src/release/java/info/nightscout/androidaps/annotations/OpenForTesting.kt similarity index 100% rename from database/src/release/java/info/nightscout/androidaps/annotations/OpenForTesting.kt rename to shared/src/release/java/info/nightscout/androidaps/annotations/OpenForTesting.kt diff --git a/wear/build.gradle b/wear/build.gradle index c18fc1be46..2bee9762de 100644 --- a/wear/build.gradle +++ b/wear/build.gradle @@ -23,8 +23,7 @@ apply from: "${project.rootDir}/gradle/jacoco_global.gradle" ext { wearableVersion = "2.9.0" - // playServicesWearable 17.1.0 breaks test - playServicesWearable = "17.0.0" + playServicesWearable = "17.1.0" } def generateGitBuild = { -> @@ -52,7 +51,6 @@ android { compileSdkVersion 31 defaultConfig { - applicationId "info.nightscout.androidaps" minSdkVersion 23 targetSdkVersion 29 versionCode 2 @@ -98,12 +96,12 @@ dependencies { implementation fileTree(include: ['*.jar'], dir: 'libs') - implementation "androidx.core:core-ktx:$core_version" implementation "androidx.appcompat:appcompat:$appcompat_version" - implementation "androidx.preference:preference-ktx:$preferencektx_version" + implementation "androidx.core:core-ktx:$core_version" implementation 'androidx.legacy:legacy-support-v13:1.0.0' - implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation "androidx.preference:preference-ktx:$preferencektx_version" implementation 'androidx.wear:wear:1.2.0' + implementation "androidx.wear.tiles:tiles:1.0.1" compileOnly "com.google.android.wearable:wearable:${wearableVersion}" implementation "com.google.android.support:wearable:${wearableVersion}" @@ -112,10 +110,10 @@ dependencies { implementation(files('libs/wearpreferenceactivity-0.5.0.aar')) implementation('com.github.lecho:hellocharts-library:1.5.8@aar') - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1' - implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.6.1' - implementation "androidx.core:core-ktx:$core_version" - implementation "androidx.wear.tiles:tiles:1.0.1" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-guava:$coroutines_version" + implementation "org.jetbrains.kotlinx:kotlinx-coroutines-play-services:$coroutines_version" implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" // for old fashioned support-app version diff --git a/wear/src/main/AndroidManifest.xml b/wear/src/main/AndroidManifest.xml index 0bd323b107..59c5068de6 100644 --- a/wear/src/main/AndroidManifest.xml +++ b/wear/src/main/AndroidManifest.xml @@ -17,15 +17,21 @@ android:icon="@drawable/ic_icon" android:label="@string/app_name" android:theme="@android:style/Theme.DeviceDefault"> + + + + android:label="@string/label_watchface_big_chart" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -43,10 +49,11 @@ + android:label="@string/label_watchface_no_chart" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -64,10 +71,11 @@ + android:label="@string/label_watchface" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -88,10 +96,11 @@ + android:label="@string/label_watchface_v2" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -112,10 +121,11 @@ + android:label="@string/label_watchface_cockpit" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -136,10 +146,11 @@ + android:label="@string/label_watchface_steampunk" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -160,10 +171,11 @@ + android:label="@string/label_watchface_large" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -185,8 +197,9 @@ + android:label="@string/label_watchface_circle" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -204,10 +217,11 @@ + android:label="@string/label_watchface_digital_style" + android:permission="android.permission.BIND_WALLPAPER" + android:exported="false"> @@ -227,68 +241,29 @@ - + - - + + + + + + + + + + + + - - - - - - - - - - - - - @@ -447,7 +422,7 @@ @@ -466,7 +441,7 @@ @@ -483,7 +458,7 @@ @@ -500,7 +475,7 @@ @@ -573,11 +548,10 @@
+ android:name=".interaction.actions.ProfileSwitchActivity" + android:label="@string/status_profile_switch" /> - + diff --git a/wear/src/main/assets/logback.xml b/wear/src/main/assets/logback.xml new file mode 100644 index 0000000000..b901b4b738 --- /dev/null +++ b/wear/src/main/assets/logback.xml @@ -0,0 +1,39 @@ + + + + + ${EXT_FILES_DIR}/AndroidAPS.log + + + ${EXT_FILES_DIR}/AndroidAPS._%d{yyyy-MM-dd}_%d{HH-mm-ss, aux}_.%i.zip + + + + 5MB + + + 120 + + + %d{HH:mm:ss.SSS} [%thread] %.-1level/%logger: %msg%n + + + + + + %logger{0} + + + [%thread]: %msg%n + + + + + + + + + diff --git a/wear/src/main/java/info/nightscout/androidaps/Aaps.kt b/wear/src/main/java/info/nightscout/androidaps/Aaps.kt index c3ddb09936..ef5ca19d11 100644 --- a/wear/src/main/java/info/nightscout/androidaps/Aaps.kt +++ b/wear/src/main/java/info/nightscout/androidaps/Aaps.kt @@ -7,13 +7,27 @@ import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.preference.PreferenceManager import dagger.android.AndroidInjector import dagger.android.DaggerApplication +import info.nightscout.androidaps.comm.DataHandlerWear +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.androidaps.di.DaggerWearComponent +import info.nightscout.androidaps.events.EventWearPreferenceChange +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import javax.inject.Inject class Aaps : DaggerApplication(), OnSharedPreferenceChangeListener { + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBus + @Inject lateinit var dataHandlerWear: DataHandlerWear // instantiate only + override fun onCreate() { super.onCreate() + aapsLogger.debug(LTag.WEAR, "onCreate") PreferenceManager.getDefaultSharedPreferences(this).registerOnSharedPreferenceChangeListener(this) + startService(Intent(this, DataLayerListenerServiceWear::class.java)) + } override fun applicationInjector(): AndroidInjector = @@ -24,6 +38,7 @@ class Aaps : DaggerApplication(), OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { // we trigger update on Complications - LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(Intent.ACTION_SEND)) + LocalBroadcastManager.getInstance(this).sendBroadcast(Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA)) + rxBus.send(EventWearPreferenceChange(key)) } } \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt new file mode 100644 index 0000000000..af9967f71a --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataHandlerWear.kt @@ -0,0 +1,285 @@ +package info.nightscout.androidaps.comm + +import android.annotation.TargetApi +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.content.Context +import android.content.Intent +import android.os.Build +import android.os.Bundle +import android.os.SystemClock +import androidx.core.app.NotificationCompat +import androidx.core.app.NotificationManagerCompat +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import androidx.wear.tiles.TileService +import com.google.android.gms.wearable.WearableListenerService +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.WatchfaceConfigurationActivity +import info.nightscout.androidaps.interaction.actions.AcceptActivity +import info.nightscout.androidaps.interaction.actions.ProfileSwitchActivity +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.tile.ActionsTileService +import info.nightscout.androidaps.tile.QuickWizardTileService +import info.nightscout.androidaps.tile.TempTargetTileService +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import javax.inject.Inject +import javax.inject.Singleton + +@Singleton +class DataHandlerWear @Inject constructor( + private val context: Context, + private val rxBus: RxBus, + private val aapsSchedulers: AapsSchedulers, + private val sp: SP, + private val aapsLogger: AAPSLogger, + private val persistence: Persistence +) { + + private val disposable = CompositeDisposable() + + init { + setupBus() + } + + private fun setupBus() { + disposable += rxBus + .toObservable(EventData.ActionPing::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "Ping received from ${it.sourceNodeId}") + rxBus.send(EventWearToMobile(EventData.ActionPong(System.currentTimeMillis()))) + } + disposable += rxBus + .toObservable(EventData.ConfirmAction::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "ConfirmAction received from ${it.sourceNodeId}") + context.startActivity(Intent(context, AcceptActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtras( + Bundle().also { bundle -> + bundle.putString(DataLayerListenerServiceWear.KEY_TITLE, it.title) + bundle.putString(DataLayerListenerServiceWear.KEY_MESSAGE, it.message) + bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, it.returnCommand?.serialize()) + } + ) + }) + } + disposable += rxBus + .toObservable(EventData.CancelNotification::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "ActionCancelNotification received from ${it.sourceNodeId}") + (context.getSystemService(WearableListenerService.NOTIFICATION_SERVICE) as NotificationManager).cancel(DataLayerListenerServiceWear.CHANGE_NOTIF_ID) + } + disposable += rxBus + .toObservable(EventData.OpenLoopRequest::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "OpenLoopRequest received from ${it.sourceNodeId}") + handleOpenLoopRequest(it) + } + disposable += rxBus + .toObservable(EventData.OpenSettings::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "ActionOpenSettings received from ${it.sourceNodeId}") + context.startActivity(Intent(context, WatchfaceConfigurationActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + disposable += rxBus + .toObservable(EventData.ActionProfileSwitchOpenActivity::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { event -> + aapsLogger.debug(LTag.WEAR, "ActionProfileSwitchOpenActivity received from ${event.sourceNodeId}") + context.startActivity(Intent(context, ProfileSwitchActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtras(Bundle().also { bundle -> + bundle.putInt("percentage", event.percentage) + bundle.putInt("timeshift", event.timeShift) + }) + }) + } + disposable += rxBus + .toObservable(EventData.BolusProgress::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "Bolus progress received from ${it.sourceNodeId}") + handleBolusProgress(it) + rxBus.send(EventWearToMobile(EventData.ActionPong(System.currentTimeMillis()))) + } + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "Status received from ${it.sourceNodeId}") + persistence.store(it) + LocalBroadcastManager.getInstance(context).sendBroadcast(Intent(DataLayerListenerServiceWear.INTENT_NEW_DATA)) + } + disposable += rxBus + .toObservable(EventData.SingleBg::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "SingleBg received from ${it.sourceNodeId}") + persistence.store(it) + } + disposable += rxBus + .toObservable(EventData.GraphData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "GraphData received from ${it.sourceNodeId}") + persistence.store(it) + } + disposable += rxBus + .toObservable(EventData.TreatmentData::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "TreatmentData received from ${it.sourceNodeId}") + persistence.store(it) + } + disposable += rxBus + .toObservable(EventData.Preferences::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "Preferences received from ${it.sourceNodeId}") + if (it.wearControl != sp.getBoolean(R.string.key_wear_control, false)) { + sp.putBoolean(R.string.key_wear_control, it.wearControl) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + TileService.getUpdater(context).requestUpdate(ActionsTileService::class.java) + TileService.getUpdater(context).requestUpdate(TempTargetTileService::class.java) + TileService.getUpdater(context).requestUpdate(QuickWizardTileService::class.java) + } + } + sp.putBoolean(R.string.key_units_mgdl, it.unitsMgdl) + sp.putInt(R.string.key_bolus_wizard_percentage, it.bolusPercentage) + sp.putInt(R.string.key_treatments_safety_max_carbs, it.maxCarbs) + sp.putDouble(R.string.key_treatments_safety_max_bolus, it.maxBolus) + } + disposable += rxBus + .toObservable(EventData.QuickWizard::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + aapsLogger.debug(LTag.WEAR, "QuickWizard received from ${it.sourceNodeId}") + val serialized = it.serialize() + if (serialized != sp.getString(R.string.key_quick_wizard_data, "")) { + sp.putString(R.string.key_quick_wizard_data, serialized) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) + TileService.getUpdater(context).requestUpdate(QuickWizardTileService::class.java) + } + } + } + + private fun handleBolusProgress(bolusProgress: EventData.BolusProgress) { + val vibratePattern: LongArray + val vibrate = sp.getBoolean("vibrateOnBolus", true) + vibratePattern = if (vibrate) longArrayOf(0, 50, 1000) else longArrayOf(0, 1, 1000) + + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + createBolusProgressChannels() + } + val cancelIntent = Intent(context, DataLayerListenerServiceWear::class.java) + cancelIntent.action = DataLayerListenerServiceWear.INTENT_CANCEL_BOLUS + val cancelPendingIntent = PendingIntent.getService(context, 0, cancelIntent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + val notificationBuilder: NotificationCompat.Builder = + NotificationCompat.Builder( + context, + if (vibrate) DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS else DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS_SILENT + ) + .setSmallIcon(R.drawable.ic_icon) + .setContentTitle(context.getString(R.string.bolus_progress)) + .setContentText("${bolusProgress.percent}% - ${bolusProgress.status}") + .setSubText(context.getString(R.string.press_to_cancel)) + .setContentIntent(cancelPendingIntent) + .setPriority(NotificationCompat.PRIORITY_MAX) + .setVibrate(vibratePattern) + .addAction(R.drawable.ic_cancel, context.getString(R.string.cancel_bolus), cancelPendingIntent) + val notificationManager = NotificationManagerCompat.from(context) + notificationManager.notify(DataLayerListenerServiceWear.BOLUS_PROGRESS_NOTIF_ID, notificationBuilder.build()) + notificationManager.cancel(DataLayerListenerServiceWear.CONFIRM_NOTIF_ID) // multiple watch setup + if (bolusProgress.percent == 100) { + scheduleDismissBolusProgress(5) + } + } + + @TargetApi(value = 26) private fun createBolusProgressChannels() { + createNotificationChannel( + longArrayOf(0, 50, 1000), + DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS, + context.getString(R.string.bolus_progress_channel_name), + context.getString(R.string.bolus_progress_channel_description) + ) + createNotificationChannel( + longArrayOf(0, 1, 1000), + DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS_SILENT, + context.getString(R.string.bolus_progress_silent_channel_name), + context.getString(R.string.bolus_progress_silent_channel_description) + ) + } + + @TargetApi(value = 26) private fun createNotificationChannel(vibratePattern: LongArray, channelID: String, name: CharSequence, description: String) { + val channel = NotificationChannel(channelID, name, NotificationManager.IMPORTANCE_HIGH) + channel.description = description + channel.enableVibration(true) + channel.vibrationPattern = vibratePattern + + // Register the channel with the system; you can't change the importance + // or other notification behaviors after this + context.getSystemService(NotificationManager::class.java) + .createNotificationChannel(channel) + } + + private fun handleOpenLoopRequest(command: EventData.OpenLoopRequest) { + // Create the NotificationChannel, but only on API 26+ because + // the NotificationChannel class is new and not in the support library + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { + val name: CharSequence = "AAPS Open Loop" + val description = "Open Loop request notification" + val channel = NotificationChannel(DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP, name, NotificationManager.IMPORTANCE_HIGH) + channel.description = description + channel.enableVibration(true) + + // Register the channel with the system; you can't change the importance + // or other notification behaviors after this + context.getSystemService(NotificationManager::class.java).createNotificationChannel(channel) + } + @Suppress("DEPRECATION") + var builder = NotificationCompat.Builder(context, DataLayerListenerServiceWear.AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP) + .setSmallIcon(R.drawable.notif_icon) + .setContentTitle(command.title) + .setContentText(command.message) + .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000)) + .setPriority(Notification.PRIORITY_HIGH) // suppress deprecation, ignored for API >= 26 + + // Creates an explicit intent for an Activity in your app + val intent = Intent(context, AcceptActivity::class.java).apply { + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtras(Bundle().also { bundle -> + bundle.putString(DataLayerListenerServiceWear.KEY_TITLE, command.title) + bundle.putString(DataLayerListenerServiceWear.KEY_MESSAGE, command.message) + bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, command.returnCommand?.serialize()) + }) + } + val resultPendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) + builder = builder.setContentIntent(resultPendingIntent) + val mNotificationManager = context.getSystemService(WearableListenerService.NOTIFICATION_SERVICE) as NotificationManager + // mId allows you to update the notification later on. + mNotificationManager.notify(DataLayerListenerServiceWear.CHANGE_NOTIF_ID, builder.build()) + } + + @Suppress("SameParameterValue") + private fun scheduleDismissBolusProgress(seconds: Int) { + Thread { + SystemClock.sleep(seconds * 1000L) + NotificationManagerCompat.from(context).cancel(DataLayerListenerServiceWear.BOLUS_PROGRESS_NOTIF_ID) + }.start() + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt b/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt new file mode 100644 index 0000000000..e027d0fcbd --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/DataLayerListenerServiceWear.kt @@ -0,0 +1,215 @@ +package info.nightscout.androidaps.comm + +import android.app.NotificationManager +import android.content.Intent +import android.os.Handler +import android.os.HandlerThread +import androidx.core.app.NotificationManagerCompat +import com.google.android.gms.tasks.Tasks +import com.google.android.gms.wearable.* +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import kotlinx.coroutines.* +import kotlinx.coroutines.tasks.await +import javax.inject.Inject + +class DataLayerListenerServiceWear : WearableListenerService() { + + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var wearUtil: WearUtil + @Inject lateinit var persistence: Persistence + @Inject lateinit var sp: SP + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + + private val dataClient by lazy { Wearable.getDataClient(this) } + private val messageClient by lazy { Wearable.getMessageClient(this) } + private val capabilityClient by lazy { Wearable.getCapabilityClient(this) } + //private val nodeClient by lazy { Wearable.getNodeClient(this) } + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) + private var handler = Handler(HandlerThread(this::class.simpleName + "Handler").also { it.start() }.looper) + + private val disposable = CompositeDisposable() + + private val rxPath get() = getString(R.string.path_rx_bridge) + + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + handler.post { updateTranscriptionCapability() } + disposable += rxBus + .toObservable(EventWearToMobile::class.java) + .observeOn(aapsSchedulers.io) + .subscribe { + sendMessage(rxPath, it.payload.serialize()) + } + } + + override fun onPeerConnected(p0: Node) { + super.onPeerConnected(p0) + } + + override fun onCapabilityChanged(p0: CapabilityInfo) { + super.onCapabilityChanged(p0) + handler.post { updateTranscriptionCapability() } + aapsLogger.debug(LTag.WEAR, "onCapabilityChanged: ${p0.name} ${p0.nodes.joinToString(", ") { it.displayName + "(" + it.id + ")" }}") + } + + override fun onDestroy() { + super.onDestroy() + scope.cancel() + disposable.clear() + } + + override fun onDataChanged(dataEvents: DataEventBuffer) { + //aapsLogger.debug(LTag.WEAR, "onDataChanged") + + dataEvents.forEach { event -> + if (event.type == DataEvent.TYPE_CHANGED) { + val path = event.dataItem.uri.path + + aapsLogger.debug(LTag.WEAR, "onDataChanged: Path: $path, EventDataItem=${event.dataItem}") + try { + @Suppress("ControlFlowWithEmptyBody", "UNUSED_EXPRESSION") + when (path) { + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, "onDataChanged failed", exception) + } + } + } + super.onDataChanged(dataEvents) + } + + override fun onMessageReceived(messageEvent: MessageEvent) { + super.onMessageReceived(messageEvent) + + when (messageEvent.path) { + rxPath -> { + aapsLogger.debug(LTag.WEAR, "onMessageReceived: ${String(messageEvent.data)}") + val command = EventData.deserialize(String(messageEvent.data)) + rxBus.send(command.also { it.sourceNodeId = messageEvent.sourceNodeId }) + // Use this sender + transcriptionNodeId = messageEvent.sourceNodeId + aapsLogger.debug(LTag.WEAR, "Updated node: $transcriptionNodeId") + } + } + } + + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + when (intent?.action) { + + INTENT_CANCEL_BOLUS -> { + //dismiss notification + NotificationManagerCompat.from(this).cancel(BOLUS_PROGRESS_NOTIF_ID) + //send cancel-request to phone. + rxBus.send(EventWearToMobile(EventData.CancelBolus(System.currentTimeMillis()))) + } + + INTENT_WEAR_TO_MOBILE -> sendMessage(rxPath, intent.extras?.getString(KEY_ACTION_DATA)) + INTENT_CANCEL_NOTIFICATION -> (getSystemService(NOTIFICATION_SERVICE) as NotificationManager).cancel(CHANGE_NOTIF_ID) + } + return START_STICKY + } + + private var transcriptionNodeId: String? = null + + private fun updateTranscriptionCapability() { + val capabilityInfo: CapabilityInfo = Tasks.await( + capabilityClient.getCapability(PHONE_CAPABILITY, CapabilityClient.FILTER_REACHABLE) + ) + aapsLogger.debug(LTag.WEAR, "Nodes: ${capabilityInfo.nodes.joinToString(", ") { it.displayName + "(" + it.id + ")" }}") + pickBestNodeId(capabilityInfo.nodes)?.let { transcriptionNodeId = it } + aapsLogger.debug(LTag.WEAR, "Selected node: $transcriptionNodeId") + } + + // Find a nearby node or pick one arbitrarily + private fun pickBestNodeId(nodes: Set): String? = + nodes.firstOrNull { it.isNearby }?.id ?: nodes.firstOrNull()?.id + + @Suppress("unused") + private fun sendData(path: String, vararg params: DataMap) { + scope.launch { + try { + for (dm in params) { + val request = PutDataMapRequest.create(path).apply { + dataMap.putAll(dm) + } + .asPutDataRequest() + .setUrgent() + + val result = dataClient.putDataItem(request).await() + aapsLogger.debug(LTag.WEAR, "sendData: ${result.uri} ${params.joinToString()}") + } + } catch (cancellationException: CancellationException) { + throw cancellationException + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, "DataItem failed: $exception") + } + } + } + + private fun sendMessage(path: String, data: String?) { + transcriptionNodeId?.also { nodeId -> + aapsLogger.debug(LTag.WEAR, "sendMessage: $path $data") + messageClient + .sendMessage(nodeId, path, data?.toByteArray() ?: byteArrayOf()).apply { + addOnSuccessListener { } + addOnFailureListener { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure $it") + } + } + } ?: aapsLogger.debug(LTag.WEAR, "sendMessage: Ignoring message. No node selected.") + } + + @Suppress("unused") + private fun sendMessage(path: String, data: ByteArray) { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path") + transcriptionNodeId?.also { nodeId -> + messageClient + .sendMessage(nodeId, path, data).apply { + addOnSuccessListener { } + addOnFailureListener { + aapsLogger.debug(LTag.WEAR, "sendMessage: $path failure") + } + } + } + } + + companion object { + + const val PHONE_CAPABILITY = "androidaps_mobile" + + // Accepted intents + val INTENT_NEW_DATA = DataLayerListenerServiceWear::class.java.name + ".NewData" + val INTENT_CANCEL_BOLUS = DataLayerListenerServiceWear::class.java.name + ".CancelBolus" + val INTENT_WEAR_TO_MOBILE = DataLayerListenerServiceWear::class.java.name + ".WearToMobile" + val INTENT_CANCEL_NOTIFICATION = DataLayerListenerServiceWear::class.java.name + ".CancelNotification" + + //data keys + const val KEY_ACTION_DATA = "actionData" + const val KEY_ACTION = "action" + const val KEY_MESSAGE = "message" + const val KEY_TITLE = "title" + + const val BOLUS_PROGRESS_NOTIF_ID = 1 + const val CONFIRM_NOTIF_ID = 2 + const val CHANGE_NOTIF_ID = 556677 + + const val AAPS_NOTIFY_CHANNEL_ID_OPEN_LOOP = "AndroidAPS-OpenLoop" + const val AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS = "bolus progress vibration" + const val AAPS_NOTIFY_CHANNEL_ID_BOLUS_PROGRESS_SILENT = "bolus progress silent" + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt b/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt new file mode 100644 index 0000000000..3c8b557ceb --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/IntentCancelNotification.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.comm + +import android.content.Context +import android.content.Intent + +class IntentCancelNotification(context: Context) : Intent(context, DataLayerListenerServiceWear::class.java) { + init { + action = DataLayerListenerServiceWear.INTENT_CANCEL_NOTIFICATION + addFlags(FLAG_ACTIVITY_NEW_TASK) + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt b/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt new file mode 100644 index 0000000000..bea1f9a157 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/comm/IntentWearToMobile.kt @@ -0,0 +1,19 @@ +package info.nightscout.androidaps.comm + +import android.content.Context +import android.content.Intent +import android.os.Bundle +import info.nightscout.shared.weardata.EventData + +class IntentWearToMobile(context: Context, command: String) : Intent(context, DataLayerListenerServiceWear::class.java) { + init { + action = DataLayerListenerServiceWear.INTENT_WEAR_TO_MOBILE + addFlags(FLAG_ACTIVITY_NEW_TASK) + putExtras(Bundle().also { bundle -> + bundle.putString(DataLayerListenerServiceWear.KEY_ACTION_DATA, command) + }) + } + + @Suppress("unused") + constructor(context: Context, command: EventData) : this(context, command.serialize()) +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java deleted file mode 100644 index 8c5a3d2c47..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.java +++ /dev/null @@ -1,409 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.content.BroadcastReceiver; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.graphics.drawable.Icon; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationManager; -import android.support.wearable.complications.ComplicationProviderService; -import android.support.wearable.complications.ComplicationText; -import android.support.wearable.complications.ProviderUpdateRequester; - -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import java.util.HashSet; -import java.util.Set; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.androidaps.interaction.utils.Inevitable; -import info.nightscout.androidaps.interaction.utils.Persistence; -import info.nightscout.androidaps.interaction.utils.WearUtil; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; - -/** - * Base class for all complications - *

- * Created by dlvoy on 2019-11-12 - */ -public abstract class BaseComplicationProviderService extends ComplicationProviderService { - - @Inject Inevitable inevitable; - @Inject WearUtil wearUtil; - @Inject DisplayFormat displayFormat; - @Inject Persistence persistence; - @Inject AAPSLogger aapsLogger; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public static final String KEY_COMPLICATIONS = "complications"; - private static final String KEY_LAST_SHOWN_SINCE_VALUE = "lastSince"; - private static final String KEY_STALE_REPORTED = "staleReported"; - private static final String TASK_ID_REFRESH_COMPLICATION = "refresh-complication"; - - - private LocalBroadcastManager localBroadcastManager; - private MessageReceiver messageReceiver; - - //============================================================================================== - // ABSTRACT COMPLICATION INTERFACE - //============================================================================================== - - public abstract ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent); - - public abstract String getProviderCanonicalName(); - - public ComplicationAction getComplicationAction() { - return ComplicationAction.MENU; - } - - //---------------------------------------------------------------------------------------------- - // DEFAULT BEHAVIOURS - //---------------------------------------------------------------------------------------------- - - public ComplicationData buildNoSyncComplicationData(int dataType, - RawDisplayData raw, - PendingIntent complicationPendingIntent, - PendingIntent exceptionalPendingIntent, - long since) { - - - final ComplicationData.Builder builder = new ComplicationData.Builder(dataType); - if (dataType != ComplicationData.TYPE_LARGE_IMAGE) { - builder.setIcon(Icon.createWithResource(this, R.drawable.ic_sync_alert)); - } - - if (dataType == ComplicationData.TYPE_RANGED_VALUE) { - builder.setMinValue(0); - builder.setMaxValue(100); - builder.setValue(0); - } - - switch (dataType) { - case ComplicationData.TYPE_ICON: - case ComplicationData.TYPE_SHORT_TEXT: - case ComplicationData.TYPE_RANGED_VALUE: - if (since > 0) { - builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old")); - } else { - builder.setShortText(ComplicationText.plainText("!err!")); - } - break; - case ComplicationData.TYPE_LONG_TEXT: - builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_sync))); - if (since > 0) { - builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since)))); - } else { - builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps))); - } - break; - case ComplicationData.TYPE_LARGE_IMAGE: - return buildComplicationData(dataType, raw, complicationPendingIntent); - default: - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - break; - } - - builder.setTapAction(exceptionalPendingIntent); - return builder.build(); - } - - public ComplicationData buildOutdatedComplicationData(int dataType, - RawDisplayData raw, - PendingIntent complicationPendingIntent, - PendingIntent exceptionalPendingIntent, - long since) { - - final ComplicationData.Builder builder = new ComplicationData.Builder(dataType); - if (dataType != ComplicationData.TYPE_LARGE_IMAGE) { - builder.setIcon(Icon.createWithResource(this, R.drawable.ic_alert)); - builder.setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_alert_burnin)); - } - - if (dataType == ComplicationData.TYPE_RANGED_VALUE) { - builder.setMinValue(0); - builder.setMaxValue(100); - builder.setValue(0); - } - - switch (dataType) { - case ComplicationData.TYPE_ICON: - case ComplicationData.TYPE_SHORT_TEXT: - case ComplicationData.TYPE_RANGED_VALUE: - if (since > 0) { - builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old")); - } else { - builder.setShortText(ComplicationText.plainText("!old!")); - } - break; - case ComplicationData.TYPE_LONG_TEXT: - builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_old))); - if (since > 0) { - builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since)))); - } else { - builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps))); - } - break; - case ComplicationData.TYPE_LARGE_IMAGE: - return buildComplicationData(dataType, raw, complicationPendingIntent); - default: - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - break; - } - - builder.setTapAction(exceptionalPendingIntent); - return builder.build(); - } - - /** - * If Complication depend on "since" field and need to be updated every minute or not - * and need only update when new DisplayRawData arrive - */ - protected boolean usesSinceField() { - return false; - } - - //============================================================================================== - // COMPLICATION LIFECYCLE - //============================================================================================== - - /* - * Called when a complication has been activated. The method is for any one-time - * (per complication) set-up. - * - * You can continue sending data for the active complicationId until onComplicationDeactivated() - * is called. - */ - @Override - public void onComplicationActivated( - int complicationId, int dataType, ComplicationManager complicationManager) { - aapsLogger.warn(LTag.WEAR, "onComplicationActivated(): " + complicationId + " of kind: " + getProviderCanonicalName()); - - persistence.putString("complication_" + complicationId, getProviderCanonicalName()); - persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField()); - persistence.addToSet(KEY_COMPLICATIONS, "complication_" + complicationId); - - IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); - - messageReceiver = new MessageReceiver(); - localBroadcastManager = LocalBroadcastManager.getInstance(this); - localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - - ListenerService.requestData(this); - checkIfUpdateNeeded(); - } - - /* - * Called when the complication needs updated data from your provider. There are four scenarios - * when this will happen: - * - * 1. An active watch face complication is changed to use this provider - * 2. A complication using this provider becomes active - * 3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS) - * 4. You triggered an update from your own class via the - * ProviderUpdateRequester.requestUpdate() method. - */ - @Override - public void onComplicationUpdate( - int complicationId, int dataType, ComplicationManager complicationManager) { - aapsLogger.warn(LTag.WEAR, "onComplicationUpdate() id: " + complicationId + " of class: " + getProviderCanonicalName()); - - // Create Tap Action so that the user can checkIfUpdateNeeded an update by tapping the complication. - final ComponentName thisProvider = new ComponentName(this, getProviderCanonicalName()); - - // We pass the complication id, so we can only update the specific complication tapped. - final PendingIntent complicationPendingIntent = - ComplicationTapBroadcastReceiver.getTapActionIntent( - getApplicationContext(), thisProvider, complicationId, getComplicationAction()); - - final RawDisplayData raw = new RawDisplayData(wearUtil); - raw.updateForComplicationsFromPersistence(persistence); - aapsLogger.warn(LTag.WEAR, "Complication data: " + raw.toDebugString()); - - // store what is currently rendered in 'SGV since' field, to detect if it was changed and need update - persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, displayFormat.shortTimeSince(raw.datetime)); - - // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round - persistence.putBoolean(KEY_STALE_REPORTED, false); - - ComplicationData complicationData; - - if (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) { - // no new data arrived - probably configuration or connection error - final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent( - getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated()); - complicationData = buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated()); - } else if (wearUtil.msSince(raw.datetime) > Constants.STALE_MS) { - // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error) - final PendingIntent infoToast = ComplicationTapBroadcastReceiver.getTapWarningSinceIntent( - getApplicationContext(), thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.datetime); - complicationData = buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.datetime); - } else { - // data is up-to-date, we can render standard complication - complicationData = buildComplicationData(dataType, raw, complicationPendingIntent); - } - - if (complicationData != null) { - complicationManager.updateComplicationData(complicationId, complicationData); - } else { - // If no data is sent, we still need to inform the ComplicationManager, so the update - // job can finish and the wake lock isn't held any longer than necessary. - complicationManager.noUpdateRequired(complicationId); - } - } - - /* - * Called when the complication has been deactivated. - */ - @Override - public void onComplicationDeactivated(int complicationId) { - aapsLogger.warn(LTag.WEAR, "onComplicationDeactivated(): " + complicationId); - - persistence.removeFromSet(KEY_COMPLICATIONS, "complication_" + complicationId); - - if (localBroadcastManager != null && messageReceiver != null) { - localBroadcastManager.unregisterReceiver(messageReceiver); - } - inevitable.kill(TASK_ID_REFRESH_COMPLICATION); - } - - //============================================================================================== - // UPDATE AND REFRESH LOGIC - //============================================================================================== - - /* - * Schedule check for field update - */ - public void checkIfUpdateNeeded() { - - aapsLogger.warn(LTag.WEAR, "Pending check if update needed - " + persistence.getString(KEY_COMPLICATIONS, "")); - - inevitable.task(TASK_ID_REFRESH_COMPLICATION, 15 * Constants.SECOND_IN_MS, () -> { - if (wearUtil.isBelowRateLimit("complication-checkIfUpdateNeeded", 5)) { - aapsLogger.warn(LTag.WEAR, "Checking if update needed"); - requestUpdateIfSinceChanged(); - // We reschedule need for check - to make sure next check will Inevitable go in next 15s - checkIfUpdateNeeded(); - } - }); - - } - - /* - * Check if displayed since field (field that shows how old, in minutes, is reading) - * is up-to-date or need to be changed (a minute or more elapsed) - */ - private void requestUpdateIfSinceChanged() { - final RawDisplayData raw = new RawDisplayData(wearUtil); - raw.updateForComplicationsFromPersistence(persistence); - - final String lastSince = persistence.getString(KEY_LAST_SHOWN_SINCE_VALUE, "-"); - final String calcSince = displayFormat.shortTimeSince(raw.datetime); - final boolean isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS) - || (wearUtil.msSince(raw.datetime) > Constants.STALE_MS); - - final boolean staleWasRefreshed = persistence.getBoolean(KEY_STALE_REPORTED, false); - final boolean sinceWasChanged = !lastSince.equals(calcSince); - - if (sinceWasChanged || (isStale && !staleWasRefreshed)) { - persistence.putString(KEY_LAST_SHOWN_SINCE_VALUE, calcSince); - persistence.putBoolean(KEY_STALE_REPORTED, isStale); - - aapsLogger.warn(LTag.WEAR, "Detected refresh of time needed! Reason: " - + (isStale ? "- stale detected" : "") - + (sinceWasChanged ? "- since changed from: " + lastSince + " to: " + calcSince : "")); - - if (isStale) { - // all complications should update to show offline/old warning - requestUpdate(getActiveProviderClasses()); - } else { - // ... but only some require update due to 'since' field change - requestUpdate(getSinceDependingProviderClasses()); - } - } - } - - /* - * Request update for specified list of providers - */ - private void requestUpdate(Set providers) { - for (String provider : providers) { - aapsLogger.warn(LTag.WEAR, "Pending update of " + provider); - // We wait with updating allowing all request, from various sources, to arrive - inevitable.task("update-req-" + provider, 700, () -> { - if (wearUtil.isBelowRateLimit("update-req-" + provider, 2)) { - aapsLogger.warn(LTag.WEAR, "Requesting update of " + provider); - final ComponentName componentName = new ComponentName(getApplicationContext(), provider); - final ProviderUpdateRequester providerUpdateRequester = new ProviderUpdateRequester(getApplicationContext(), componentName); - providerUpdateRequester.requestUpdateAll(); - } - }); - } - } - - /* - * List all Complication providing classes that have active (registered) providers - */ - private Set getActiveProviderClasses() { - Set providers = new HashSet<>(); - Set complications = persistence.getSetOf(KEY_COMPLICATIONS); - for (String complication : complications) { - final String providerClass = persistence.getString(complication, ""); - if (providerClass.length() > 0) { - providers.add(providerClass); - } - } - return providers; - } - - /* - * List all Complication providing classes that have active (registered) providers - * and additionally they depend on "since" field - * == they need to be updated not only on data broadcasts, but every minute or so - */ - private Set getSinceDependingProviderClasses() { - Set providers = new HashSet<>(); - Set complications = persistence.getSetOf(KEY_COMPLICATIONS); - for (String complication : complications) { - final String providerClass = persistence.getString(complication, ""); - final boolean dependOnSince = persistence.getBoolean(complication + "_since", false); - if ((providerClass.length() > 0) && (dependOnSince)) { - providers.add(providerClass); - } - } - return providers; - } - - /* - * Listen to broadcast --> new data was stored by ListenerService to Persistence - */ - public class MessageReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - Set complications = persistence.getSetOf(KEY_COMPLICATIONS); - if (complications.size() > 0) { - checkIfUpdateNeeded(); - // We request all active providers - requestUpdate(getActiveProviderClasses()); - } - } - } - - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt new file mode 100644 index 0000000000..fc5769c078 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BaseComplicationProviderService.kt @@ -0,0 +1,380 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.content.BroadcastReceiver +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.graphics.drawable.Icon +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationManager +import android.support.wearable.complications.ComplicationProviderService +import android.support.wearable.complications.ComplicationText +import android.support.wearable.complications.ProviderUpdateRequester +import androidx.localbroadcastmanager.content.LocalBroadcastManager +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear.Companion.INTENT_NEW_DATA +import info.nightscout.androidaps.complications.ComplicationTapBroadcastReceiver.Companion.getTapActionIntent +import info.nightscout.androidaps.complications.ComplicationTapBroadcastReceiver.Companion.getTapWarningSinceIntent +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.Constants +import info.nightscout.androidaps.interaction.utils.DisplayFormat +import info.nightscout.androidaps.interaction.utils.Inevitable +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.weardata.EventData.ActionResendData +import javax.inject.Inject + +/** + * Base class for all complications + * + * + * Created by dlvoy on 2019-11-12 + */ +abstract class BaseComplicationProviderService : ComplicationProviderService() { + + @Inject lateinit var inevitable: Inevitable + @Inject lateinit var wearUtil: WearUtil + @Inject lateinit var displayFormat: DisplayFormat + @Inject lateinit var persistence: Persistence + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBus + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + private var localBroadcastManager: LocalBroadcastManager? = null + private var messageReceiver: MessageReceiver? = null + + //============================================================================================== + // ABSTRACT COMPLICATION INTERFACE + //============================================================================================== + abstract fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? + abstract fun getProviderCanonicalName(): String + open fun getComplicationAction(): ComplicationAction = ComplicationAction.MENU + + //---------------------------------------------------------------------------------------------- + // DEFAULT BEHAVIOURS + //---------------------------------------------------------------------------------------------- + private fun buildNoSyncComplicationData( + dataType: Int, + raw: RawDisplayData, + complicationPendingIntent: PendingIntent, + exceptionalPendingIntent: PendingIntent, + since: Long + ): ComplicationData? { + val builder = ComplicationData.Builder(dataType) + if (dataType != ComplicationData.TYPE_LARGE_IMAGE) { + builder.setIcon(Icon.createWithResource(this, R.drawable.ic_sync_alert)) + } + if (dataType == ComplicationData.TYPE_RANGED_VALUE) { + builder.setMinValue(0f) + builder.setMaxValue(100f) + builder.setValue(0f) + } + when (dataType) { + ComplicationData.TYPE_ICON, ComplicationData.TYPE_SHORT_TEXT, ComplicationData.TYPE_RANGED_VALUE -> if (since > 0) { + builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old")) + } else { + builder.setShortText(ComplicationText.plainText("!err!")) + } + + ComplicationData.TYPE_LONG_TEXT -> { + builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_sync))) + if (since > 0) { + builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since)))) + } else { + builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps))) + } + } + + ComplicationData.TYPE_LARGE_IMAGE -> return buildComplicationData(dataType, raw, complicationPendingIntent) + else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + builder.setTapAction(exceptionalPendingIntent) + return builder.build() + } + + private fun buildOutdatedComplicationData( + dataType: Int, + raw: RawDisplayData, + complicationPendingIntent: PendingIntent, + exceptionalPendingIntent: PendingIntent, + since: Long + ): ComplicationData? { + val builder = ComplicationData.Builder(dataType) + if (dataType != ComplicationData.TYPE_LARGE_IMAGE) { + builder.setIcon(Icon.createWithResource(this, R.drawable.ic_alert)) + builder.setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_alert_burnin)) + } + if (dataType == ComplicationData.TYPE_RANGED_VALUE) { + builder.setMinValue(0f) + builder.setMaxValue(100f) + builder.setValue(0f) + } + when (dataType) { + ComplicationData.TYPE_ICON, ComplicationData.TYPE_SHORT_TEXT, ComplicationData.TYPE_RANGED_VALUE -> if (since > 0) { + builder.setShortText(ComplicationText.plainText(displayFormat.shortTimeSince(since) + " old")) + } else { + builder.setShortText(ComplicationText.plainText("!old!")) + } + + ComplicationData.TYPE_LONG_TEXT -> { + builder.setLongTitle(ComplicationText.plainText(getString(R.string.label_warning_old))) + if (since > 0) { + builder.setLongText(ComplicationText.plainText(String.format(getString(R.string.label_warning_since), displayFormat.shortTimeSince(since)))) + } else { + builder.setLongText(ComplicationText.plainText(getString(R.string.label_warning_sync_aaps))) + } + } + + ComplicationData.TYPE_LARGE_IMAGE -> return buildComplicationData(dataType, raw, complicationPendingIntent) + else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + builder.setTapAction(exceptionalPendingIntent) + return builder.build() + } + + /** + * If Complication depend on "since" field and need to be updated every minute or not + * and need only update when new DisplayRawData arrive + */ + protected open fun usesSinceField(): Boolean { + return false + } + + //============================================================================================== + // COMPLICATION LIFECYCLE + //============================================================================================== + /* + * Called when a complication has been activated. The method is for any one-time + * (per complication) set-up. + * + * You can continue sending data for the active complicationId until onComplicationDeactivated() + * is called. + */ + override fun onComplicationActivated( + complicationId: Int, dataType: Int, complicationManager: ComplicationManager + ) { + aapsLogger.warn(LTag.WEAR, "onComplicationActivated(): $complicationId of kind: ${getProviderCanonicalName()}") + persistence.putString("complication_$complicationId", getProviderCanonicalName()) + persistence.putBoolean("complication_" + complicationId + "_since", usesSinceField()) + persistence.addToSet(Persistence.KEY_COMPLICATIONS, "complication_$complicationId") + val messageFilter = IntentFilter(INTENT_NEW_DATA) + messageReceiver = MessageReceiver() + localBroadcastManager = LocalBroadcastManager.getInstance(this) + messageReceiver?.let { localBroadcastManager?.registerReceiver(it, messageFilter) } + rxBus.send(EventWearToMobile(ActionResendData("BaseComplicationProviderService"))) + checkIfUpdateNeeded() + } + + /* + * Called when the complication needs updated data from your provider. There are four scenarios + * when this will happen: + * + * 1. An active watch face complication is changed to use this provider + * 2. A complication using this provider becomes active + * 3. The period of time you specified in the manifest has elapsed (UPDATE_PERIOD_SECONDS) + * 4. You triggered an update from your own class via the + * ProviderUpdateRequester.requestUpdate() method. + */ + override fun onComplicationUpdate( + complicationId: Int, dataType: Int, complicationManager: ComplicationManager + ) { + aapsLogger.warn(LTag.WEAR, "onComplicationUpdate() id: $complicationId of class: ${getProviderCanonicalName()}") + + // Create Tap Action so that the user can checkIfUpdateNeeded an update by tapping the complication. + val thisProvider = ComponentName(this, getProviderCanonicalName()) + + // We pass the complication id, so we can only update the specific complication tapped. + val complicationPendingIntent = getTapActionIntent(applicationContext, thisProvider, complicationId, getComplicationAction()) + val raw = RawDisplayData() + raw.updateFromPersistence(persistence) + aapsLogger.warn(LTag.WEAR, "Complication data: " + raw.toDebugString()) + + // store what is currently rendered in 'SGV since' field, to detect if it was changed and need update + persistence.putString( + Persistence.KEY_LAST_SHOWN_SINCE_VALUE, + displayFormat.shortTimeSince(raw.singleBg.timeStamp) + ) + + // by each render we clear stale flag to ensure it is re-rendered at next refresh detection round + persistence.putBoolean(Persistence.KEY_STALE_REPORTED, false) + val complicationData: ComplicationData? = when { + wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS -> { + // no new data arrived - probably configuration or connection error + val infoToast = getTapWarningSinceIntent( + applicationContext, thisProvider, complicationId, ComplicationAction.WARNING_SYNC, persistence.whenDataUpdated() + ) + buildNoSyncComplicationData(dataType, raw, complicationPendingIntent, infoToast, persistence.whenDataUpdated()) + } + + wearUtil.msSince(raw.singleBg.timeStamp) > Constants.STALE_MS -> { + // data arriving from phone AAPS, but it is outdated (uploader/NS/xDrip/Sensor error) + val infoToast = getTapWarningSinceIntent( + applicationContext, thisProvider, complicationId, ComplicationAction.WARNING_OLD, raw.singleBg.timeStamp + ) + buildOutdatedComplicationData(dataType, raw, complicationPendingIntent, infoToast, raw.singleBg.timeStamp) + } + + else -> { + // data is up-to-date, we can render standard complication + buildComplicationData(dataType, raw, complicationPendingIntent) + } + } + if (complicationData != null) { + complicationManager.updateComplicationData(complicationId, complicationData) + } else { + // If no data is sent, we still need to inform the ComplicationManager, so the update + // job can finish and the wake lock isn't held any longer than necessary. + complicationManager.noUpdateRequired(complicationId) + } + } + + /* + * Called when the complication has been deactivated. + */ + override fun onComplicationDeactivated(complicationId: Int) { + aapsLogger.warn(LTag.WEAR, "onComplicationDeactivated(): $complicationId") + persistence.removeFromSet(Persistence.KEY_COMPLICATIONS, "complication_$complicationId") + messageReceiver?.let { localBroadcastManager?.unregisterReceiver(it) } + inevitable.kill(TASK_ID_REFRESH_COMPLICATION) + } + + //============================================================================================== + // UPDATE AND REFRESH LOGIC + //============================================================================================== + /* + * Schedule check for field update + */ + private fun checkIfUpdateNeeded() { + aapsLogger.warn(LTag.WEAR, "Pending check if update needed - " + persistence.getString(Persistence.KEY_COMPLICATIONS, "")) + inevitable.task(TASK_ID_REFRESH_COMPLICATION, 15 * Constants.SECOND_IN_MS) { + if (wearUtil.isBelowRateLimit("complication-checkIfUpdateNeeded", 5)) { + aapsLogger.warn(LTag.WEAR, "Checking if update needed") + requestUpdateIfSinceChanged() + // We reschedule need for check - to make sure next check will Inevitable go in next 15s + checkIfUpdateNeeded() + } + } + } + + /* + * Check if displayed since field (field that shows how old, in minutes, is reading) + * is up-to-date or need to be changed (a minute or more elapsed) + */ + private fun requestUpdateIfSinceChanged() { + val raw = RawDisplayData() + raw.updateFromPersistence(persistence) + val lastSince = persistence.getString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, "-") + val calcSince = displayFormat.shortTimeSince(raw.singleBg.timeStamp) + val isStale = (wearUtil.msSince(persistence.whenDataUpdated()) > Constants.STALE_MS + || wearUtil.msSince(raw.singleBg.timeStamp) > Constants.STALE_MS) + val staleWasRefreshed = persistence.getBoolean(Persistence.KEY_STALE_REPORTED, false) + val sinceWasChanged = lastSince != calcSince + if (sinceWasChanged || isStale && !staleWasRefreshed) { + persistence.putString(Persistence.KEY_LAST_SHOWN_SINCE_VALUE, calcSince) + persistence.putBoolean(Persistence.KEY_STALE_REPORTED, isStale) + aapsLogger.warn( + LTag.WEAR, "Detected refresh of time needed! Reason: " + + (if (isStale) "- stale detected" else "") + + if (sinceWasChanged) "- since changed from: $lastSince to: $calcSince" else "" + ) + if (isStale) { + // all complications should update to show offline/old warning + requestUpdate(activeProviderClasses) + } else { + // ... but only some require update due to 'since' field change + requestUpdate(sinceDependingProviderClasses) + } + } + } + + /* + * Request update for specified list of providers + */ + private fun requestUpdate(providers: Set) { + for (provider in providers) { + aapsLogger.warn(LTag.WEAR, "Pending update of $provider") + // We wait with updating allowing all request, from various sources, to arrive + inevitable.task("update-req-$provider", 700) { + if (wearUtil.isBelowRateLimit("update-req-$provider", 2)) { + aapsLogger.warn(LTag.WEAR, "Requesting update of $provider") + val componentName = ComponentName(applicationContext, provider) + val providerUpdateRequester = ProviderUpdateRequester(applicationContext, componentName) + providerUpdateRequester.requestUpdateAll() + } + } + } + } + + /* + * List all Complication providing classes that have active (registered) providers + */ + private val activeProviderClasses: Set + get() { + val providers: MutableSet = HashSet() + val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS) + for (complication in complications) { + val providerClass = persistence.getString(complication, "") + if (providerClass.isNotEmpty()) { + providers.add(providerClass) + } + } + return providers + } + + /* + * List all Complication providing classes that have active (registered) providers + * and additionally they depend on "since" field + * == they need to be updated not only on data broadcasts, but every minute or so + */ + private val sinceDependingProviderClasses: Set + get() { + val providers: MutableSet = HashSet() + val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS) + for (complication in complications) { + val providerClass = persistence.getString(complication, "") + val dependOnSince = persistence.getBoolean(complication + "_since", false) + if (providerClass.isNotEmpty() && dependOnSince) { + providers.add(providerClass) + } + } + return providers + } + + /* + * Listen to broadcast --> new data was stored by ListenerService to Persistence + */ + inner class MessageReceiver : BroadcastReceiver() { + + override fun onReceive(context: Context, intent: Intent) { + updateAll() + } + } + + private fun updateAll() { + val complications = persistence.getSetOf(Persistence.KEY_COMPLICATIONS) + if (complications.isNotEmpty()) { + checkIfUpdateNeeded() + // We request all active providers + requestUpdate(activeProviderClasses) + } + } + + companion object { + + private const val TASK_ID_REFRESH_COMPLICATION = "refresh-complication" + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java deleted file mode 100644 index 10295844c4..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.java +++ /dev/null @@ -1,54 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; -import android.util.Log; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.androidaps.interaction.utils.SmallestDoubleString; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class BrCobIobComplication extends BaseComplicationProviderService { - - @Inject DisplayFormat displayFormat; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - final String cob = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB); - final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(Math.max(displayFormat.MIN_FIELD_LEN_IOB, (displayFormat.MAX_FIELD_LEN_SHORT - 1) - cob.length())); - - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.sBasalRate)) - .setShortTitle(ComplicationText.plainText(cob + " " + iob)) - .setTapAction(complicationPendingIntent); - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return BrCobIobComplication.class.getCanonicalName(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt new file mode 100644 index 0000000000..308aaf2d73 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt @@ -0,0 +1,42 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import dagger.android.AndroidInjection +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.interaction.utils.SmallestDoubleString +import info.nightscout.shared.logging.LTag +import kotlin.math.max + +/* + * Created by dlvoy on 2019-11-12 + */ +class BrCobIobComplication : BaseComplicationProviderService() { + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val cob = SmallestDoubleString(raw.status.cob, SmallestDoubleString.Units.USE).minimise(displayFormat.MIN_FIELD_LEN_COB) + val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(max(displayFormat.MIN_FIELD_LEN_IOB, displayFormat.MAX_FIELD_LEN_SHORT - 1 - cob.length)) + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.status.currentBasal)) + .setShortTitle(ComplicationText.plainText("$cob $iob")) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = BrCobIobComplication::class.java.canonicalName!! +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java deleted file mode 100644 index 3f77ca3fb5..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.java +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.Pair; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class CobDetailedComplication extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - - Pair cob = displayFormat.detailedCob(raw); - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(cob.first)) - .setTapAction(complicationPendingIntent); - - if (cob.second.length() > 0) { - builder.setShortTitle(ComplicationText.plainText(cob.second)); - } - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return CobDetailedComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.WIZARD; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt new file mode 100644 index 0000000000..9228627720 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobDetailedComplication.kt @@ -0,0 +1,35 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class CobDetailedComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val cob = displayFormat.detailedCob(raw) + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(cob.first)) + .setTapAction(complicationPendingIntent) + if (cob.second.isNotEmpty()) { + builder.setShortTitle(ComplicationText.plainText(cob.second)) + } + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = CobDetailedComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.WIZARD +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java deleted file mode 100644 index 98ffdb1e56..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.java +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.graphics.drawable.Icon; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class CobIconComplication extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(raw.sCOB2)) - .setIcon( - Icon.createWithResource( - this, R.drawable.ic_carbs)) - .setBurnInProtectionIcon( - Icon.createWithResource( - this, R.drawable.ic_carbs)) - .setTapAction(complicationPendingIntent); - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return CobIconComplication.class.getCanonicalName(); - } - - public ComplicationAction getComplicationAction() { - return ComplicationAction.WIZARD; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt new file mode 100644 index 0000000000..9c38290f75 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIconComplication.kt @@ -0,0 +1,35 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.graphics.drawable.Icon +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class CobIconComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(raw.status.cob)) + .setIcon(Icon.createWithResource(this, R.drawable.ic_carbs)) + .setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_carbs)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = CobIconComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.WIZARD +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java deleted file mode 100644 index 62109b1dfc..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.java +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.SmallestDoubleString; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class CobIobComplication extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - final String cob = raw.sCOB2; - final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT); - - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(cob)) - .setShortTitle(ComplicationText.plainText(iob)) - .setTapAction(complicationPendingIntent); - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return CobIobComplication.class.getCanonicalName(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt new file mode 100644 index 0000000000..339f2fae85 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/CobIobComplication.kt @@ -0,0 +1,34 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.interaction.utils.SmallestDoubleString +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class CobIobComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val cob = raw.status.cob + val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT) + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(cob)) + .setShortTitle(ComplicationText.plainText(iob)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = CobIobComplication::class.java.canonicalName!! +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java deleted file mode 100644 index 9ca1e9c456..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.java +++ /dev/null @@ -1,12 +0,0 @@ -package info.nightscout.androidaps.complications; - -public enum ComplicationAction { - NONE, - MENU, - WIZARD, - BOLUS, - ECARB, - STATUS, - WARNING_SYNC, - WARNING_OLD -} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt new file mode 100644 index 0000000000..5ad6c80ee7 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationAction.kt @@ -0,0 +1,5 @@ +package info.nightscout.androidaps.complications + +enum class ComplicationAction { + NONE, MENU, WIZARD, BOLUS, E_CARB, STATUS, WARNING_SYNC, WARNING_OLD +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java deleted file mode 100644 index 158ad0f3e1..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.java +++ /dev/null @@ -1,179 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.support.wearable.complications.ProviderUpdateRequester; -import android.util.Log; -import android.widget.Toast; - -import androidx.annotation.StringRes; - -import javax.inject.Inject; - -import dagger.android.DaggerBroadcastReceiver; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.actions.TreatmentActivity; -import info.nightscout.androidaps.interaction.actions.ECarbActivity; -import info.nightscout.androidaps.interaction.actions.WizardActivity; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -import info.nightscout.androidaps.interaction.menus.StatusMenuActivity; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.androidaps.interaction.utils.WearUtil; -import info.nightscout.shared.sharedPreferences.SP; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class ComplicationTapBroadcastReceiver extends DaggerBroadcastReceiver { - - @Inject WearUtil wearUtil; - @Inject DisplayFormat displayFormat; - @Inject SP sp; - - private static final String TAG = ComplicationTapBroadcastReceiver.class.getSimpleName(); - - private static final String EXTRA_PROVIDER_COMPONENT = - "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT"; - private static final String EXTRA_COMPLICATION_ID = - "info.nightscout.androidaps.complications.action.COMPLICATION_ID"; - private static final String EXTRA_COMPLICATION_ACTION = - "info.nightscout.androidaps.complications.action.COMPLICATION_ACTION"; - private static final String EXTRA_COMPLICATION_SINCE = - "info.nightscout.androidaps.complications.action.COMPLICATION_SINCE"; - - @Override - public void onReceive(Context context, Intent intent) { - super.onReceive(context, intent); - Bundle extras = intent.getExtras(); - ComponentName provider = extras.getParcelable(EXTRA_PROVIDER_COMPONENT); - int complicationId = extras.getInt(EXTRA_COMPLICATION_ID); - String complicationAction = extras.getString(EXTRA_COMPLICATION_ACTION, ComplicationAction.MENU.toString()); - - ComplicationAction action = ComplicationAction.MENU; - try { - action = ComplicationAction.valueOf(ComplicationAction.class, complicationAction); - } catch (IllegalArgumentException | NullPointerException ex) { - // but how? - Log.e(TAG, "Cannot interpret complication action: " + complicationAction); - } - - action = remapActionWithUserPreferences(action); - - // Request an update for the complication that has just been tapped. - ProviderUpdateRequester requester = new ProviderUpdateRequester(context, provider); - requester.requestUpdate(complicationId); - - Intent intentOpen = null; - - switch (action) { - case NONE: - // do nothing - return; - case WIZARD: - intentOpen = new Intent(context, WizardActivity.class); - break; - case BOLUS: - intentOpen = new Intent(context, TreatmentActivity.class); - break; - case ECARB: - intentOpen = new Intent(context, ECarbActivity.class); - break; - case STATUS: - intentOpen = new Intent(context, StatusMenuActivity.class); - break; - case WARNING_OLD: - case WARNING_SYNC: - long oneAndHalfMinuteAgo = - wearUtil.timestamp() - (Constants.MINUTE_IN_MS + Constants.SECOND_IN_MS * 30); - long since = extras.getLong(EXTRA_COMPLICATION_SINCE, oneAndHalfMinuteAgo); - @StringRes int labelId = (action == ComplicationAction.WARNING_SYNC) ? - R.string.msg_warning_sync : R.string.msg_warning_old; - String msg = String.format(context.getString(labelId), displayFormat.shortTimeSince(since)); - Toast.makeText(context, msg, Toast.LENGTH_LONG).show(); - break; - case MENU: - default: - intentOpen = new Intent(context, MainMenuActivity.class); - } - - if (intentOpen != null) { - // Perform intent - open dialog - intentOpen.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - context.startActivity(intentOpen); - } - } - - private String getComplicationTapAction() { - return sp.getString("complication_tap_action", "default"); - } - - private ComplicationAction remapActionWithUserPreferences(ComplicationAction originalAction) { - final String userPrefAction = getComplicationTapAction(); - switch (originalAction) { - case WARNING_OLD: - case WARNING_SYNC: - // warnings cannot be reconfigured by user - return originalAction; - default: - switch (userPrefAction) { - case "menu": - return ComplicationAction.MENU; - case "wizard": - return ComplicationAction.WIZARD; - case "bolus": - return ComplicationAction.BOLUS; - case "ecarb": - return ComplicationAction.ECARB; - case "status": - return ComplicationAction.STATUS; - case "none": - return ComplicationAction.NONE; - case "default": - default: - return originalAction; - } - } - } - - /** - * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be - * toggled and updated. - */ - static PendingIntent getTapActionIntent( - Context context, ComponentName provider, int complicationId, ComplicationAction action) { - Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class); - intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider); - intent.putExtra(EXTRA_COMPLICATION_ID, complicationId); - intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString()); - - - // Pass complicationId as the requestCode to ensure that different complications get - // different intents. - return PendingIntent.getBroadcast( - context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); - } - - /** - * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be - * toggled and updated. - */ - static PendingIntent getTapWarningSinceIntent( - Context context, ComponentName provider, int complicationId, ComplicationAction action, long since) { - Intent intent = new Intent(context, ComplicationTapBroadcastReceiver.class); - intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider); - intent.putExtra(EXTRA_COMPLICATION_ID, complicationId); - intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString()); - intent.putExtra(EXTRA_COMPLICATION_SINCE, since); - - - // Pass complicationId as the requestCode to ensure that different complications get - // different intents. - return PendingIntent.getBroadcast( - context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt new file mode 100644 index 0000000000..f8452ec35d --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/ComplicationTapBroadcastReceiver.kt @@ -0,0 +1,150 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.content.ComponentName +import android.content.Context +import android.content.Intent +import android.support.wearable.complications.ProviderUpdateRequester +import android.widget.Toast +import androidx.annotation.StringRes +import dagger.android.DaggerBroadcastReceiver +import info.nightscout.androidaps.R +import info.nightscout.androidaps.interaction.actions.ECarbActivity +import info.nightscout.androidaps.interaction.actions.TreatmentActivity +import info.nightscout.androidaps.interaction.actions.WizardActivity +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.androidaps.interaction.menus.StatusMenuActivity +import info.nightscout.androidaps.interaction.utils.Constants +import info.nightscout.androidaps.interaction.utils.DisplayFormat +import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import javax.inject.Inject + +/* + * Created by dlvoy on 2019-11-12 + */ +class ComplicationTapBroadcastReceiver : DaggerBroadcastReceiver() { + + @Inject lateinit var wearUtil: WearUtil + @Inject lateinit var displayFormat: DisplayFormat + @Inject lateinit var sp: SP + @Inject lateinit var aapsLogger: AAPSLogger + + override fun onReceive(context: Context, intent: Intent) { + super.onReceive(context, intent) + val extras = intent.extras + val provider = extras!!.getParcelable(EXTRA_PROVIDER_COMPONENT) + val complicationId = extras.getInt(EXTRA_COMPLICATION_ID) + val complicationAction = extras.getString(EXTRA_COMPLICATION_ACTION, ComplicationAction.MENU.toString()) + var action = ComplicationAction.MENU + try { + action = ComplicationAction.valueOf(complicationAction) + } catch (ex: IllegalArgumentException) { + // but how? + aapsLogger.error(LTag.WEAR, "Cannot interpret complication action: $complicationAction") + } catch (ex: NullPointerException) { + aapsLogger.error(LTag.WEAR, "Cannot interpret complication action: $complicationAction") + } + action = remapActionWithUserPreferences(action) + + // Request an update for the complication that has just been tapped. + val requester = ProviderUpdateRequester(context, provider) + requester.requestUpdate(complicationId) + var intentOpen: Intent? = null + when (action) { + ComplicationAction.NONE -> // do nothing + return + ComplicationAction.WIZARD -> intentOpen = Intent(context, WizardActivity::class.java) + ComplicationAction.BOLUS -> intentOpen = Intent(context, TreatmentActivity::class.java) + ComplicationAction.E_CARB -> intentOpen = Intent(context, ECarbActivity::class.java) + ComplicationAction.STATUS -> intentOpen = Intent(context, StatusMenuActivity::class.java) + + ComplicationAction.WARNING_OLD, ComplicationAction.WARNING_SYNC -> { + val oneAndHalfMinuteAgo = wearUtil.timestamp() - (Constants.MINUTE_IN_MS + Constants.SECOND_IN_MS * 30) + val since = extras.getLong(EXTRA_COMPLICATION_SINCE, oneAndHalfMinuteAgo) + @StringRes val labelId = if (action == ComplicationAction.WARNING_SYNC) R.string.msg_warning_sync else R.string.msg_warning_old + val msg = String.format(context.getString(labelId), displayFormat.shortTimeSince(since)) + Toast.makeText(context, msg, Toast.LENGTH_LONG).show() + } + + ComplicationAction.MENU -> intentOpen = Intent(context, MainMenuActivity::class.java) + } + if (intentOpen != null) { + // Perform intent - open dialog + intentOpen.flags = Intent.FLAG_ACTIVITY_NEW_TASK + context.startActivity(intentOpen) + } + } + + private val complicationTapAction: String + get() = sp.getString("complication_tap_action", "default") + + private fun remapActionWithUserPreferences(originalAction: ComplicationAction): ComplicationAction { + val userPrefAction = complicationTapAction + return when (originalAction) { + ComplicationAction.WARNING_OLD, ComplicationAction.WARNING_SYNC -> // warnings cannot be reconfigured by user + originalAction + else -> when (userPrefAction) { + "menu" -> ComplicationAction.MENU + "wizard" -> ComplicationAction.WIZARD + "bolus" -> ComplicationAction.BOLUS + "ecarb" -> ComplicationAction.E_CARB + "status" -> ComplicationAction.STATUS + "none" -> ComplicationAction.NONE + "default" -> originalAction + else -> originalAction + } + } + } + + companion object { + + private const val EXTRA_PROVIDER_COMPONENT = "info.nightscout.androidaps.complications.action.PROVIDER_COMPONENT" + private const val EXTRA_COMPLICATION_ID = "info.nightscout.androidaps.complications.action.COMPLICATION_ID" + private const val EXTRA_COMPLICATION_ACTION = "info.nightscout.androidaps.complications.action.COMPLICATION_ACTION" + private const val EXTRA_COMPLICATION_SINCE = "info.nightscout.androidaps.complications.action.COMPLICATION_SINCE" + + /** + * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be + * toggled and updated. + */ + fun getTapActionIntent( + context: Context, provider: ComponentName?, complicationId: Int, action: ComplicationAction + ): PendingIntent { + val intent = Intent(context, ComplicationTapBroadcastReceiver::class.java) + intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider) + intent.putExtra(EXTRA_COMPLICATION_ID, complicationId) + intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString()) + + // Pass complicationId as the requestCode to ensure that different complications get + // different intents. + return PendingIntent.getBroadcast( + context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + } + + /** + * Returns a pending intent, suitable for use as a tap intent, that causes a complication to be + * toggled and updated. + */ + fun getTapWarningSinceIntent( + context: Context?, provider: ComponentName?, complicationId: Int, action: ComplicationAction, since: Long + ): PendingIntent { + val intent = Intent(context, ComplicationTapBroadcastReceiver::class.java) + intent.putExtra(EXTRA_PROVIDER_COMPONENT, provider) + intent.putExtra(EXTRA_COMPLICATION_ID, complicationId) + intent.putExtra(EXTRA_COMPLICATION_ACTION, action.toString()) + intent.putExtra(EXTRA_COMPLICATION_SINCE, since) + + // Pass complicationId as the requestCode to ensure that different complications get + // different intents. + return PendingIntent.getBroadcast( + context, complicationId, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT + ) + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java deleted file mode 100644 index 55b6f7168c..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.java +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.Pair; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class IobDetailedComplication extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - - Pair iob = displayFormat.detailedIob(raw); - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(iob.first)) - .setTapAction(complicationPendingIntent); - - if (iob.second.length() > 0) { - builder.setShortTitle(ComplicationText.plainText(iob.second)); - } - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return IobDetailedComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.BOLUS; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt new file mode 100644 index 0000000000..bebb6887a1 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobDetailedComplication.kt @@ -0,0 +1,35 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class IobDetailedComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val iob = displayFormat.detailedIob(raw) + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(iob.first)) + .setTapAction(complicationPendingIntent) + if (iob.second.isNotEmpty()) { + builder.setShortTitle(ComplicationText.plainText(iob.second)) + } + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = IobDetailedComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java deleted file mode 100644 index ce76524fb9..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.java +++ /dev/null @@ -1,50 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.graphics.drawable.Icon; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.SmallestDoubleString; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class IobIconComplication extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - final String iob = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT); - - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(iob)) - .setIcon(Icon.createWithResource( - this, R.drawable.ic_ins)) - .setBurnInProtectionIcon( - Icon.createWithResource( - this, R.drawable.ic_ins_burnin)) - .setTapAction(complicationPendingIntent); - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return IobIconComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.BOLUS; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt new file mode 100644 index 0000000000..7befcd9858 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/IobIconComplication.kt @@ -0,0 +1,37 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.graphics.drawable.Icon +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.interaction.utils.SmallestDoubleString +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class IobIconComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_SHORT_TEXT) { + val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(displayFormat.MAX_FIELD_LEN_SHORT) + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(iob)) + .setIcon(Icon.createWithResource(this, R.drawable.ic_ins)) + .setBurnInProtectionIcon(Icon.createWithResource(this, R.drawable.ic_ins_burnin)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = IobIconComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.BOLUS +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java deleted file mode 100644 index ad03acfab4..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.java +++ /dev/null @@ -1,60 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class LongStatusComplication extends BaseComplicationProviderService { - - @Inject DisplayFormat displayFormat; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - switch (dataType) { - case ComplicationData.TYPE_LONG_TEXT: - - final String glucoseLine = displayFormat.longGlucoseLine(raw); - final String detailsLine = displayFormat.longDetailsLine(raw); - - final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) - .setLongTitle(ComplicationText.plainText(glucoseLine)) - .setLongText(ComplicationText.plainText(detailsLine)) - .setTapAction(complicationPendingIntent); - complicationData = builderLong.build(); - - break; - default: - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return LongStatusComplication.class.getCanonicalName(); - } - - @Override - protected boolean usesSinceField() { - return true; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt new file mode 100644 index 0000000000..08832c50c2 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusComplication.kt @@ -0,0 +1,43 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import dagger.android.AndroidInjection +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class LongStatusComplication : BaseComplicationProviderService() { + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + when (dataType) { + ComplicationData.TYPE_LONG_TEXT -> { + val glucoseLine = displayFormat.longGlucoseLine(raw) + val detailsLine = displayFormat.longDetailsLine(raw) + val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) + .setLongTitle(ComplicationText.plainText(glucoseLine)) + .setLongText(ComplicationText.plainText(detailsLine)) + .setTapAction(complicationPendingIntent) + complicationData = builderLong.build() + } + + else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = LongStatusComplication::class.java.canonicalName!! + override fun usesSinceField(): Boolean = true +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java deleted file mode 100644 index c66c994d69..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.java +++ /dev/null @@ -1,60 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class LongStatusFlippedComplication extends BaseComplicationProviderService { - - @Inject DisplayFormat displayFormat; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - switch (dataType) { - case ComplicationData.TYPE_LONG_TEXT: - - final String glucoseLine = displayFormat.longGlucoseLine(raw); - final String detailsLine = displayFormat.longDetailsLine(raw); - - final ComplicationData.Builder builderLong = new ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) - .setLongTitle(ComplicationText.plainText(detailsLine)) - .setLongText(ComplicationText.plainText(glucoseLine)) - .setTapAction(complicationPendingIntent); - complicationData = builderLong.build(); - - break; - default: - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return LongStatusFlippedComplication.class.getCanonicalName(); - } - - @Override - protected boolean usesSinceField() { - return true; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt new file mode 100644 index 0000000000..f6bf913871 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/LongStatusFlippedComplication.kt @@ -0,0 +1,43 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import dagger.android.AndroidInjection +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class LongStatusFlippedComplication : BaseComplicationProviderService() { + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + when (dataType) { + ComplicationData.TYPE_LONG_TEXT -> { + val glucoseLine = displayFormat.longGlucoseLine(raw) + val detailsLine = displayFormat.longDetailsLine(raw) + val builderLong = ComplicationData.Builder(ComplicationData.TYPE_LONG_TEXT) + .setLongTitle(ComplicationText.plainText(detailsLine)) + .setLongText(ComplicationText.plainText(glucoseLine)) + .setTapAction(complicationPendingIntent) + complicationData = builderLong.build() + } + + else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = LongStatusFlippedComplication::class.java.canonicalName!! + override fun usesSinceField(): Boolean = true +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java deleted file mode 100644 index d09a58a7ea..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.java +++ /dev/null @@ -1,56 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.DisplayFormat; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class SgvComplication extends BaseComplicationProviderService { - - @Inject DisplayFormat displayFormat; - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - switch (dataType) { - case ComplicationData.TYPE_SHORT_TEXT: - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(raw.sSgv + raw.sDirection + "\uFE0E")) - .setShortTitle(ComplicationText.plainText(displayFormat.shortTrend(raw))) - .setTapAction(complicationPendingIntent); - - complicationData = builder.build(); - break; - default: - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return SgvComplication.class.getCanonicalName(); - } - - @Override - protected boolean usesSinceField() { - return true; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt new file mode 100644 index 0000000000..b692eeb17d --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/SgvComplication.kt @@ -0,0 +1,41 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import dagger.android.AndroidInjection +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag + +/* + * Created by dlvoy on 2019-11-12 + */ +class SgvComplication : BaseComplicationProviderService() { + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + when (dataType) { + ComplicationData.TYPE_SHORT_TEXT -> { + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(raw.singleBg.sgvString + raw.singleBg.slopeArrow + "\uFE0E")) + .setShortTitle(ComplicationText.plainText(displayFormat.shortTrend(raw))) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } + + else -> aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } + + override fun getProviderCanonicalName(): String = SgvComplication::class.java.canonicalName!! + override fun usesSinceField(): Boolean = true +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java deleted file mode 100644 index 10f214ee33..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBattery.java +++ /dev/null @@ -1,157 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.graphics.drawable.Icon; -import android.support.wearable.complications.ComplicationData; -import android.support.wearable.complications.ComplicationText; - -import androidx.annotation.DrawableRes; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class UploaderBattery extends BaseComplicationProviderService { - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - @DrawableRes int batteryIcon = R.drawable.ic_battery_unknown; - @DrawableRes int burnInBatteryIcon = R.drawable.ic_battery_unknown_burnin; - int level = 0; - String levelStr = "???"; - - if (raw.sUploaderBattery.matches("^[0-9]+$")) { - try { - level = Integer.parseInt(raw.sUploaderBattery); - level = Math.max(Math.min(level, 100), 0); - levelStr = level + "%"; - int iconNo = (int) Math.floor(level / 10.0); - if (level > 95) { - iconNo = 10; - } - switch (iconNo) { - case 10: - batteryIcon = R.drawable.ic_battery_charging_wireless; - break; - case 9: - batteryIcon = R.drawable.ic_battery_charging_wireless_90; - break; - case 8: - batteryIcon = R.drawable.ic_battery_charging_wireless_80; - break; - case 7: - batteryIcon = R.drawable.ic_battery_charging_wireless_70; - break; - case 6: - batteryIcon = R.drawable.ic_battery_charging_wireless_60; - break; - case 5: - batteryIcon = R.drawable.ic_battery_charging_wireless_50; - break; - case 4: - batteryIcon = R.drawable.ic_battery_charging_wireless_40; - break; - case 3: - batteryIcon = R.drawable.ic_battery_charging_wireless_30; - break; - case 2: - batteryIcon = R.drawable.ic_battery_charging_wireless_20; - break; - case 1: - batteryIcon = R.drawable.ic_battery_charging_wireless_10; - break; - case 0: - batteryIcon = R.drawable.ic_battery_alert_variant_outline; - break; - default: - batteryIcon = R.drawable.ic_battery_charging_wireless_outline; - } - - switch (iconNo) { - case 10: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_burnin; - break; - case 9: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_90_burnin; - break; - case 8: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_80_burnin; - break; - case 7: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_70_burnin; - break; - case 6: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_60_burnin; - break; - case 5: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_50_burnin; - break; - case 4: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_40_burnin; - break; - case 3: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_30_burnin; - break; - case 2: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_20_burnin; - break; - case 1: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_10_burnin; - break; - case 0: - burnInBatteryIcon = R.drawable.ic_battery_alert_variant_outline; - break; - default: - burnInBatteryIcon = R.drawable.ic_battery_charging_wireless_outline; - } - - - } catch (NumberFormatException ex) { - aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.sUploaderBattery); - } - } - - if (dataType == ComplicationData.TYPE_RANGED_VALUE) { - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE) - .setMinValue(0) - .setMaxValue(100) - .setValue(level) - .setShortText(ComplicationText.plainText(levelStr)) - .setIcon(Icon.createWithResource(this, batteryIcon)) - .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) - .setTapAction(complicationPendingIntent); - complicationData = builder.build(); - } else if (dataType == ComplicationData.TYPE_SHORT_TEXT) { - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) - .setShortText(ComplicationText.plainText(levelStr)) - .setIcon(Icon.createWithResource(this, batteryIcon)) - .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) - .setTapAction(complicationPendingIntent); - complicationData = builder.build(); - } else if (dataType == ComplicationData.TYPE_ICON) { - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_ICON) - .setIcon(Icon.createWithResource(this, batteryIcon)) - .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) - .setTapAction(complicationPendingIntent); - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } - - @Override - public String getProviderCanonicalName() { - return UploaderBattery.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.STATUS; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt new file mode 100644 index 0000000000..6260b8d804 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/UploaderBatteryComplication.kt @@ -0,0 +1,108 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.graphics.drawable.Icon +import android.support.wearable.complications.ComplicationData +import android.support.wearable.complications.ComplicationText +import androidx.annotation.DrawableRes +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag +import kotlin.math.floor +import kotlin.math.max +import kotlin.math.min + +/* + * Created by dlvoy on 2019-11-12 + */ +class UploaderBatteryComplication : BaseComplicationProviderService() { + + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + @DrawableRes var batteryIcon = R.drawable.ic_battery_unknown + @DrawableRes var burnInBatteryIcon = R.drawable.ic_battery_unknown_burnin + var level = 0 + var levelStr = "???" + if (raw.status.battery.matches(Regex("^[0-9]+$"))) { + try { + level = raw.status.battery.toInt() + level = max(min(level, 100), 0) + levelStr = "$level%" + var iconNo = floor(level / 10.0).toInt() + if (level > 95) { + iconNo = 10 + } + batteryIcon = when (iconNo) { + 10 -> R.drawable.ic_battery_charging_wireless + 9 -> R.drawable.ic_battery_charging_wireless_90 + 8 -> R.drawable.ic_battery_charging_wireless_80 + 7 -> R.drawable.ic_battery_charging_wireless_70 + 6 -> R.drawable.ic_battery_charging_wireless_60 + 5 -> R.drawable.ic_battery_charging_wireless_50 + 4 -> R.drawable.ic_battery_charging_wireless_40 + 3 -> R.drawable.ic_battery_charging_wireless_30 + 2 -> R.drawable.ic_battery_charging_wireless_20 + 1 -> R.drawable.ic_battery_charging_wireless_10 + 0 -> R.drawable.ic_battery_alert_variant_outline + else -> R.drawable.ic_battery_charging_wireless_outline + } + burnInBatteryIcon = when (iconNo) { + 10 -> R.drawable.ic_battery_charging_wireless_burnin + 9 -> R.drawable.ic_battery_charging_wireless_90_burnin + 8 -> R.drawable.ic_battery_charging_wireless_80_burnin + 7 -> R.drawable.ic_battery_charging_wireless_70_burnin + 6 -> R.drawable.ic_battery_charging_wireless_60_burnin + 5 -> R.drawable.ic_battery_charging_wireless_50_burnin + 4 -> R.drawable.ic_battery_charging_wireless_40_burnin + 3 -> R.drawable.ic_battery_charging_wireless_30_burnin + 2 -> R.drawable.ic_battery_charging_wireless_20_burnin + 1 -> R.drawable.ic_battery_charging_wireless_10_burnin + 0 -> R.drawable.ic_battery_alert_variant_outline + else -> R.drawable.ic_battery_charging_wireless_outline + } + } catch (ex: NumberFormatException) { + aapsLogger.error(LTag.WEAR, "Cannot parse battery level of: " + raw.status.battery) + } + } + when (dataType) { + ComplicationData.TYPE_RANGED_VALUE -> { + val builder = ComplicationData.Builder(ComplicationData.TYPE_RANGED_VALUE) + .setMinValue(0f) + .setMaxValue(100f) + .setValue(level.toFloat()) + .setShortText(ComplicationText.plainText(levelStr)) + .setIcon(Icon.createWithResource(this, batteryIcon)) + .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } + + ComplicationData.TYPE_SHORT_TEXT -> { + val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT) + .setShortText(ComplicationText.plainText(levelStr)) + .setIcon(Icon.createWithResource(this, batteryIcon)) + .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } + + ComplicationData.TYPE_ICON -> { + val builder = ComplicationData.Builder(ComplicationData.TYPE_ICON) + .setIcon(Icon.createWithResource(this, batteryIcon)) + .setBurnInProtectionIcon(Icon.createWithResource(this, burnInBatteryIcon)) + .setTapAction(complicationPendingIntent) + complicationData = builder.build() + } + + else -> { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + } + return complicationData + } + + override fun getProviderCanonicalName(): String = UploaderBatteryComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.STATUS +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java deleted file mode 100644 index dfceeb4a03..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.java +++ /dev/null @@ -1,56 +0,0 @@ -package info.nightscout.androidaps.complications; - -import android.app.PendingIntent; -import android.content.Context; -import android.content.res.AssetManager; -import android.graphics.Bitmap; -import android.graphics.BitmapFactory; -import android.graphics.drawable.Icon; -import android.support.wearable.complications.ComplicationData; -import android.util.DisplayMetrics; -import android.view.WindowManager; - -import java.io.IOException; -import java.io.InputStream; - -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.shared.logging.LTag; - -/* - * Created by dlvoy on 2019-11-12 - */ -public abstract class WallpaperComplication extends BaseComplicationProviderService { - - public abstract String getWallpaperAssetsFileName(); - - public ComplicationData buildComplicationData(int dataType, RawDisplayData raw, PendingIntent complicationPendingIntent) { - - ComplicationData complicationData = null; - - if (dataType == ComplicationData.TYPE_LARGE_IMAGE) { - - DisplayMetrics metrics = new DisplayMetrics(); - WindowManager windowManager = (WindowManager) getApplicationContext() - .getSystemService(Context.WINDOW_SERVICE); - windowManager.getDefaultDisplay().getMetrics(metrics); - int width = metrics.widthPixels; - int height = metrics.heightPixels; - - final ComplicationData.Builder builder = new ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE); - - AssetManager assetManager = getAssets(); - try (InputStream iStr = assetManager.open(getWallpaperAssetsFileName())) { - Bitmap bitmap = BitmapFactory.decodeStream(iStr); - Bitmap scaled = Bitmap.createScaledBitmap(bitmap, width, height, true); - builder.setLargeImage(Icon.createWithBitmap(scaled)); - } catch (IOException e) { - aapsLogger.error(LTag.WEAR, "Cannot read wallpaper asset: " + e.getMessage(), e); - } - - complicationData = builder.build(); - } else { - aapsLogger.warn(LTag.WEAR, "Unexpected complication type " + dataType); - } - return complicationData; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt new file mode 100644 index 0000000000..d9bb821a00 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperComplication.kt @@ -0,0 +1,47 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.complications + +import android.app.PendingIntent +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.graphics.drawable.Icon +import android.support.wearable.complications.ComplicationData +import android.util.DisplayMetrics +import android.view.WindowManager +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.shared.logging.LTag +import java.io.IOException + +/* + * Created by dlvoy on 2019-11-12 + */ +abstract class WallpaperComplication : BaseComplicationProviderService() { + + abstract val wallpaperAssetsFileName: String + override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? { + var complicationData: ComplicationData? = null + if (dataType == ComplicationData.TYPE_LARGE_IMAGE) { + val metrics = DisplayMetrics() + val windowManager = applicationContext.getSystemService(WINDOW_SERVICE) as WindowManager + windowManager.defaultDisplay.getMetrics(metrics) + val width = metrics.widthPixels + val height = metrics.heightPixels + val builder = ComplicationData.Builder(ComplicationData.TYPE_LARGE_IMAGE) + val assetManager = assets + try { + assetManager.open(wallpaperAssetsFileName).use { iStr -> + val bitmap = BitmapFactory.decodeStream(iStr) + val scaled = Bitmap.createScaledBitmap(bitmap, width, height, true) + builder.setLargeImage(Icon.createWithBitmap(scaled)) + } + } catch (e: IOException) { + aapsLogger.error(LTag.WEAR, "Cannot read wallpaper asset: " + e.message, e) + } + complicationData = builder.build() + } else { + aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType") + } + return complicationData + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java deleted file mode 100644 index a45beb8a1e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.complications; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class WallpaperDarkComplication extends WallpaperComplication { - - @Override - public String getWallpaperAssetsFileName() { - return "watch_dark.jpg"; - } - - @Override - public String getProviderCanonicalName() { - return WallpaperDarkComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.NONE; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt new file mode 100644 index 0000000000..ccc6159694 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperDarkComplication.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.complications + +/* + * Created by dlvoy on 2019-11-12 + */ +class WallpaperDarkComplication : WallpaperComplication() { + + override val wallpaperAssetsFileName: String = "watch_dark.jpg" + override fun getProviderCanonicalName(): String = WallpaperDarkComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java deleted file mode 100644 index 5c06550ef2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.complications; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class WallpaperGrayComplication extends WallpaperComplication { - - @Override - public String getWallpaperAssetsFileName() { - return "watch_gray.jpg"; - } - - @Override - public String getProviderCanonicalName() { - return WallpaperGrayComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.NONE; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt new file mode 100644 index 0000000000..ff2028d01b --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperGrayComplication.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.complications + +/* + * Created by dlvoy on 2019-11-12 + */ +class WallpaperGrayComplication : WallpaperComplication() { + + override val wallpaperAssetsFileName: String = "watch_gray.jpg" + override fun getProviderCanonicalName(): String = WallpaperGrayComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java deleted file mode 100644 index 04bdf5fd95..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.java +++ /dev/null @@ -1,22 +0,0 @@ -package info.nightscout.androidaps.complications; - -/* - * Created by dlvoy on 2019-11-12 - */ -public class WallpaperLightComplication extends WallpaperComplication { - - @Override - public String getWallpaperAssetsFileName() { - return "watch_light.jpg"; - } - - @Override - public String getProviderCanonicalName() { - return WallpaperLightComplication.class.getCanonicalName(); - } - - @Override - public ComplicationAction getComplicationAction() { - return ComplicationAction.NONE; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt new file mode 100644 index 0000000000..9ac71e953a --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/complications/WallpaperLightComplication.kt @@ -0,0 +1,11 @@ +package info.nightscout.androidaps.complications + +/* + * Created by dlvoy on 2019-11-12 + */ +class WallpaperLightComplication : WallpaperComplication() { + + override val wallpaperAssetsFileName: String = "watch_light.jpg" + override fun getProviderCanonicalName(): String = WallpaperLightComplication::class.java.canonicalName!! + override fun getComplicationAction(): ComplicationAction = ComplicationAction.NONE +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java deleted file mode 100644 index ebed526ec8..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/BasalWatchData.java +++ /dev/null @@ -1,11 +0,0 @@ -package info.nightscout.androidaps.data; - -/** - * Created by adrian on 18/11/16. - */ - -public class BasalWatchData { - public long startTime; - public long endTime; - public double amount; -} diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java deleted file mode 100644 index 4f258ee074..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/BgWatchData.java +++ /dev/null @@ -1,49 +0,0 @@ -package info.nightscout.androidaps.data; - -import java.util.Objects; - -/** - * Created by emmablack on 1/7/15. - */ -public class BgWatchData implements Comparable{ - public double sgv; - public double high; - public double low; - public long timestamp; - public int color; - - public BgWatchData(double aSgv, double aHigh, double aLow, long aTimestamp, int aColor) { - this.sgv = aSgv; - this.high = aHigh; - this.low = aLow; - this.timestamp = aTimestamp; - this.color = aColor; - } - - public BgWatchData(){ - - } - - @Override - public boolean equals(Object that){ - if(! (that instanceof BgWatchData)){ - return false; - } - if (this.color != ((BgWatchData) that).color) - return false; - return this.timestamp == ((BgWatchData) that).timestamp; - } - - @Override - public int hashCode() { - return Objects.hash(timestamp, color); - } - - @Override - public int compareTo(BgWatchData that) { - // reverse order endTime get latest first - if(this.timestamp < that.timestamp) return 1; - if(this.timestamp > that.timestamp) return -1; - return 0; - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java deleted file mode 100644 index 6a474f3632..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/BolusWatchData.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.data; - -/** - * Created by adrian on 17/11/16. - */ - -public class BolusWatchData { - public long date; - public double bolus; - public double carbs; - public boolean isSMB; - public boolean isValid; -} diff --git a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java b/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java deleted file mode 100644 index 47a3aa0a60..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/ListenerService.java +++ /dev/null @@ -1,628 +0,0 @@ -package info.nightscout.androidaps.data; - -import android.annotation.TargetApi; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.Context; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.AsyncTask; -import android.os.Build; -import android.os.Bundle; -import android.os.SystemClock; -import android.preference.PreferenceManager; -import android.util.Base64; -import android.util.Log; - -import androidx.core.app.NotificationCompat; -import androidx.core.app.NotificationManagerCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import androidx.wear.tiles.TileService; - -import com.google.android.gms.common.ConnectionResult; -import com.google.android.gms.common.api.GoogleApiClient; -import com.google.android.gms.wearable.ChannelApi; -import com.google.android.gms.wearable.DataEvent; -import com.google.android.gms.wearable.DataEventBuffer; -import com.google.android.gms.wearable.DataMap; -import com.google.android.gms.wearable.DataMapItem; -import com.google.android.gms.wearable.Node; -import com.google.android.gms.wearable.NodeApi; -import com.google.android.gms.wearable.Wearable; -import com.google.android.gms.wearable.WearableListenerService; - -import org.jetbrains.annotations.NotNull; - -import java.util.concurrent.TimeUnit; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.AAPSPreferences; -import info.nightscout.androidaps.interaction.actions.AcceptActivity; -import info.nightscout.androidaps.interaction.actions.CPPActivity; -import info.nightscout.androidaps.interaction.utils.Persistence; -import info.nightscout.androidaps.interaction.utils.WearUtil; -import info.nightscout.androidaps.tile.ActionsTileService; -import info.nightscout.androidaps.tile.QuickWizardTileService; -import info.nightscout.androidaps.tile.TempTargetTileService; -import info.nightscout.shared.SafeParse; -import info.nightscout.shared.weardata.WearUris; - -/** - * Created by emmablack on 12/26/14. - */ -public class ListenerService extends WearableListenerService implements GoogleApiClient.ConnectionCallbacks, - GoogleApiClient.OnConnectionFailedListener, ChannelApi.ChannelListener { - - @Inject WearUtil wearUtil; - @Inject Persistence persistence; - - public static final int BOLUS_PROGRESS_NOTIF_ID = 1; - public static final int CONFIRM_NOTIF_ID = 2; - public static final int CHANGE_NOTIF_ID = 556677; - - private static final String ACTION_RESEND = "com.dexdrip.stephenblack.nightwatch.RESEND_DATA"; - private static final String ACTION_CANCELBOLUS = "com.dexdrip.stephenblack.nightwatch.CANCELBOLUS"; - private static final String ACTION_CONFIRMATION = "com.dexdrip.stephenblack.nightwatch.CONFIRMACTION"; - private static final String ACTION_CONFIRMCHANGE = "com.dexdrip.stephenblack.nightwatch.CONFIRMCHANGE"; - private static final String ACTION_INITIATE_ACTION = "com.dexdrip.stephenblack.nightwatch.INITIATE_ACTION"; - - private static final String AAPS_NOTIFY_CHANNEL_ID_OPENLOOP = "AndroidAPS-OpenLoop"; - private static final String AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS = "bolus progress vibration"; - private static final String AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT = "bolus progress silent"; - - GoogleApiClient googleApiClient; - - private DismissThread bolusprogressThread; - private static final String TAG = "ListenerService"; - - private final String logPrefix = ""; // "WR: " - - // Not derived from DaggerService, do injection here - @Override - public void onCreate() { - AndroidInjection.inject(this); - super.onCreate(); - } - - public class BolusCancelTask extends AsyncTask { - Context mContext; - - BolusCancelTask(Context context) { - mContext = context; - } - - @Override - protected Void doInBackground(Void... params) { - Log.d(TAG, logPrefix + "BolusCancelTask.doInBackground: " + params); - if (!googleApiClient.isConnected()) { - Log.i(TAG, "BolusCancelTask.doInBackground: not connected"); - googleApiClient.blockingConnect(15, TimeUnit.SECONDS); - } - if (googleApiClient.isConnected()) { - NodeApi.GetConnectedNodesResult nodes = - Wearable.NodeApi.getConnectedNodes(googleApiClient).await(); - for (Node node : nodes.getNodes()) { - Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), - WearUris.WEARABLE_CANCELBOLUS_PATH, null); - } - - } - return null; - } - } - - public class MessageActionTask extends AsyncTask { - Context mContext; - String mActionstring; - String mMessagePath; - - MessageActionTask(Context context, String messagePath, String actionstring) { - mContext = context; - mActionstring = actionstring; - mMessagePath = messagePath; - } - - @Override - protected Void doInBackground(Void... params) { - Log.i(TAG, "MessageActionTask.doInBackground: "); - - if (!googleApiClient.isConnected()) { - Log.i(TAG, "MessageActionTask.doInBackground: not connected"); - googleApiClient.blockingConnect(15, TimeUnit.SECONDS); - } - if (googleApiClient.isConnected()) { - NodeApi.GetConnectedNodesResult nodes = - Wearable.NodeApi.getConnectedNodes(googleApiClient).await(); - for (Node node : nodes.getNodes()) { - Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), mMessagePath, mActionstring.getBytes()); - } - - } - return null; - } - } - - public class ResendDataTask extends AsyncTask { - Context mContext; - - ResendDataTask(Context context) { - mContext = context; - } - - @Override - protected Void doInBackground(Void... params) { - Log.d(TAG, logPrefix + "ResendDataTask.doInBackground: " + params); - - if (!googleApiClient.isConnected()) { - Log.i(TAG, "ResendDataTask.doInBackground: not connected"); - googleApiClient.blockingConnect(15, TimeUnit.SECONDS); - } - if (googleApiClient.isConnected()) { - Log.i(TAG, "ResendDataTask.doInBackground: connected"); - NodeApi.GetConnectedNodesResult nodes = Wearable.NodeApi.getConnectedNodes(googleApiClient).await(); - for (Node node : nodes.getNodes()) { - Wearable.MessageApi.sendMessage(googleApiClient, node.getId(), WearUris.WEARABLE_RESEND_PATH, null); - } - } else { - Log.i(TAG, "ResendDataTask.doInBackground: could not connect"); - } - return null; - - } - } - - public void requestData() { - new ResendDataTask(this).execute(); - } - - public void cancelBolus() { - new BolusCancelTask(this).execute(); - } - - private void sendConfirmActionstring(String actionstring) { - new MessageActionTask(this, WearUris.WEARABLE_CONFIRM_ACTIONSTRING_PATH, actionstring).execute(); - } - - private void sendInitiateActionstring(String actionstring) { - new MessageActionTask(this, WearUris.WEARABLE_INITIATE_ACTIONSTRING_PATH, actionstring).execute(); - } - - private void googleApiConnect() { - if (googleApiClient != null) { - // Remove old listener(s) - try { - Wearable.ChannelApi.removeListener(googleApiClient, this); - } catch (Exception e) { - // - } - try { - Wearable.MessageApi.removeListener(googleApiClient, this); - } catch (Exception e) { - // - } - } - - googleApiClient = new GoogleApiClient.Builder(this) - .addConnectionCallbacks(this) - .addOnConnectionFailedListener(this) - .addApi(Wearable.API) - .build(); - Wearable.MessageApi.addListener(googleApiClient, this); - } - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - - // Log.d(TAG, logPrefix + "onStartCommand: Intent: " + intent); - - if (intent != null && ACTION_RESEND.equals(intent.getAction())) { - googleApiConnect(); - requestData(); - } else if (intent != null && ACTION_CANCELBOLUS.equals(intent.getAction())) { - googleApiConnect(); - - //dismiss notification - NotificationManagerCompat notificationManager = - NotificationManagerCompat.from(ListenerService.this); - notificationManager.cancel(BOLUS_PROGRESS_NOTIF_ID); - - //send cancel-request to phone. - cancelBolus(); - - - } else if (intent != null && ACTION_CONFIRMATION.equals(intent.getAction())) { - googleApiConnect(); - - //dismiss notification - NotificationManagerCompat notificationManager = - NotificationManagerCompat.from(ListenerService.this); - notificationManager.cancel(CONFIRM_NOTIF_ID); - - String actionstring = intent.getStringExtra("actionstring"); - sendConfirmActionstring(actionstring); - - } else if (intent != null && ACTION_CONFIRMCHANGE.equals(intent.getAction())) { - googleApiConnect(); - - //dismiss notification - NotificationManagerCompat notificationManager = - NotificationManagerCompat.from(ListenerService.this); - notificationManager.cancel(CHANGE_NOTIF_ID); - - String actionstring = intent.getStringExtra("actionstring"); - sendConfirmActionstring(actionstring); - - } else if (intent != null && ACTION_INITIATE_ACTION.equals(intent.getAction())) { - googleApiConnect(); - - String actionstring = intent.getStringExtra("actionstring"); - sendInitiateActionstring(actionstring); - - } - - return START_STICKY; - } - - @Override - public void onDataChanged(DataEventBuffer dataEvents) { - - DataMap dataMap; - // Log.d(TAG, logPrefix + "onDataChanged: DataEvents=" + dataEvents); - - for (DataEvent event : dataEvents) { - - if (event.getType() == DataEvent.TYPE_CHANGED) { - - String path = event.getDataItem().getUri().getPath(); - - //Log.d(TAG, "WR: onDataChanged: Path: " + path + ", EventDataItem=" + event.getDataItem()); - - if (path.equals(WearUris.OPEN_SETTINGS_PATH)) { - Intent intent = new Intent(this, AAPSPreferences.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } else if (path.equals(WearUris.BOLUS_PROGRESS_PATH)) { - int progress = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getInt("progresspercent", 0); - String status = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("progressstatus", ""); - showBolusProgress(progress, status); - } else if (path.equals(WearUris.ACTION_CONFIRMATION_REQUEST_PATH)) { - String title = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("title"); - String message = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("message"); - String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring"); - - if ("opencpp".equals(title) && actionstring.startsWith("opencpp")) { - String[] act = actionstring.split("\\s+"); - Intent intent = new Intent(this, CPPActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - //TODO adrian: parse actionstring and add parameters - Bundle params = new Bundle(); - params.putInt("percentage", SafeParse.stringToInt(act[1])); - params.putInt("timeshift", SafeParse.stringToInt(act[2])); - intent.putExtras(params); - startActivity(intent); - } else { - showConfirmationDialog(title, message, actionstring); - } - - } else if (path.equals(WearUris.NEW_STATUS_PATH)) { - dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); - Intent messageIntent = new Intent(); - messageIntent.setAction(Intent.ACTION_SEND); - messageIntent.putExtra("status", dataMap.toBundle()); - persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMap); - LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent); - } else if (path.equals(WearUris.BASAL_DATA_PATH)) { - dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); - Intent messageIntent = new Intent(); - messageIntent.setAction(Intent.ACTION_SEND); - messageIntent.putExtra("basals", dataMap.toBundle()); - persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMap); - LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent); - } else if (path.equals(WearUris.NEW_PREFERENCES_PATH)) { - dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); - SharedPreferences.Editor editor = sharedPreferences.edit(); - String keyControl = getString(R.string.key_wear_control); - if (dataMap.containsKey(keyControl)) { - boolean previousWearControl = sharedPreferences.getBoolean(keyControl, false); - boolean wearControl = dataMap.getBoolean(keyControl, false); - editor.putBoolean(keyControl, wearControl); - editor.apply(); - if (wearControl != previousWearControl) { - updateTiles(); - } - } - String keyPercentage = getString(R.string.key_boluswizard_percentage); - if (dataMap.containsKey(keyPercentage)) { - int wpercentage = dataMap.getInt(keyPercentage, 100); - editor.putInt(keyPercentage, wpercentage); - editor.apply(); - } - String keyUnits = getString(R.string.key_units_mgdl); - if (dataMap.containsKey(keyUnits)) { - boolean mgdl = dataMap.getBoolean(keyUnits, true); - editor.putBoolean(keyUnits, mgdl); - editor.apply(); - } - String keyMaxCarbs = getString(R.string.key_treatmentssafety_maxcarbs); - if (dataMap.containsKey(keyMaxCarbs)) { - int maxCarbs = dataMap.getInt(keyMaxCarbs, 48); - editor.putInt(keyMaxCarbs, maxCarbs); - editor.apply(); - } - String keyMaxBolus = getString(R.string.key_treatmentssafety_maxbolus); - if (dataMap.containsKey(keyMaxBolus)) { - float maxBolus = (float) dataMap.getDouble(keyMaxBolus, 3.0f); - editor.putFloat(keyMaxBolus, maxBolus); - editor.apply(); - } - - } else if (path.equals(WearUris.QUICK_WIZARD_PATH)) { - dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); - Log.i(TAG, "onDataChanged: QUICK_WIZARD_PATH" + dataMap); - SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); - dataMap.remove("timestamp"); - String key = getString(R.string.key_quick_wizard_data_map); - String dataString = Base64.encodeToString(dataMap.toByteArray(), Base64.DEFAULT); - if (!dataString.equals(sharedPreferences.getString(key, ""))) { - SharedPreferences.Editor editor = sharedPreferences.edit(); - editor.putString(key, dataString); - editor.apply(); - // Todo maybe add debounce function, due to 20 seconds update limit? - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - TileService.getUpdater(this) - .requestUpdate(QuickWizardTileService.class); - } - Log.i(TAG, "onDataChanged: updated QUICK_WIZARD"); - } else { - Log.i(TAG, "onDataChanged: ignore update"); - } - } else if (path.equals(WearUris.ACTION_CHANGECONFIRMATION_REQUEST_PATH)) { - String title = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("title"); - String message = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("message"); - String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring"); - notifyChangeRequest(title, message, actionstring); - } else if (path.equals(WearUris.ACTION_CANCELNOTIFICATION_REQUEST_PATH)) { - String actionstring = DataMapItem.fromDataItem(event.getDataItem()).getDataMap().getString("actionstring"); - cancelNotificationRequest(actionstring); - } else { - dataMap = DataMapItem.fromDataItem(event.getDataItem()).getDataMap(); - Intent messageIntent = new Intent(); - messageIntent.setAction(Intent.ACTION_SEND); - messageIntent.putExtra("data", dataMap.toBundle()); - persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMap); - LocalBroadcastManager.getInstance(this).sendBroadcast(messageIntent); - } - } - } - } - - private void updateTiles() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - TileService.getUpdater(this) - .requestUpdate(ActionsTileService.class); - - TileService.getUpdater(this) - .requestUpdate(TempTargetTileService.class); - - TileService.getUpdater(this) - .requestUpdate(QuickWizardTileService.class); - } - } - - private void notifyChangeRequest(String title, String message, String actionstring) { - // Create the NotificationChannel, but only on API 26+ because - // the NotificationChannel class is new and not in the support library - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - CharSequence name = "AAPS Open Loop"; - String description = "Open Loop request notiffication";//getString(R.string.channel_description); - NotificationChannel channel = new NotificationChannel(AAPS_NOTIFY_CHANNEL_ID_OPENLOOP, name, NotificationManager.IMPORTANCE_HIGH); - channel.setDescription(description); - channel.enableVibration(true); - - // Register the channel with the system; you can't change the importance - // or other notification behaviors after this - NotificationManager notificationManager = getSystemService(NotificationManager.class); - notificationManager.createNotificationChannel(channel); - } - - NotificationCompat.Builder builder = - new NotificationCompat.Builder(this, AAPS_NOTIFY_CHANNEL_ID_OPENLOOP); - - builder = builder.setSmallIcon(R.drawable.notif_icon) - .setContentTitle(title) - .setContentText(message) - .setPriority(Notification.PRIORITY_HIGH) - .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000}); - - // Creates an explicit intent for an Activity in your app - Intent intent = new Intent(this, AcceptActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Bundle params = new Bundle(); - params.putString("title", title); - params.putString("message", message); - params.putString("actionstring", actionstring); - intent.putExtras(params); - - PendingIntent resultPendingIntent = - PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT); - - builder = builder.setContentIntent(resultPendingIntent); - - NotificationManager mNotificationManager = - (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - // mId allows you to update the notification later on. - mNotificationManager.notify(CHANGE_NOTIF_ID, builder.build()); - } - - private void cancelNotificationRequest(String actionstring) { - NotificationManager mNotificationManager = - (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - mNotificationManager.cancel(CHANGE_NOTIF_ID); - } - - private void showBolusProgress(int progresspercent, String progresstatus) { - - long[] vibratePattern; - boolean vibrate = PreferenceManager - .getDefaultSharedPreferences(this).getBoolean("vibrateOnBolus", true); - if (vibrate) { - vibratePattern = new long[]{0, 50, 1000}; - } else { - vibratePattern = new long[]{0, 1, 1000}; - } - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - createBolusProgressChannels(); - } - - Intent cancelIntent = new Intent(this, ListenerService.class); - cancelIntent.setAction(ACTION_CANCELBOLUS); - PendingIntent cancelPendingIntent = PendingIntent.getService(this, 0, cancelIntent, 0); - - NotificationCompat.Builder notificationBuilder = - new NotificationCompat.Builder(this, vibrate ? AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS : AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT) - .setSmallIcon(R.drawable.ic_icon) - .setContentTitle(getString(R.string.bolus_progress)) - .setContentText(progresspercent + "% - " + progresstatus) - .setSubText(getString(R.string.press_to_cancel)) - .setContentIntent(cancelPendingIntent) - .setPriority(NotificationCompat.PRIORITY_MAX) - .setVibrate(vibratePattern) - .addAction(R.drawable.ic_cancel, getString(R.string.cancel_bolus), cancelPendingIntent); - - NotificationManagerCompat notificationManager = - NotificationManagerCompat.from(this); - - notificationManager.notify(BOLUS_PROGRESS_NOTIF_ID, notificationBuilder.build()); - notificationManager.cancel(CONFIRM_NOTIF_ID); // multiple watch setup - - - if (progresspercent == 100) { - scheduleDismissBolusprogress(5); - } - } - - @TargetApi(value = 26) - private void createBolusProgressChannels() { - createNotificationChannel(new long[]{0, 50, 1000}, AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS, getString(R.string.bolus_progress_channel_name), getString(R.string.bolus_progress_channel_description)); - createNotificationChannel(new long[]{0, 1, 1000}, AAPS_NOTIFY_CHANNEL_ID_BOLUSPROGRESS_SILENT, getString(R.string.bolus_progress_silent_channel_name), getString(R.string.bolus_progress_silent_channel_description)); - } - - @TargetApi(value = 26) - private void createNotificationChannel(long[] vibratePattern, String channelID, CharSequence name, String description) { - NotificationChannel channel = new NotificationChannel(channelID, name, NotificationManager.IMPORTANCE_HIGH); - channel.setDescription(description); - channel.enableVibration(true); - channel.setVibrationPattern(vibratePattern); - - // Register the channel with the system; you can't change the importance - // or other notification behaviors after this - NotificationManager notificationManager = getSystemService(NotificationManager.class); - notificationManager.createNotificationChannel(channel); - } - - private void showConfirmationDialog(String title, String message, String actionstring) { - Intent intent = new Intent(this, AcceptActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - Bundle params = new Bundle(); - params.putString("title", title); - params.putString("message", message); - params.putString("actionstring", actionstring); - intent.putExtras(params); - startActivity(intent); - } - - private void scheduleDismissBolusprogress(final int seconds) { - bolusprogressThread = new DismissThread(BOLUS_PROGRESS_NOTIF_ID, seconds); - bolusprogressThread.start(); - } - - private class DismissThread extends Thread { - private final int notificationID; - private final int seconds; - private boolean valid = true; - - DismissThread(int notificationID, int seconds) { - this.notificationID = notificationID; - this.seconds = seconds; - } - - public synchronized void invalidate() { - valid = false; - } - - @Override - public void run() { - SystemClock.sleep(seconds * 1000); - synchronized (this) { - if (valid) { - NotificationManagerCompat notificationManager = - NotificationManagerCompat.from(ListenerService.this); - notificationManager.cancel(notificationID); - } - } - } - } - - public static void requestData(Context context) { - Intent intent = new Intent(context, ListenerService.class); - intent.setAction(ACTION_RESEND); - context.startService(intent); - } - - public static void initiateAction(Context context, @NotNull String actionstring) { - Intent intent = new Intent(context, ListenerService.class); - intent.putExtra("actionstring", actionstring); - intent.setAction(ACTION_INITIATE_ACTION); - context.startService(intent); - } - - public static void confirmAction(Context context, String actionstring) { - Intent intent = new Intent(context, ListenerService.class); - intent.putExtra("actionstring", actionstring); - - if (actionstring.equals("changeRequest")) { - intent.setAction(ACTION_CONFIRMCHANGE); - } else { - intent.setAction(ACTION_CONFIRMATION); - } - context.startService(intent); - } - - @Override - public void onConnected(Bundle bundle) { - // Log.d(TAG, logPrefix + "onConnected call requestData"); - - Wearable.ChannelApi.addListener(googleApiClient, this); - // requestData(); - } - - @Override - public void onConnectionSuspended(int i) { - - } - - @Override - public void onConnectionFailed(ConnectionResult connectionResult) { - - } - - @Override - public void onDestroy() { - super.onDestroy(); - if (googleApiClient != null && googleApiClient.isConnected()) { - googleApiClient.disconnect(); - } - - if (googleApiClient != null) { - Wearable.MessageApi.removeListener(googleApiClient, this); - Wearable.ChannelApi.removeListener(googleApiClient, this); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java deleted file mode 100644 index ecadbd7d4f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.java +++ /dev/null @@ -1,281 +0,0 @@ -package info.nightscout.androidaps.data; - -import android.content.Intent; -import android.os.Bundle; -import android.os.PowerManager; - -import com.google.android.gms.wearable.DataMap; - -import java.util.ArrayList; -import java.util.Iterator; - -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.interaction.utils.Persistence; -import info.nightscout.androidaps.interaction.utils.WearUtil; - -/** - * Holds bunch of data model variables and lists that arrive from phone app and are due to be - * displayed on watchface and complications. Keeping them together makes code cleaner and allows - * passing it to complications via persistence layer. - * - * Created by dlvoy on 2019-11-12 - */ -public class RawDisplayData { - - private final WearUtil wearUtil; - - public RawDisplayData(WearUtil wearUtil) { - this.wearUtil = wearUtil; - } - - static final String DATA_PERSISTENCE_KEY = "raw_data"; - static final String BASALS_PERSISTENCE_KEY = "raw_basals"; - static final String STATUS_PERSISTENCE_KEY = "raw_status"; - - // data bundle - public long sgvLevel = 0; - public long datetime; - public String sSgv = "---"; - public String sDirection = "--"; - public String sDelta = "--"; - public String sAvgDelta = "--"; - public String sUnits = "-"; - - // status bundle - public String sBasalRate = "-.--U/h"; - public String sUploaderBattery = "--"; - public String sRigBattery = "--"; - public boolean detailedIOB = false; - public String sIOB1 = "IOB"; - public String sIOB2 = "-.--"; - public String sCOB1 = "Carb"; - public String sCOB2= "--g"; - public String sBgi = "--"; - public boolean showBGI = false; - public String externalStatusString = "no status"; - public int batteryLevel = 1; - public long openApsStatus = -1; - - // basals bundle - public ArrayList bgDataList = new ArrayList<>(); - public ArrayList tempWatchDataList = new ArrayList<>(); - public ArrayList basalWatchDataList = new ArrayList<>(); - public ArrayList bolusWatchDataList = new ArrayList<>(); - public ArrayList predictionList = new ArrayList<>(); - - public String toDebugString() { - return "DisplayRawData{" + - "sgvLevel=" + sgvLevel + - ", datetime=" + datetime + - ", sSgv='" + sSgv + '\'' + - ", sDirection='" + sDirection + '\'' + - ", sDelta='" + sDelta + '\'' + - ", sAvgDelta='" + sAvgDelta + '\'' + - ", sUnits='" + sUnits + '\'' + - ", sBasalRate='" + sBasalRate + '\'' + - ", sUploaderBattery='" + sUploaderBattery + '\'' + - ", sRigBattery='" + sRigBattery + '\'' + - ", detailedIOB=" + detailedIOB + - ", sIOB1='" + sIOB1 + '\'' + - ", sIOB2='" + sIOB2 + '\'' + - ", sCOB1='" + sCOB1 + '\'' + - ", sCOB2='" + sCOB2 + '\'' + - ", sBgi='" + sBgi + '\'' + - ", showBGI=" + showBGI + - ", externalStatusString='" + externalStatusString + '\'' + - ", batteryLevel=" + batteryLevel + - ", openApsStatus=" + openApsStatus + - ", bgDataList size=" + bgDataList.size() + - ", tempWatchDataList size=" + tempWatchDataList.size() + - ", basalWatchDataList size=" + basalWatchDataList.size() + - ", bolusWatchDataLis size=" + bolusWatchDataList.size() + - ", predictionList size=" + predictionList.size() + - '}'; - } - - public void updateFromPersistence(Persistence persistence) { - - DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY); - if (dataMapData != null) { - updateData(dataMapData); - } - DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY); - if (dataMapStatus != null) { - updateStatus(dataMapStatus); - } - DataMap dataMapBasals = persistence.getDataMap(BASALS_PERSISTENCE_KEY); - if (dataMapBasals != null) { - updateBasals(dataMapBasals); - } - } - - /* - * Since complications do not need Basals, we skip them for performance - */ - public void updateForComplicationsFromPersistence(Persistence persistence) { - - DataMap dataMapData = persistence.getDataMap(DATA_PERSISTENCE_KEY); - if (dataMapData != null) { - updateData(dataMapData); - } - DataMap dataMapStatus = persistence.getDataMap(STATUS_PERSISTENCE_KEY); - if (dataMapStatus != null) { - updateStatus(dataMapStatus); - } - } - - public DataMap updateDataFromMessage(Intent intent, PowerManager.WakeLock wakeLock) { - Bundle bundle = intent.getBundleExtra("data"); - if (bundle != null) { - DataMap dataMap = wearUtil.bundleToDataMap(bundle); - updateData(dataMap); - return dataMap; - } - return null; - } - - private void updateData(DataMap dataMap) { - PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50); - sgvLevel = dataMap.getLong("sgvLevel"); - datetime = dataMap.getLong("timestamp"); - sSgv = dataMap.getString("sgvString"); - sDirection = dataMap.getString("slopeArrow"); - sDelta = dataMap.getString("delta"); - sAvgDelta = dataMap.getString("avgDelta"); - sUnits = dataMap.getString("glucoseUnits"); - wearUtil.releaseWakeLock(wl); - } - - public DataMap updateStatusFromMessage(Intent intent, PowerManager.WakeLock wakeLock) { - Bundle bundle = intent.getBundleExtra("status"); - if (bundle != null) { - DataMap dataMap = wearUtil.bundleToDataMap(bundle); - updateStatus(dataMap); - return dataMap; - } - return null; - } - - private void updateStatus(DataMap dataMap) { - PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50); - sBasalRate = dataMap.getString("currentBasal"); - sUploaderBattery = dataMap.getString("battery"); - sRigBattery = dataMap.getString("rigBattery"); - detailedIOB = dataMap.getBoolean("detailedIob"); - sIOB1 = dataMap.getString("iobSum") + "U"; - sIOB2 = dataMap.getString("iobDetail"); - sCOB1 = "Carb"; - sCOB2 = dataMap.getString("cob"); - sBgi = dataMap.getString("bgi"); - showBGI = dataMap.getBoolean("showBgi"); - externalStatusString = dataMap.getString("externalStatusString"); - batteryLevel = dataMap.getInt("batteryLevel"); - openApsStatus = dataMap.getLong("openApsStatus"); - wearUtil.releaseWakeLock(wl); - } - - public DataMap updateBasalsFromMessage(Intent intent, PowerManager.WakeLock wakeLock) { - Bundle bundle = intent.getBundleExtra("basals"); - if (bundle != null) { - DataMap dataMap = wearUtil.bundleToDataMap(bundle); - updateBasals(dataMap); - return dataMap; - } - return null; - } - - private void updateBasals(DataMap dataMap) { - PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 500); - loadBasalsAndTemps(dataMap); - wearUtil.releaseWakeLock(wl); - } - - private void loadBasalsAndTemps(DataMap dataMap) { - ArrayList temps = dataMap.getDataMapArrayList("temps"); - if (temps != null) { - tempWatchDataList = new ArrayList<>(); - for (DataMap temp : temps) { - TempWatchData twd = new TempWatchData(); - twd.startTime = temp.getLong("starttime"); - twd.startBasal = temp.getDouble("startBasal"); - twd.endTime = temp.getLong("endtime"); - twd.endBasal = temp.getDouble("endbasal"); - twd.amount = temp.getDouble("amount"); - tempWatchDataList.add(twd); - } - } - ArrayList basals = dataMap.getDataMapArrayList("basals"); - if (basals != null) { - basalWatchDataList = new ArrayList<>(); - for (DataMap basal : basals) { - BasalWatchData bwd = new BasalWatchData(); - bwd.startTime = basal.getLong("starttime"); - bwd.endTime = basal.getLong("endtime"); - bwd.amount = basal.getDouble("amount"); - basalWatchDataList.add(bwd); - } - } - ArrayList boluses = dataMap.getDataMapArrayList("boluses"); - if (boluses != null) { - bolusWatchDataList = new ArrayList<>(); - for (DataMap bolus : boluses) { - BolusWatchData bwd = new BolusWatchData(); - bwd.date = bolus.getLong("date"); - bwd.bolus = bolus.getDouble("bolus"); - bwd.carbs = bolus.getDouble("carbs"); - bwd.isSMB = bolus.getBoolean("isSMB"); - bwd.isValid = bolus.getBoolean("isValid"); - bolusWatchDataList.add(bwd); - } - } - ArrayList predictions = dataMap.getDataMapArrayList("predictions"); - if (boluses != null) { - predictionList = new ArrayList<>(); - for (DataMap prediction : predictions) { - BgWatchData bwd = new BgWatchData(); - bwd.timestamp = prediction.getLong("timestamp"); - bwd.sgv = prediction.getDouble("sgv"); - bwd.color = prediction.getInt("color"); - predictionList.add(bwd); - } - } - } - - public void addToWatchSet(DataMap dataMap) { - ArrayList entries = dataMap.getDataMapArrayList("entries"); - if (entries != null) { - bgDataList = new ArrayList<>(); - for (DataMap entry : entries) { - double sgv = entry.getDouble("sgvDouble"); - double high = entry.getDouble("high"); - double low = entry.getDouble("low"); - long timestamp = entry.getLong("timestamp"); - int color = entry.getInt("color", 0); - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } - } else { - double sgv = dataMap.getDouble("sgvDouble"); - double high = dataMap.getDouble("high"); - double low = dataMap.getDouble("low"); - long timestamp = dataMap.getLong("timestamp"); - int color = dataMap.getInt("color", 0); - - final int size = bgDataList.size(); - if (size > 0) { - if (bgDataList.get(size - 1).timestamp == timestamp) - return; // Ignore duplicates. - } - - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } - - // We use iterator instead for-loop because we iterate and remove on the go - Iterator itr = bgDataList.iterator(); - while (itr.hasNext()) { - BgWatchData entry = (BgWatchData)itr.next(); - if (entry.timestamp < (wearUtil.timestamp() - (Constants.HOUR_IN_MS * 5))) { - itr.remove(); //Get rid of anything more than 5 hours old - } - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt new file mode 100644 index 0000000000..471fc91b42 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/data/RawDisplayData.kt @@ -0,0 +1,66 @@ +package info.nightscout.androidaps.data + +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.shared.weardata.EventData + +/** + * Holds bunch of data model variables and lists that arrive from phone app and are due to be + * displayed on watchface and complications. Keeping them together makes code cleaner and allows + * passing it to complications via persistence layer. + * + * Created by dlvoy on 2019-11-12 + * Refactored by MilosKozak 24/04/2022 + * + */ +class RawDisplayData { + + var singleBg = EventData.SingleBg( + timeStamp = 0, + sgvString = "---", + glucoseUnits = "-", + slopeArrow = "--", + delta = "--", + avgDelta = "--", + sgvLevel = 0, + sgv = 0.0, + high = 0.0, + low = 0.0, + color = 0) + + // status bundle + var status = EventData.Status( + externalStatus = "no status", + iobSum = "IOB", + iobDetail = "-.--", + detailedIob = false, + cob = "--g", + currentBasal = "-.--U/h", + battery = "--", + rigBattery = "--", + openApsStatus = -1, + bgi = "--", + showBgi = false, + batteryLevel = 1 + ) + + var graphData = EventData.GraphData( + entries = ArrayList() + ) + + var treatmentData = EventData.TreatmentData( + temps = ArrayList(), + basals = ArrayList(), + boluses = ArrayList(), + predictions = ArrayList() + ) + + fun toDebugString(): String = + "DisplayRawData{singleBg=$singleBg, status=$status, graphData=$graphData, treatmentData=$treatmentData}" + + fun updateFromPersistence(persistence: Persistence) { + persistence.readSingleBg()?.let { singleBg = it } + persistence.readGraphData()?.let { graphData = it } + persistence.readStatus()?.let { status = it } + persistence.readTreatments()?.let { treatmentData = it } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java b/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java deleted file mode 100644 index a7a23962eb..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/data/TempWatchData.java +++ /dev/null @@ -1,13 +0,0 @@ -package info.nightscout.androidaps.data; - -/** - * Created by adrian on 17/11/16. - */ - -public class TempWatchData { - public long startTime; - public double startBasal; - public long endTime; - public double endBasal; - public double amount; -} diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt new file mode 100644 index 0000000000..18a63adb66 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearActivitiesModule.kt @@ -0,0 +1,37 @@ +package info.nightscout.androidaps.di + +import dagger.Module +import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.interaction.ConfigurationActivity +import info.nightscout.androidaps.interaction.TileConfigurationActivity +import info.nightscout.androidaps.interaction.actions.* +import info.nightscout.androidaps.interaction.menus.FillMenuActivity +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.androidaps.interaction.menus.StatusMenuActivity +import info.nightscout.androidaps.interaction.utils.MenuListActivity + +@Module +@Suppress("unused") +abstract class WearActivitiesModule { + + @ContributesAndroidInjector abstract fun contributesTileConfigurationActivity(): TileConfigurationActivity + @ContributesAndroidInjector abstract fun contributesConfigurationActivity(): ConfigurationActivity + + @ContributesAndroidInjector abstract fun contributesBackgroundActionActivity(): BackgroundActionActivity + + @ContributesAndroidInjector abstract fun contributesViewSelectorActivity(): ViewSelectorActivity + @ContributesAndroidInjector abstract fun contributesAcceptActivity(): AcceptActivity + @ContributesAndroidInjector abstract fun contributesBolusActivity(): BolusActivity + @ContributesAndroidInjector abstract fun contributesCarbActivity(): CarbActivity + @ContributesAndroidInjector abstract fun contributesProfileSwitchActivity(): ProfileSwitchActivity + @ContributesAndroidInjector abstract fun contributesECarbActivity(): ECarbActivity + @ContributesAndroidInjector abstract fun contributesFillActivity(): FillActivity + @ContributesAndroidInjector abstract fun contributesTempTargetActivity(): TempTargetActivity + @ContributesAndroidInjector abstract fun contributesTreatmentActivity(): TreatmentActivity + @ContributesAndroidInjector abstract fun contributesWizardActivity(): WizardActivity + + @ContributesAndroidInjector abstract fun contributesMenuListActivity(): MenuListActivity + @ContributesAndroidInjector abstract fun contributesFillMenuActivity(): FillMenuActivity + @ContributesAndroidInjector abstract fun contributesMainMenuActivity(): MainMenuActivity + @ContributesAndroidInjector abstract fun contributesStatusMenuActivity(): StatusMenuActivity +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt index 01e49b6a6f..4315149eb8 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearModule.kt @@ -7,6 +7,8 @@ import dagger.Module import dagger.Provides import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Aaps +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.androidaps.utils.rx.DefaultAapsSchedulers import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLoggerProduction import info.nightscout.shared.logging.L @@ -16,7 +18,8 @@ import javax.inject.Singleton @Suppress("unused") @Module(includes = [ - WearModule.AppBindings::class + WearModule.AppBindings::class, + WearActivitiesModule::class ]) open class WearModule { @@ -28,6 +31,10 @@ open class WearModule { @Singleton fun provideAAPSLogger(l: L): AAPSLogger = AAPSLoggerProduction(l) + @Provides + @Singleton + internal fun provideSchedulers(): AapsSchedulers = DefaultAapsSchedulers() + @Module interface AppBindings { diff --git a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt index 49a3eb5561..6e318f0e45 100644 --- a/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt +++ b/wear/src/main/java/info/nightscout/androidaps/di/WearServicesModule.kt @@ -2,15 +2,16 @@ package info.nightscout.androidaps.di import dagger.Module import dagger.android.ContributesAndroidInjector +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear import info.nightscout.androidaps.complications.* -import info.nightscout.androidaps.data.ListenerService +import info.nightscout.androidaps.tile.* import info.nightscout.androidaps.watchfaces.* @Module @Suppress("unused") abstract class WearServicesModule { - @ContributesAndroidInjector abstract fun contributesListenerService(): ListenerService + @ContributesAndroidInjector abstract fun contributesDataLayerListenerService(): DataLayerListenerServiceWear @ContributesAndroidInjector abstract fun contributesBaseComplicationProviderService(): BaseComplicationProviderService @ContributesAndroidInjector abstract fun contributesBrCobIobComplication(): BrCobIobComplication @@ -23,14 +24,24 @@ abstract class WearServicesModule { @ContributesAndroidInjector abstract fun contributesLongStatusComplication(): LongStatusComplication @ContributesAndroidInjector abstract fun contributesLongStatusFlippedComplication(): LongStatusFlippedComplication @ContributesAndroidInjector abstract fun contributesSgvComplication(): SgvComplication - @ContributesAndroidInjector abstract fun contributesUploaderBattery(): UploaderBattery + @ContributesAndroidInjector abstract fun contributesUploaderBatteryComplication(): UploaderBatteryComplication @ContributesAndroidInjector abstract fun contributesWallpaperComplication(): WallpaperComplication @ContributesAndroidInjector abstract fun contributesBaseWatchFace(): BaseWatchFace - @ContributesAndroidInjector abstract fun contributesHome(): Home - @ContributesAndroidInjector abstract fun contributesHome2(): Home2 - @ContributesAndroidInjector abstract fun contributesLargeHome(): LargeHome - @ContributesAndroidInjector abstract fun contributesSteampunk(): Steampunk - @ContributesAndroidInjector abstract fun contributesDigitalStyle(): DigitalStyle - @ContributesAndroidInjector abstract fun contributesCockpit(): Cockpit + @ContributesAndroidInjector abstract fun contributesAapsWatchface(): AapsWatchface + @ContributesAndroidInjector abstract fun contributesAapsV2Watchface(): AapsV2Watchface + @ContributesAndroidInjector abstract fun contributesAapsLargeWatchface(): AapsLargeWatchface + @ContributesAndroidInjector abstract fun contributesSteampunk(): SteampunkWatchface + @ContributesAndroidInjector abstract fun contributesDigitalStyleWatchface(): DigitalStyleWatchface + @ContributesAndroidInjector abstract fun contributesCockpitWatchface(): CockpitWatchface + + @ContributesAndroidInjector abstract fun contributesBIGChart(): BigChartWatchface + @ContributesAndroidInjector abstract fun contributesNOChart(): NoChartWatchface + @ContributesAndroidInjector abstract fun contributesCircleWatchface(): CircleWatchface + + @ContributesAndroidInjector abstract fun contributesTileBase(): TileBase + @ContributesAndroidInjector abstract fun contributesQuickWizardTileService(): QuickWizardTileService + @ContributesAndroidInjector abstract fun contributesTempTargetTileService(): TempTargetTileService + @ContributesAndroidInjector abstract fun contributesActionsTileService(): ActionsTileService + } \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt b/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt new file mode 100644 index 0000000000..51fe819340 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/events/EventWearPreferenceChange.kt @@ -0,0 +1,22 @@ +package info.nightscout.androidaps.events + +import android.content.Context + +@Suppress("unused") +class EventWearPreferenceChange : Event { + + var changedKey: String? = null + private set + + constructor(key: String) { + changedKey = key + } + + constructor(context: Context, resourceID: Int) { + changedKey = context.getString(resourceID) + } + + fun isChanged(context: Context, id: Int): Boolean { + return changedKey == context.getString(id) + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java b/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java deleted file mode 100644 index 72f9f0a968..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/AAPSPreferences.java +++ /dev/null @@ -1,35 +0,0 @@ -package info.nightscout.androidaps.interaction; - - -import android.os.Bundle; -import android.view.View; -import android.view.ViewGroup; - -import androidx.core.content.ContextCompat; - -import info.nightscout.androidaps.R; -import preference.WearPreferenceActivity; - -public class AAPSPreferences extends WearPreferenceActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - addPreferencesFromResource(R.xml.preferences); - ViewGroup view = (ViewGroup) getWindow().getDecorView(); - removeBackgroundRecursively(view); - view.setBackground(ContextCompat.getDrawable(this, R.drawable.settings_background)); - view.requestFocus(); - } - - void removeBackgroundRecursively(View parent) { - if (parent instanceof ViewGroup) { - ViewGroup group = (ViewGroup) parent; - for (int i = 0; i < group.getChildCount(); i++) { - removeBackgroundRecursively(group.getChildAt(i)); - } - } - parent.setBackground(null); - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java deleted file mode 100644 index e01a31216c..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.java +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.interaction; - -import android.content.res.XmlResourceParser; -import android.os.Bundle; -import android.util.Log; -import android.view.View; -import android.view.ViewGroup; - -import androidx.core.content.ContextCompat; - -import info.nightscout.androidaps.R; -import preference.WearPreferenceActivity; - -public class ConfigurationActivity extends WearPreferenceActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setTitle("Watchface"); - String configFileName = getIntent().getAction(); - int resXmlId = getResources().getIdentifier(configFileName, "xml", getApplicationContext().getPackageName()); - Log.d("ConfigurationActivity::onCreate --->> getIntent().getAction()", configFileName); - Log.d("ConfigurationActivity::onCreate --->> resXmlId", String.valueOf(resXmlId)); - addPreferencesFromResource(resXmlId); - ViewGroup view = (ViewGroup) getWindow().getDecorView(); - removeBackgroundRecursively(view); - view.setBackground(ContextCompat.getDrawable(this, R.drawable.settings_background)); - view.requestFocus(); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - void removeBackgroundRecursively(View parent) { - if (parent instanceof ViewGroup) { - ViewGroup group = (ViewGroup) parent; - for (int i = 0; i < group.getChildCount(); i++) { - removeBackgroundRecursively(group.getChildAt(i)); - } - } - parent.setBackground(null); - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt new file mode 100644 index 0000000000..5c0cee4e8f --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/ConfigurationActivity.kt @@ -0,0 +1,44 @@ +package info.nightscout.androidaps.interaction + +import preference.WearPreferenceActivity +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import javax.inject.Inject + +class ConfigurationActivity : WearPreferenceActivity() { + + @Inject lateinit var aapsLogger: AAPSLogger + + override fun onCreate(savedInstanceState: Bundle?) { + AndroidInjection.inject(this) + super.onCreate(savedInstanceState) + title = "Watchface" + val configFileName = intent.action + val resXmlId = resources.getIdentifier(configFileName, "xml", applicationContext.packageName) + aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> getIntent().getAction() $configFileName") + aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> resXmlId $resXmlId") + addPreferencesFromResource(resXmlId) + val view = window.decorView as ViewGroup + removeBackgroundRecursively(view) + view.background = ContextCompat.getDrawable(this, R.drawable.settings_background) + view.requestFocus() + } + + override fun onPause() { + super.onPause() + finish() + } + + private fun removeBackgroundRecursively(parent: View) { + if (parent is ViewGroup) + for (i in 0 until parent.childCount) + removeBackgroundRecursively(parent.getChildAt(i)) + parent.background = null + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt index 0b73d7fa96..ccf19933fb 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/TileConfigurationActivity.kt @@ -1,26 +1,30 @@ package info.nightscout.androidaps.interaction import android.os.Bundle -import android.util.Log import android.view.ViewGroup import androidx.wear.tiles.TileService -import preference.WearPreferenceActivity +import dagger.android.AndroidInjection import info.nightscout.androidaps.tile.ActionsTileService import info.nightscout.androidaps.tile.TempTargetTileService - -var TAG = "ASTAG-config" +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import preference.WearPreferenceActivity +import javax.inject.Inject class TileConfigurationActivity : WearPreferenceActivity() { + @Inject lateinit var aapsLogger: AAPSLogger + private var configFileName: String? = null override fun onCreate(savedInstanceState: Bundle?) { + AndroidInjection.inject(this) super.onCreate(savedInstanceState) title = "Tile" configFileName = intent.action val resXmlId = resources.getIdentifier(configFileName, "xml", applicationContext.packageName) - Log.d("ConfigurationActivity::onCreate --->> getIntent().getAction()", configFileName!!) - Log.d("ConfigurationActivity::onCreate --->> resXmlId", resXmlId.toString()) + aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> getIntent().getAction() $configFileName") + aapsLogger.debug(LTag.WEAR, "ConfigurationActivity::onCreate --->> resXmlId $resXmlId") addPreferencesFromResource(resXmlId) val view = window.decorView as ViewGroup view.requestFocus() @@ -29,16 +33,20 @@ class TileConfigurationActivity : WearPreferenceActivity() { override fun onDestroy() { super.onDestroy() // Note that TileService updates are hard limited to once every 20 seconds. - if (configFileName === "tile_configuration_activity") { - Log.i(TAG, "onDestroy a: requestUpdate!!") - TileService.getUpdater(this) - .requestUpdate(ActionsTileService::class.java) - } else if (configFileName === "tile_configuration_tempt") { - Log.i(TAG, "onDestroy tt: requestUpdate!!") - TileService.getUpdater(this) - .requestUpdate(TempTargetTileService::class.java) - } else { - Log.i(TAG, "onDestroy : NO tile service available for $configFileName") + when { + configFileName === "tile_configuration_activity" -> { + aapsLogger.info(LTag.WEAR, "onDestroy a: requestUpdate") + TileService.getUpdater(this).requestUpdate(ActionsTileService::class.java) + } + + configFileName === "tile_configuration_tempt" -> { + aapsLogger.info(LTag.WEAR, "onDestroy tt: requestUpdate") + TileService.getUpdater(this).requestUpdate(TempTargetTileService::class.java) + } + + else -> { + aapsLogger.info(LTag.WEAR, "onDestroy : NO tile service available for $configFileName") + } } } } diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt new file mode 100644 index 0000000000..2b06023155 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/WatchfaceConfigurationActivity.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.interaction + +import android.os.Bundle +import android.view.View +import android.view.ViewGroup +import androidx.core.content.ContextCompat +import info.nightscout.androidaps.R +import preference.WearPreferenceActivity + +class WatchfaceConfigurationActivity : WearPreferenceActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + addPreferencesFromResource(R.xml.preferences) + val view = window.decorView as ViewGroup + removeBackgroundRecursively(view) + view.background = ContextCompat.getDrawable(this, R.drawable.settings_background) + view.requestFocus() + } + + private fun removeBackgroundRecursively(parent: View) { + if (parent is ViewGroup) + for (i in 0 until parent.childCount) + removeBackgroundRecursively(parent.getChildAt(i)) + parent.background = null + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java deleted file mode 100644 index 1b3c1ba0f2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.java +++ /dev/null @@ -1,166 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.Context; -import android.content.Intent; -import android.os.Bundle; -import android.os.SystemClock; -import android.os.Vibrator; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.MotionEvent; -import android.view.View; -import android.view.ViewConfiguration; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.core.view.InputDeviceCompat; -import androidx.core.view.MotionEventCompat; -import androidx.core.view.ViewConfigurationCompat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; - -/** - * Created by adrian on 09/02/17. - */ - -public class AcceptActivity extends ViewSelectorActivity { - - String message = ""; - String actionstring = ""; - private DismissThread dismissThread; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - this.dismissThread = new DismissThread(); - dismissThread.start(); - - Bundle extras = getIntent().getExtras(); - message = extras.getString("message", ""); - actionstring = extras.getString("actionstring", ""); - - if ("".equals(message) || "".equals(actionstring)) { - finish(); - return; - } - - setAdapter(new MyGridViewPagerAdapter()); - - Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); - long[] vibratePattern = new long[]{0, 100, 50, 100, 50}; - v.vibrate(vibratePattern, -1); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 2; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_confirm_text, container, false); - final TextView textView = view.findViewById(R.id.message); - final View scrollView = view.findViewById(R.id.message_scroll); - textView.setText(message); - container.addView(view); - scrollView.setOnGenericMotionListener(new View.OnGenericMotionListener() { - @Override - public boolean onGenericMotion(View v, MotionEvent ev) { - if (ev.getAction() == MotionEvent.ACTION_SCROLL && - ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER) - ) { - float delta = -ev.getAxisValue(MotionEventCompat.AXIS_SCROLL) * - ViewConfigurationCompat.getScaledVerticalScrollFactor( - ViewConfiguration.get(container.getContext()), - container.getContext()); - v.scrollBy(0, Math.round(delta)); - - return true; - } - return false; - } - }); - - scrollView.requestFocus(); - return view; - } else { - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - ListenerService.confirmAction(AcceptActivity.this, actionstring); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } - - @Override - public synchronized void onDestroy() { - super.onDestroy(); - if (dismissThread != null) { - dismissThread.invalidate(); - } - - } - - private class DismissThread extends Thread { - private boolean valid = true; - - public synchronized void invalidate() { - valid = false; - } - - @Override - public void run() { - SystemClock.sleep(60 * 1000); - synchronized (this) { - if (valid) { - AcceptActivity.this.finish(); - } - } - } - } - - @Override - protected synchronized void onNewIntent(Intent intent) { - super.onNewIntent(intent); - if (dismissThread != null) dismissThread.invalidate(); - Bundle extras = intent.getExtras(); - Intent msgIntent = new Intent(this, AcceptActivity.class); - msgIntent.putExtras(extras); - startActivity(msgIntent); - finish(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt new file mode 100644 index 0000000000..2134f60f6d --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/AcceptActivity.kt @@ -0,0 +1,130 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.content.Intent +import android.os.Bundle +import android.os.SystemClock +import android.os.Vibrator +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup +import android.widget.ImageView +import android.widget.TextView +import androidx.core.view.InputDeviceCompat +import androidx.core.view.MotionEventCompat +import androidx.core.view.ViewConfigurationCompat +import info.nightscout.androidaps.R +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear +import info.nightscout.androidaps.comm.IntentCancelNotification +import info.nightscout.androidaps.comm.IntentWearToMobile +import kotlin.math.roundToInt + +class AcceptActivity : ViewSelectorActivity() { + + var message = "" + var actionKey = "" + private var dismissThread: DismissThread? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + dismissThread = DismissThread() + dismissThread?.start() + val extras = intent.extras + message = extras?.getString(DataLayerListenerServiceWear.KEY_MESSAGE, "") ?: "" + actionKey = extras?.getString(DataLayerListenerServiceWear.KEY_ACTION_DATA, "") ?: "" + if (message.isEmpty()) { + finish() + return + } + setAdapter(MyGridViewPagerAdapter()) + val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator + val vibratePattern = longArrayOf(0, 100, 50, 100, 50) + vibrator.vibrate(vibratePattern, -1) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 2 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + val view: View + if (col == 0) { + view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_text, container, false) + val textView = view.findViewById(R.id.message) + val scrollView = view.findViewById(R.id.message_scroll) + textView.text = message + container.addView(view) + scrollView.setOnGenericMotionListener { v: View, ev: MotionEvent -> + if (ev.action == MotionEvent.ACTION_SCROLL && + ev.isFromSource(InputDeviceCompat.SOURCE_ROTARY_ENCODER) + ) { + val delta = -ev.getAxisValue(MotionEventCompat.AXIS_SCROLL) * + ViewConfigurationCompat.getScaledVerticalScrollFactor( + ViewConfiguration.get(container.context), + container.context + ) + v.scrollBy(0, delta.roundToInt()) + return@setOnGenericMotionListener true + } + false + } + scrollView.requestFocus() + } else { + view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + if (actionKey.isNotEmpty()) startService(IntentWearToMobile(this@AcceptActivity, actionKey)) + startService(IntentCancelNotification(this@AcceptActivity)) + finishAffinity() + } + container.addView(view) + } + return view + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } + + @Synchronized public override fun onDestroy() { + dismissThread?.invalidate() + super.onDestroy() + } + + private inner class DismissThread : Thread() { + + private var valid = true + @Synchronized fun invalidate() { + valid = false + } + + override fun run() { + SystemClock.sleep((60 * 1000L)) + synchronized(this) { if (valid) finish() } + } + } + + @Synchronized override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + dismissThread?.invalidate() + intent.extras?.let { + startActivity(Intent(this, AcceptActivity::class.java).apply { putExtras(it) }) + finish() + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt index a7db92eea9..15afd34b46 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BackgroundActionActivity.kt @@ -1,28 +1,30 @@ package info.nightscout.androidaps.interaction.actions -import android.app.Activity import android.os.Bundle -import android.util.Log import android.widget.Toast -import info.nightscout.androidaps.data.ListenerService +import dagger.android.DaggerActivity +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.weardata.EventData +import javax.inject.Inject -const val TAG = "QuickWizard" +class BackgroundActionActivity : DaggerActivity() { -class BackgroundActionActivity : Activity() { + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBus override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - val actionString = intent.extras?.getString("actionString") - Log.i(TAG, "QuickWizardActivity.onCreate: actionString=$actionString") - if (actionString != null) { - ListenerService.initiateAction(this, actionString) - val message = intent.extras?.getString("message") - if (message != null) { + intent.extras?.getString(DataLayerListenerServiceWear.KEY_ACTION)?.let { action -> + aapsLogger.info(LTag.WEAR, "QuickWizardActivity.onCreate: action=$action") + rxBus.send(EventWearToMobile(EventData.deserialize(action))) + intent.extras?.getString(DataLayerListenerServiceWear.KEY_MESSAGE)?.let { message -> Toast.makeText(this, message, Toast.LENGTH_LONG).show() } - } else { - Log.e(TAG, "BackgroundActionActivity.onCreate extras 'actionString' required") - } + } ?: aapsLogger.error(LTag.WEAR, "BackgroundActionActivity.onCreate extras 'actionString' required") finishAffinity() } diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java deleted file mode 100644 index 0814ac6a52..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.java +++ /dev/null @@ -1,89 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -public class BolusActivity extends ViewSelectorActivity { - - PlusMinusEditText editInsulin; - float maxBolus; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - maxBolus = sp.getFloat(getString(R.string.key_treatmentssafety_maxbolus), 3f); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 2; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editInsulin != null) { - def = SafeParse.stringToDouble(editInsulin.editText.getText().toString()); - } - editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxBolus, 0.1d, new DecimalFormat("#0.0"),false); - setLabelToPlusMinusView(view, getString(R.string.action_insulin)); - container.addView(view); - view.requestFocus(); - return view; - } else { - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - String actionstring = "bolus " + SafeParse.stringToDouble(editInsulin.editText.getText().toString()) - + " 0"; // Zero carbs - ListenerService.initiateAction(BolusActivity.this, actionstring); - confirmAction(BolusActivity.this, R.string.action_bolus_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt new file mode 100644 index 0000000000..e7e8b56355 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/BolusActivity.kt @@ -0,0 +1,65 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse +import info.nightscout.shared.weardata.EventData.ActionBolusPreCheck +import java.text.DecimalFormat + +class BolusActivity : ViewSelectorActivity() { + + var editInsulin: PlusMinusEditText? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 2 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + val view: View + if (col == 0) { + view = getInflatedPlusMinusView(container) + val initValue = if (editInsulin != null) SafeParse.stringToDouble(editInsulin?.editText?.text.toString()) else 0.0 + val maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0) + editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, initValue, 0.0, maxBolus, 0.1, DecimalFormat("#0.0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_insulin)) + container.addView(view) + view.requestFocus() + } else { + view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + rxBus.send(EventWearToMobile(ActionBolusPreCheck(SafeParse.stringToDouble(editInsulin?.editText?.text.toString()), 0))) + showToast(this@BolusActivity, R.string.action_bolus_confirmation) + finishAffinity() + } + container.addView(view) + } + return view + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java deleted file mode 100644 index d5c488f185..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CPPActivity.java +++ /dev/null @@ -1,120 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.os.Bundle; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 09/02/17. - */ - -public class CPPActivity extends ViewSelectorActivity { - - PlusMinusEditText editPercentage; - PlusMinusEditText editTimeshift; - - int percentage = -1; - int timeshift = -25; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - Bundle extras = getIntent().getExtras(); - percentage = extras.getInt("percentage", -1); - timeshift = extras.getInt("timeshift", -1); - - if (percentage == -1 || timeshift == -25) { - finish(); - return; - } - - if (timeshift < 0) timeshift += 24; - - setAdapter(new MyGridViewPagerAdapter()); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 3; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = timeshift; - if (editTimeshift != null) { - def = SafeParse.stringToDouble(editTimeshift.editText.getText().toString()); - } - editTimeshift = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 23d, 1d, new DecimalFormat("0"), true, true); - setLabelToPlusMinusView(view, getString(R.string.action_timeshift)); - container.addView(view); - view.requestFocus(); - return view; - } else if (col == 1) { - final View view = getInflatedPlusMinusView(container); - double def = percentage; - if (editPercentage != null) { - def = SafeParse.stringToDouble(editPercentage.editText.getText().toString()); - } - editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 30d, 250d, 1d, new DecimalFormat("0"), false); - setLabelToPlusMinusView(view, getString(R.string.action_percentage)); - container.addView(view); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - //check if it can happen that the fagment is never created that hold data? - // (you have to swipe past them anyways - but still) - - String actionstring = "cppset " + SafeParse.stringToInt(editTimeshift.editText.getText().toString()) - + " " + SafeParse.stringToInt(editPercentage.editText.getText().toString()); - ListenerService.initiateAction(CPPActivity.this, actionstring); - confirmAction(CPPActivity.this, R.string.action_cpp_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java deleted file mode 100644 index f5a6b95d08..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.java +++ /dev/null @@ -1,92 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -public class CarbActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - int maxCarbs; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 2; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editCarbs != null) { - def = SafeParse.stringToDouble(editCarbs.editText.getText().toString()); - } - editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), true); - setLabelToPlusMinusView(view, getString(R.string.action_carbs)); - container.addView(view); - view.requestFocus(); - return view; - } else { - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - // With start time 0 and duration 0 - String actionstring = "ecarbs " + SafeParse.stringToInt(editCarbs.editText.getText().toString()) + " 0 0"; - ListenerService.initiateAction(CarbActivity.this, actionstring); - confirmAction(CarbActivity.this, R.string.action_ecarb_confirmation); - finishAffinity(); - - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt new file mode 100644 index 0000000000..4dd487bb79 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/CarbActivity.kt @@ -0,0 +1,72 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse +import info.nightscout.shared.weardata.EventData.ActionECarbsPreCheck +import java.text.DecimalFormat + +class CarbActivity : ViewSelectorActivity() { + + var editCarbs: PlusMinusEditText? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 2 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + val view: View + if (col == 0) { + view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editCarbs != null) { + def = SafeParse.stringToDouble(editCarbs?.editText?.text.toString()) + } + val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48) + editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), true) + setLabelToPlusMinusView(view, getString(R.string.action_carbs)) + container.addView(view) + view.requestFocus() + } else { + view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + // With start time 0 and duration 0 + val bolus = ActionECarbsPreCheck(SafeParse.stringToInt(editCarbs?.editText?.text.toString()), 0, 0) + rxBus.send(EventWearToMobile(bolus)) + showToast(this@CarbActivity, R.string.action_ecarb_confirmation) + finishAffinity() + } + container.addView(view) + } + return view + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java deleted file mode 100644 index 61d0882d70..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.java +++ /dev/null @@ -1,124 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 04/08/18. - */ - -public class ECarbActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - PlusMinusEditText editStartTime; - PlusMinusEditText editDuration; - int maxCarbs; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 4; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editCarbs != null) { - def = SafeParse.stringToDouble(editCarbs.editText.getText().toString()); - } - editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), true); - setLabelToPlusMinusView(view, getString(R.string.action_carbs)); - container.addView(view); - view.requestFocus(); - return view; - } else if (col == 1) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editStartTime != null) { - def = SafeParse.stringToDouble(editStartTime.editText.getText().toString()); - } - editStartTime = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, -60d, 300d, 15d, new DecimalFormat("0"), false); - setLabelToPlusMinusView(view, getString(R.string.action_start_min)); - container.addView(view); - return view; - } else if (col == 2) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editDuration != null) { - def = SafeParse.stringToDouble(editDuration.editText.getText().toString()); - } - editDuration = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 8d, 1d, new DecimalFormat("0"), false); - setLabelToPlusMinusView(view, getString(R.string.action_duration_h)); - container.addView(view); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - - //check if it can happen that the fagment is never created that hold data? - // (you have to swipe past them anyways - but still) - - String actionstring = "ecarbs " + SafeParse.stringToInt(editCarbs.editText.getText().toString()) - + " " + SafeParse.stringToInt(editStartTime.editText.getText().toString()) - + " " + SafeParse.stringToInt(editDuration.editText.getText().toString()); - ListenerService.initiateAction(ECarbActivity.this, actionstring); - confirmAction(ECarbActivity.this, R.string.action_ecarb_confirmation); - finishAffinity(); - - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt new file mode 100644 index 0000000000..21d7b41f31 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ECarbActivity.kt @@ -0,0 +1,101 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse.stringToDouble +import info.nightscout.shared.SafeParse.stringToInt +import info.nightscout.shared.weardata.EventData.ActionECarbsPreCheck +import java.text.DecimalFormat + +class ECarbActivity : ViewSelectorActivity() { + + var editCarbs: PlusMinusEditText? = null + var editStartTime: PlusMinusEditText? = null + var editDuration: PlusMinusEditText? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 4 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editCarbs != null) { + def = stringToDouble(editCarbs?.editText?.text.toString()) + } + val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48) + editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), true) + setLabelToPlusMinusView(view, getString(R.string.action_carbs)) + container.addView(view) + view.requestFocus() + view + } else if (col == 1) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editStartTime != null) { + def = stringToDouble(editStartTime?.editText?.text.toString()) + } + editStartTime = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, -60.0, 300.0, 15.0, DecimalFormat("0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_start_min)) + container.addView(view) + view + } else if (col == 2) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editDuration != null) { + def = stringToDouble(editDuration?.editText?.text.toString()) + } + editDuration = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 8.0, 1.0, DecimalFormat("0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_duration_h)) + container.addView(view) + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + val bolus = ActionECarbsPreCheck( + stringToInt(editCarbs?.editText?.text.toString()), + stringToInt(editStartTime?.editText?.text.toString()), + stringToInt(editDuration?.editText?.text.toString()) + ) + rxBus.send(EventWearToMobile(bolus)) + showToast(this@ECarbActivity, R.string.action_ecarb_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java deleted file mode 100644 index b76829182e..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.java +++ /dev/null @@ -1,93 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.os.Bundle; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 09/02/17. - */ - -public class FillActivity extends ViewSelectorActivity { - - PlusMinusEditText editInsulin; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 2; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = 0d; - if (editInsulin != null) { - def = SafeParse.stringToDouble(editInsulin.editText.getText().toString()); - } - editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 30d, 0.1d, new DecimalFormat("#0.0"), false); - setLabelToPlusMinusView(view, getString(R.string.action_insulin)); - container.addView(view); - view.requestFocus(); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - //check if it can happen that the fagment is never created that hold data? - // (you have to swipe past them anyways - but still) - - String actionstring = "fill " + SafeParse.stringToDouble(editInsulin.editText.getText().toString()); - ListenerService.initiateAction(FillActivity.this, actionstring); - confirmAction(FillActivity.this, R.string.action_fill_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt new file mode 100644 index 0000000000..a10163e466 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/FillActivity.kt @@ -0,0 +1,71 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse.stringToDouble +import info.nightscout.shared.weardata.EventData.ActionFillPreCheck +import java.text.DecimalFormat + +class FillActivity : ViewSelectorActivity() { + + var editInsulin: PlusMinusEditText? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 2 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editInsulin != null) { + def = stringToDouble(editInsulin?.editText?.text.toString()) + } + editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 30.0, 0.1, DecimalFormat("#0.0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_insulin)) + container.addView(view) + view.requestFocus() + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + rxBus.send(EventWearToMobile(ActionFillPreCheck(stringToDouble(editInsulin?.editText?.text.toString())))) + showToast(this@FillActivity, R.string.action_fill_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt new file mode 100644 index 0000000000..73b9551b53 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ProfileSwitchActivity.kt @@ -0,0 +1,94 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse +import info.nightscout.shared.weardata.EventData.ActionProfileSwitchPreCheck +import java.text.DecimalFormat + +class ProfileSwitchActivity : ViewSelectorActivity() { + + var editPercentage: PlusMinusEditText? = null + var editTimeshift: PlusMinusEditText? = null + var percentage = -1 + var timeshift = -25 + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + percentage = intent.extras?.getInt("percentage", -1) ?: -1 + timeshift = intent.extras?.getInt("timeshift", -25) ?: -25 + if (percentage == -1 || timeshift == -25) { + finish() + return + } + if (timeshift < 0) timeshift += 24 + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 3 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + var def = timeshift.toDouble() + if (editTimeshift != null) { + def = SafeParse.stringToDouble(editTimeshift?.editText?.text.toString()) + } + editTimeshift = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 23.0, 1.0, DecimalFormat("0"), true, true) + setLabelToPlusMinusView(view, getString(R.string.action_timeshift)) + container.addView(view) + view.requestFocus() + view + } else if (col == 1) { + val view = getInflatedPlusMinusView(container) + var def = percentage.toDouble() + if (editPercentage != null) { + def = SafeParse.stringToDouble(editPercentage?.editText?.text.toString()) + } + editPercentage = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 30.0, 250.0, 1.0, DecimalFormat("0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_percentage)) + container.addView(view) + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + val ps = ActionProfileSwitchPreCheck(SafeParse.stringToInt(editTimeshift?.editText?.text.toString()), SafeParse.stringToInt(editPercentage?.editText?.text.toString())) + rxBus.send(EventWearToMobile(ps)) + showToast(this@ProfileSwitchActivity, R.string.action_profile_switch_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean { + return view === `object` + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java deleted file mode 100644 index df2db8fafa..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.java +++ /dev/null @@ -1,151 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 09/02/17. - */ - -public class TempTargetActivity extends ViewSelectorActivity { - - PlusMinusEditText lowRange; - PlusMinusEditText highRange; - PlusMinusEditText time; - boolean isMGDL; - boolean isSingleTarget; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setAdapter(new MyGridViewPagerAdapter()); - - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - isMGDL = sp.getBoolean("units_mgdl", true); - isSingleTarget = sp.getBoolean("singletarget", true); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return isSingleTarget ? 3 : 4; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - if (time == null) { - time = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 60d, 0d, 24 * 60d, 5d, new DecimalFormat("0"), false); - } else { - double def = SafeParse.stringToDouble(time.editText.getText().toString()); - time = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, 24 * 60d, 5d, new DecimalFormat("0"), false); - } - setLabelToPlusMinusView(view, getString(R.string.action_duration)); - container.addView(view); - view.requestFocus(); - return view; - - } else if (col == 1) { - final View view = getInflatedPlusMinusView(container); - if (isMGDL) { - double def = 100; - if (lowRange != null) { - def = SafeParse.stringToDouble(lowRange.editText.getText().toString()); - } - lowRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72d, 180d, 1d, new DecimalFormat("0"), false); - } else { - double def = 5.5; - if (lowRange != null) { - def = SafeParse.stringToDouble(lowRange.editText.getText().toString()); - } - lowRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4d, 10d, 0.1d, new DecimalFormat("#0.0"), false); - } - if (isSingleTarget) { - setLabelToPlusMinusView(view, getString(R.string.action_target)); - } else { - setLabelToPlusMinusView(view, getString(R.string.action_low)); - } - container.addView(view); - return view; - } else if (col == 2 && !isSingleTarget) { - final View view = getInflatedPlusMinusView(container); - if (isMGDL) { - double def = 100; - if (highRange != null) { - def = SafeParse.stringToDouble(highRange.editText.getText().toString()); - } - highRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72d, 180d, 1d, new DecimalFormat("0"), false); - } else { - double def = 5.5; - if (highRange != null) { - def = SafeParse.stringToDouble(highRange.editText.getText().toString()); - } - highRange = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4d, 10d, 0.1d, new DecimalFormat("#0.0"), false); - } - setLabelToPlusMinusView(view, getString(R.string.action_high)); - container.addView(view); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - //check if it can happen that the fagment is never created that hold data? - // (you have to swipe past them anyways - but still) - - String actionstring = "temptarget" - + " " + isMGDL - + " " + SafeParse.stringToInt(time.editText.getText().toString()) - + " " + SafeParse.stringToDouble(lowRange.editText.getText().toString()) - + " " + (isSingleTarget ? SafeParse.stringToDouble(lowRange.editText.getText().toString()) : SafeParse.stringToDouble(highRange.editText.getText().toString())); - - ListenerService.initiateAction(TempTargetActivity.this, actionstring); - confirmAction(TempTargetActivity.this, R.string.action_tempt_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt new file mode 100644 index 0000000000..cab25b52eb --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TempTargetActivity.kt @@ -0,0 +1,122 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse +import info.nightscout.shared.weardata.EventData.ActionTempTargetPreCheck +import java.text.DecimalFormat + +class TempTargetActivity : ViewSelectorActivity() { + + var lowRange: PlusMinusEditText? = null + var highRange: PlusMinusEditText? = null + var time: PlusMinusEditText? = null + var isMGDL = false + var isSingleTarget = false + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + isMGDL = sp.getBoolean(R.string.key_units_mgdl, true) + isSingleTarget = sp.getBoolean(R.string.key_single_target, true) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int { + return if (isSingleTarget) 3 else 4 + } + + override fun getRowCount(): Int { + return 1 + } + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + time = if (time == null) { + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 60.0, 0.0, 24 * 60.0, 5.0, DecimalFormat("0"), false) + } else { + val def = SafeParse.stringToDouble(time?.editText?.text.toString()) + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, 24 * 60.0, 5.0, DecimalFormat("0"), false) + } + setLabelToPlusMinusView(view, getString(R.string.action_duration)) + container.addView(view) + view.requestFocus() + view + } else if (col == 1) { + val view = getInflatedPlusMinusView(container) + if (isMGDL) { + var def = 100.0 + if (lowRange != null) def = SafeParse.stringToDouble(lowRange?.editText?.text.toString()) + lowRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72.0, 180.0, 1.0, DecimalFormat("0"), false) + } else { + var def = 5.5 + if (lowRange != null) def = SafeParse.stringToDouble(lowRange?.editText?.text.toString()) + lowRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false) + } + if (isSingleTarget) setLabelToPlusMinusView(view, getString(R.string.action_target)) + else setLabelToPlusMinusView(view, getString(R.string.action_low)) + container.addView(view) + view + } else if (col == 2 && !isSingleTarget) { + val view = getInflatedPlusMinusView(container) + if (isMGDL) { + var def = 100.0 + if (highRange != null) def = SafeParse.stringToDouble(highRange?.editText?.text.toString()) + highRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 72.0, 180.0, 1.0, DecimalFormat("0"), false) + } else { + var def = 5.5 + if (highRange != null) def = SafeParse.stringToDouble(highRange?.editText?.text.toString()) + highRange = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 4.0, 10.0, 0.1, DecimalFormat("#0.0"), false) + } + setLabelToPlusMinusView(view, getString(R.string.action_high)) + container.addView(view) + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + val action = ActionTempTargetPreCheck( + ActionTempTargetPreCheck.TempTargetCommand.MANUAL, + isMGDL, + SafeParse.stringToInt(time?.editText?.text.toString()), + SafeParse.stringToDouble(lowRange?.editText?.text.toString()), + if (isSingleTarget) SafeParse.stringToDouble(lowRange?.editText?.text.toString()) else SafeParse.stringToDouble(highRange?.editText?.text.toString()) + ) + rxBus.send(EventWearToMobile(action)) + showToast(this@TempTargetActivity, R.string.action_tempt_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean { + return view === `object` + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java deleted file mode 100644 index 7929dc2299..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.java +++ /dev/null @@ -1,112 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 09/02/17. - */ - -public class TreatmentActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - PlusMinusEditText editInsulin; - int maxCarbs; - float maxBolus; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - maxBolus = sp.getFloat(getString(R.string.key_treatmentssafety_maxbolus), 3f); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return 3; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editInsulin != null) { - def = SafeParse.stringToDouble(editInsulin.editText.getText().toString()); - } - editInsulin = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double) maxBolus, 0.1d, new DecimalFormat("#0.0"),false); - setLabelToPlusMinusView(view, getString(R.string.action_insulin)); - container.addView(view); - view.requestFocus(); - return view; - } else if (col == 1) { - final View view = getInflatedPlusMinusView(container); - double def = 0; - if (editCarbs != null) { - def = SafeParse.stringToDouble(editCarbs.editText.getText().toString()); - } - editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"),false); - setLabelToPlusMinusView(view, getString(R.string.action_carbs)); - container.addView(view); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - //check if it can happen that the fagment is never created that hold data? - // (you have to swipe past them anyways - but still) - String actionstring = "bolus " + SafeParse.stringToDouble(editInsulin.editText.getText().toString()) - + " " + SafeParse.stringToInt(editCarbs.editText.getText().toString()); - ListenerService.initiateAction(TreatmentActivity.this, actionstring); - confirmAction(TreatmentActivity.this, R.string.action_treatment_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt new file mode 100644 index 0000000000..ed504969b1 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/TreatmentActivity.kt @@ -0,0 +1,82 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse.stringToDouble +import info.nightscout.shared.SafeParse.stringToInt +import info.nightscout.shared.weardata.EventData.ActionBolusPreCheck +import java.text.DecimalFormat + +class TreatmentActivity : ViewSelectorActivity() { + + var editCarbs: PlusMinusEditText? = null + var editInsulin: PlusMinusEditText? = null + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = 3 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + if (editInsulin != null) def = stringToDouble(editInsulin?.editText?.text.toString()) + val maxBolus = sp.getDouble(getString(R.string.key_treatments_safety_max_bolus), 3.0) + editInsulin = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxBolus, 0.1, DecimalFormat("#0.0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_insulin)) + container.addView(view) + view.requestFocus() + view + } else if (col == 1) { + val view = getInflatedPlusMinusView(container) + var def = 0.0 + val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48) + if (editCarbs != null) def = stringToDouble(editCarbs?.editText?.text.toString()) + editCarbs = PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false) + setLabelToPlusMinusView(view, getString(R.string.action_carbs)) + container.addView(view) + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + //check if it can happen that the fragment is never created that hold data? + // (you have to swipe past them anyways - but still) + val bolus = ActionBolusPreCheck(stringToDouble(editInsulin?.editText?.text.toString()), stringToInt(editCarbs?.editText?.text.toString())) + rxBus.send(EventWearToMobile(bolus)) + showToast(this@TreatmentActivity, R.string.action_treatment_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java deleted file mode 100644 index 068cca59f7..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.java +++ /dev/null @@ -1,109 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.DotsPageIndicator; -import android.support.wearable.view.GridPagerAdapter; -import android.support.wearable.view.GridViewPager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.TextView; -import android.widget.Toast; - -import androidx.wear.widget.CurvedTextView; - -import info.nightscout.androidaps.R; - -/** - * Created by adrian on 13/02/17. - */ - -public class ViewSelectorActivity extends Activity { - - private GridViewPager pager; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.grid_layout); - - setTitleBasedOnScreenShape(); - - pager = findViewById(R.id.pager); - DotsPageIndicator dotsPageIndicator = findViewById(R.id.page_indicator); - dotsPageIndicator.setPager(pager); - pager.setOnPageChangeListener(new GridViewPager.OnPageChangeListener() { - @Override - public void onPageScrolled(int row, int column, float rowOffset, float columnOffset, int rowOffsetPixels, int columnOffsetPixels) { - dotsPageIndicator.onPageScrolled(row, column, rowOffset, columnOffset, rowOffsetPixels, - columnOffsetPixels); - } - - @Override - public void onPageSelected(int row, int column) { - dotsPageIndicator.onPageSelected(row, column); - View view = pager.getChildAt(column); - view.requestFocus(); - } - - @Override - public void onPageScrollStateChanged(int state) { - dotsPageIndicator.onPageScrollStateChanged(state); - } - }); - } - - public void setAdapter(GridPagerAdapter adapter) { - pager.setAdapter(adapter); - } - - private void setTitleBasedOnScreenShape() { - // intents can inject dynamic titles, otherwise we'll use the default - String title = String.valueOf(getTitle()); - if (getIntent().getExtras() != null) { - title = getIntent().getExtras().getString("title", title); - } - CurvedTextView titleViewCurved = findViewById(R.id.title_curved); - TextView titleView = findViewById(R.id.title); - if (this.getResources().getConfiguration().isScreenRound()) { - titleViewCurved.setText(title); - titleViewCurved.setVisibility(View.VISIBLE); - titleView.setVisibility((View.GONE)); - } else { - titleView.setText(title); - titleView.setVisibility(View.VISIBLE); - titleViewCurved.setVisibility((View.GONE)); - } - } - - View getInflatedPlusMinusView(ViewGroup container) { - SharedPreferences sharedPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - int design = Integer.parseInt(sharedPrefs.getString("input_design", "1")); - - if (design == 2) { - return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_quickrighty, container, false); - } else if (design == 3) { - return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_quicklefty, container, false); - } else if (design == 4) { - return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item_viktoria, container, false); - } - - //default - return LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_editplusminus_item, container, false); - } - - void setLabelToPlusMinusView(View view, String labelText) { - final TextView textView = view.findViewById(R.id.label); - textView.setText(labelText); - } - - void confirmAction(Context context, int text) { - Toast.makeText(context, getString(text), Toast.LENGTH_LONG).show(); - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt new file mode 100644 index 0000000000..0552f59f36 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/ViewSelectorActivity.kt @@ -0,0 +1,92 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.content.Context +import android.os.Bundle +import android.support.wearable.view.DotsPageIndicator +import android.support.wearable.view.GridPagerAdapter +import android.support.wearable.view.GridViewPager +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.TextView +import android.widget.Toast +import androidx.wear.widget.CurvedTextView +import dagger.android.DaggerActivity +import info.nightscout.androidaps.R +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.shared.sharedPreferences.SP +import javax.inject.Inject + +/** + * Created by adrian on 13/02/17. + */ +open class ViewSelectorActivity : DaggerActivity() { + + @Inject lateinit var sp: SP + @Inject lateinit var rxBus: RxBus + + private var pager: GridViewPager? = null + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.grid_layout) + setTitleBasedOnScreenShape() + pager = findViewById(R.id.pager) + val dotsPageIndicator: DotsPageIndicator = findViewById(R.id.page_indicator) + dotsPageIndicator.setPager(pager) + pager?.setOnPageChangeListener(object : GridViewPager.OnPageChangeListener { + override fun onPageScrolled(row: Int, column: Int, rowOffset: Float, columnOffset: Float, rowOffsetPixels: Int, columnOffsetPixels: Int) { + dotsPageIndicator.onPageScrolled(row, column, rowOffset, columnOffset, rowOffsetPixels, columnOffsetPixels) + } + + override fun onPageSelected(row: Int, column: Int) { + dotsPageIndicator.onPageSelected(row, column) + pager?.getChildAt(column)?.requestFocus() + } + + override fun onPageScrollStateChanged(state: Int) { + dotsPageIndicator.onPageScrollStateChanged(state) + } + }) + } + + fun setAdapter(adapter: GridPagerAdapter?) { + pager?.adapter = adapter + } + + private fun setTitleBasedOnScreenShape() { + // intents can inject dynamic titles, otherwise we'll use the default + var title: String? = this.title.toString() + title = intent?.extras?.getString("title", title) + val titleViewCurved: CurvedTextView = findViewById(R.id.title_curved) + val titleView = findViewById(R.id.title) + if (this.resources.configuration.isScreenRound) { + titleViewCurved.text = title + titleViewCurved.visibility = View.VISIBLE + titleView.visibility = View.GONE + } else { + titleView.text = title + titleView.visibility = View.VISIBLE + titleViewCurved.visibility = View.GONE + } + } + + fun getInflatedPlusMinusView(container: ViewGroup?): View = + when (sp.getInt("input_design", 1)) { + 2 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_quickrighty, container, false) + 3 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_quicklefty, container, false) + 4 -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item_viktoria, container, false) + else -> LayoutInflater.from(applicationContext).inflate(R.layout.action_editplusminus_item, container, false) + } + + fun setLabelToPlusMinusView(view: View, labelText: String?) { + val textView = view.findViewById(R.id.label) + textView.text = labelText + } + + fun showToast(context: Context?, text: Int) { + Toast.makeText(context, getString(text), Toast.LENGTH_LONG).show() + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java deleted file mode 100644 index 0d7be17da4..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.java +++ /dev/null @@ -1,118 +0,0 @@ -package info.nightscout.androidaps.interaction.actions; - -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.wearable.view.GridPagerAdapter; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; - -import java.text.DecimalFormat; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.PlusMinusEditText; -import info.nightscout.shared.SafeParse; - -/** - * Created by adrian on 09/02/17. - */ - -public class WizardActivity extends ViewSelectorActivity { - - PlusMinusEditText editCarbs; - PlusMinusEditText editPercentage; - - boolean hasPercentage; - int percentage; - int maxCarbs; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setAdapter(new MyGridViewPagerAdapter()); - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); - hasPercentage = sp.getBoolean("wizardpercentage", false); - percentage = sp.getInt(getString(R.string.key_boluswizard_percentage), 100); - maxCarbs = sp.getInt(getString(R.string.key_treatmentssafety_maxcarbs), 48); - } - - @Override - protected void onPause() { - super.onPause(); - finish(); - } - - private class MyGridViewPagerAdapter extends GridPagerAdapter { - @Override - public int getColumnCount(int arg0) { - return hasPercentage ? 3 : 2; - } - - @Override - public int getRowCount() { - return 1; - } - - @Override - public Object instantiateItem(ViewGroup container, int row, int col) { - - if (col == 0) { - final View view = getInflatedPlusMinusView(container); - if (editCarbs == null) { - editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 0d, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"), false); - } else { - double def = SafeParse.stringToDouble(editCarbs.editText.getText().toString()); - editCarbs = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0d, (double)maxCarbs, 1d, new DecimalFormat("0"),false); - } - setLabelToPlusMinusView(view, getString(R.string.action_carbs)); - container.addView(view); - view.requestFocus(); - return view; - } else if (col == 1 && hasPercentage) { - final View view = getInflatedPlusMinusView(container); - if (editPercentage == null) { - editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, (double)percentage, 50d, 150d, 1d, new DecimalFormat("0"), false); - } else { - double def = SafeParse.stringToDouble(editPercentage.editText.getText().toString()); - editPercentage = new PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 50d, 150d, 1d, new DecimalFormat("0"), false); - } - setLabelToPlusMinusView(view, getString(R.string.action_percentage)); - container.addView(view); - return view; - } else { - - final View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.action_send_item, container, false); - final ImageView confirmbutton = view.findViewById(R.id.confirmbutton); - confirmbutton.setOnClickListener((View v) -> { - if (editPercentage != null) { - percentage = SafeParse.stringToInt(editPercentage.editText.getText().toString()); - } - - String actionstring = "wizard2 " + SafeParse.stringToInt(editCarbs.editText.getText().toString()) - + " " + percentage; - ListenerService.initiateAction(WizardActivity.this, actionstring); - confirmAction(WizardActivity.this, R.string.action_wizard_confirmation); - finishAffinity(); - }); - container.addView(view); - return view; - } - } - - @Override - public void destroyItem(ViewGroup container, int row, int col, Object view) { - // Handle this to get the data before the view is destroyed? - // Object should still be kept by this, just setup for reinit? - container.removeView((View) view); - } - - @Override - public boolean isViewFromObject(View view, Object object) { - return view == object; - } - - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt new file mode 100644 index 0000000000..53247573a7 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/actions/WizardActivity.kt @@ -0,0 +1,90 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.interaction.actions + +import android.os.Bundle +import android.support.wearable.view.GridPagerAdapter +import android.view.LayoutInflater +import android.view.View +import android.view.ViewGroup +import android.widget.ImageView +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.PlusMinusEditText +import info.nightscout.shared.SafeParse +import info.nightscout.shared.weardata.EventData.ActionWizardPreCheck +import java.text.DecimalFormat + +class WizardActivity : ViewSelectorActivity() { + + var editCarbs: PlusMinusEditText? = null + var editPercentage: PlusMinusEditText? = null + var hasPercentage = false + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setAdapter(MyGridViewPagerAdapter()) + hasPercentage = sp.getBoolean(R.string.key_wizard_percentage, false) + } + + override fun onPause() { + super.onPause() + finish() + } + + private inner class MyGridViewPagerAdapter : GridPagerAdapter() { + + override fun getColumnCount(arg0: Int): Int = if (hasPercentage) 3 else 2 + override fun getRowCount(): Int = 1 + + override fun instantiateItem(container: ViewGroup, row: Int, col: Int): Any { + return if (col == 0) { + val view = getInflatedPlusMinusView(container) + val maxCarbs = sp.getInt(getString(R.string.key_treatments_safety_max_carbs), 48) + editCarbs = if (editCarbs == null) { + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, 0.0, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false) + } else { + val def = SafeParse.stringToDouble(editCarbs?.editText?.text.toString()) + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 0.0, maxCarbs.toDouble(), 1.0, DecimalFormat("0"), false) + } + setLabelToPlusMinusView(view, getString(R.string.action_carbs)) + container.addView(view) + view.requestFocus() + view + } else if (col == 1 && hasPercentage) { + val view = getInflatedPlusMinusView(container) + val percentage = sp.getInt(getString(R.string.key_bolus_wizard_percentage), 100) + editPercentage = if (editPercentage == null) { + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, percentage.toDouble(), 50.0, 150.0, 1.0, DecimalFormat("0"), false) + } else { + val def = SafeParse.stringToDouble(editPercentage?.editText?.text.toString()) + PlusMinusEditText(view, R.id.amountfield, R.id.plusbutton, R.id.minusbutton, def, 50.0, 150.0, 1.0, DecimalFormat("0"), false) + } + setLabelToPlusMinusView(view, getString(R.string.action_percentage)) + container.addView(view) + view + } else { + val view = LayoutInflater.from(applicationContext).inflate(R.layout.action_confirm_ok, container, false) + val confirmButton = view.findViewById(R.id.confirmbutton) + confirmButton.setOnClickListener { + val action = ActionWizardPreCheck( + SafeParse.stringToInt(editCarbs?.editText?.text.toString()), + SafeParse.stringToInt(editPercentage?.editText?.text.toString()) + ) + rxBus.send(EventWearToMobile(action)) + showToast(this@WizardActivity, R.string.action_wizard_confirmation) + finishAffinity() + } + container.addView(view) + view + } + } + + override fun destroyItem(container: ViewGroup, row: Int, col: Int, view: Any) { + // Handle this to get the data before the view is destroyed? + // Object should still be kept by this, just setup for re-init? + container.removeView(view as View) + } + + override fun isViewFromObject(view: View, `object`: Any): Boolean = view === `object` + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java deleted file mode 100644 index 92f557268f..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.java +++ /dev/null @@ -1,51 +0,0 @@ -package info.nightscout.androidaps.interaction.menus; - -import android.content.Intent; -import android.os.Bundle; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.actions.FillActivity; -import info.nightscout.androidaps.interaction.utils.MenuListActivity; - -/** - * Created by adrian on 09/02/17. - */ - -public class FillMenuActivity extends MenuListActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - setTitle(R.string.menu_prime_fill); - super.onCreate(savedInstanceState); - } - - @Override - protected List getElements() { - List menuItems = new ArrayList<>(); - menuItems.add(new MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_1))); - menuItems.add(new MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_2))); - menuItems.add(new MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_3))); - menuItems.add(new MenuItem(R.drawable.ic_canula, getString(R.string.action_free_amount))); - - return menuItems; - } - - @Override - protected void doAction(String action) { - if (getString(R.string.action_preset_1).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 1"); - } else if (getString(R.string.action_preset_2).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 2"); - } else if (getString(R.string.action_preset_3).equals(action)) { - ListenerService.initiateAction(this, "fillpreset 3"); - } else if (getString(R.string.action_free_amount).equals(action)) { - Intent intent = new Intent(this, FillActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.kt new file mode 100644 index 0000000000..56889fca22 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/FillMenuActivity.kt @@ -0,0 +1,34 @@ +package info.nightscout.androidaps.interaction.menus + +import android.content.Intent +import android.os.Bundle +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.actions.FillActivity +import info.nightscout.androidaps.interaction.utils.MenuListActivity +import info.nightscout.shared.weardata.EventData + +class FillMenuActivity : MenuListActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setTitle(R.string.menu_prime_fill) + super.onCreate(savedInstanceState) + } + + override fun getElements(): List = + ArrayList().apply { + add(MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_1))) + add(MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_2))) + add(MenuItem(R.drawable.ic_canula, getString(R.string.action_preset_3))) + add(MenuItem(R.drawable.ic_canula, getString(R.string.action_free_amount))) + } + + override fun doAction(action: String) { + when (action) { + getString(R.string.action_preset_1) -> rxBus.send(EventWearToMobile(EventData.ActionFillPresetPreCheck(1))) + getString(R.string.action_preset_2) -> rxBus.send(EventWearToMobile(EventData.ActionFillPresetPreCheck(2))) + getString(R.string.action_preset_3) -> rxBus.send(EventWearToMobile(EventData.ActionFillPresetPreCheck(3))) + getString(R.string.action_free_amount) -> startActivity(Intent(this, FillActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java deleted file mode 100644 index fcc21cee0d..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.java +++ /dev/null @@ -1,98 +0,0 @@ -package info.nightscout.androidaps.interaction.menus; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.AAPSPreferences; -import info.nightscout.androidaps.interaction.actions.TreatmentActivity; -import info.nightscout.androidaps.interaction.actions.ECarbActivity; -import info.nightscout.androidaps.interaction.actions.TempTargetActivity; -import info.nightscout.androidaps.interaction.actions.WizardActivity; -import info.nightscout.androidaps.interaction.utils.MenuListActivity; - -/** - * Created by adrian on 09/02/17. - */ - -public class MainMenuActivity extends MenuListActivity { - - SharedPreferences sp; - - @Override - protected void onCreate(Bundle savedInstanceState) { - sp = PreferenceManager.getDefaultSharedPreferences(this); - setTitle(R.string.label_actions_activity); - super.onCreate(savedInstanceState); - ListenerService.requestData(this); - } - - @Override - protected List getElements() { - - List menuItems = new ArrayList<>(); - if (!sp.getBoolean("wearcontrol", false)) { - menuItems.add(new MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))); - menuItems.add(new MenuItem(R.drawable.ic_sync, getString(R.string.menu_resync))); - - return menuItems; - } - - boolean showPrimeFill = sp.getBoolean("primefill", false); - boolean showWizard = sp.getBoolean("showWizard", true); - - if (showWizard) menuItems.add(new MenuItem(R.drawable.ic_calculator, getString(R.string.menu_wizard))); - menuItems.add(new MenuItem(R.drawable.ic_e_carbs, getString(R.string.menu_ecarb))); - menuItems.add(new MenuItem(R.drawable.ic_treatment, getString(R.string.menu_treatment))); - menuItems.add(new MenuItem(R.drawable.ic_temptarget, getString(R.string.menu_tempt))); - menuItems.add(new MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))); - menuItems.add(new MenuItem(R.drawable.ic_status, getString(R.string.menu_status))); - if (showPrimeFill) menuItems.add(new MenuItem(R.drawable.ic_canula, getString(R.string.menu_prime_fill))); - - return menuItems; - } - - @Override - protected void doAction(String action) { - - Intent intent; - - if (getString(R.string.menu_settings).equals(action)) { - intent = new Intent(this, AAPSPreferences.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_resync).equals(action)) { - ListenerService.requestData(this); - } else if (getString(R.string.menu_tempt).equals(action)) { - intent = new Intent(this, TempTargetActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_treatment).equals(action)) { - intent = new Intent(this, TreatmentActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_wizard).equals(action)) { - intent = new Intent(this, WizardActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_status).equals(action)) { - intent = new Intent(this, StatusMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_prime_fill).equals(action)) { - intent = new Intent(this, FillMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } else if (getString(R.string.menu_ecarb).equals(action)) { - intent = new Intent(this, ECarbActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - this.startActivity(intent); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt new file mode 100644 index 0000000000..9cc84c832c --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/MainMenuActivity.kt @@ -0,0 +1,56 @@ +package info.nightscout.androidaps.interaction.menus + +import android.content.Intent +import android.os.Bundle +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.WatchfaceConfigurationActivity +import info.nightscout.androidaps.interaction.actions.ECarbActivity +import info.nightscout.androidaps.interaction.actions.TempTargetActivity +import info.nightscout.androidaps.interaction.actions.TreatmentActivity +import info.nightscout.androidaps.interaction.actions.WizardActivity +import info.nightscout.androidaps.interaction.utils.MenuListActivity +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.ActionResendData + +class MainMenuActivity : MenuListActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setTitle(R.string.label_actions_activity) + super.onCreate(savedInstanceState) + rxBus.send(EventWearToMobile(ActionResendData("MainMenuListActivity"))) + } + + override fun getElements(): List = + ArrayList().apply { + if (!sp.getBoolean(R.string.key_wear_control, false)) { + add(MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))) + add(MenuItem(R.drawable.ic_sync, getString(R.string.menu_resync))) + } else { + if (sp.getBoolean(R.string.key_show_wizard, true)) + add(MenuItem(R.drawable.ic_calculator, getString(R.string.menu_wizard))) + add(MenuItem(R.drawable.ic_e_carbs, getString(R.string.menu_ecarb))) + add(MenuItem(R.drawable.ic_treatment, getString(R.string.menu_treatment))) + add(MenuItem(R.drawable.ic_temptarget, getString(R.string.menu_tempt))) + add(MenuItem(R.drawable.ic_status, getString(R.string.status_profile_switch))) + add(MenuItem(R.drawable.ic_settings, getString(R.string.menu_settings))) + add(MenuItem(R.drawable.ic_status, getString(R.string.menu_status))) + if (sp.getBoolean(R.string.key_prime_fill, false)) + add(MenuItem(R.drawable.ic_canula, getString(R.string.menu_prime_fill))) + } + } + + override fun doAction(action: String) { + when (action) { + getString(R.string.menu_settings) -> startActivity(Intent(this, WatchfaceConfigurationActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_resync) -> rxBus.send(EventWearToMobile(ActionResendData("Re-Sync"))) + getString(R.string.status_profile_switch) -> rxBus.send(EventWearToMobile(EventData.ActionProfileSwitchSendInitialData(System.currentTimeMillis()))) + getString(R.string.menu_tempt) -> startActivity(Intent(this, TempTargetActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_treatment) -> startActivity(Intent(this, TreatmentActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_wizard) -> startActivity(Intent(this, WizardActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_status) -> startActivity(Intent(this, StatusMenuActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_prime_fill) -> startActivity(Intent(this, FillMenuActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + getString(R.string.menu_ecarb) -> startActivity(Intent(this, ECarbActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java deleted file mode 100644 index 8861e45ed6..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.java +++ /dev/null @@ -1,47 +0,0 @@ -package info.nightscout.androidaps.interaction.menus; - -import android.os.Bundle; - -import java.util.ArrayList; -import java.util.List; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.interaction.utils.MenuListActivity; - -/** - * Created by adrian on 09/02/17. - */ - -public class StatusMenuActivity extends MenuListActivity { - - @Override - protected void onCreate(Bundle savedInstanceState) { - setTitle(R.string.menu_status); - super.onCreate(savedInstanceState); - } - - @Override - protected List getElements() { - List menuitems = new ArrayList<>(); - menuitems.add(new MenuItem(R.drawable.ic_status, getString(R.string.status_pump))); - menuitems.add(new MenuItem(R.drawable.ic_loop_closed, getString(R.string.status_loop))); - menuitems.add(new MenuItem(R.drawable.ic_status, getString(R.string.status_cpp))); - menuitems.add(new MenuItem(R.drawable.ic_tdd, getString(R.string.status_tdd))); - - return menuitems; - } - - @Override - protected void doAction(String action) { - if (getString(R.string.status_pump).equals(action)) { - ListenerService.initiateAction(this, "status pump"); - } else if (getString(R.string.status_loop).equals(action)) { - ListenerService.initiateAction(this, "status loop"); - } else if (getString(R.string.status_cpp).equals(action)) { - ListenerService.initiateAction(this, "opencpp"); - } else if (getString(R.string.status_tdd).equals(action)) { - ListenerService.initiateAction(this, "tddstats"); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.kt new file mode 100644 index 0000000000..38ffeef840 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/menus/StatusMenuActivity.kt @@ -0,0 +1,32 @@ +package info.nightscout.androidaps.interaction.menus + +import android.os.Bundle +import info.nightscout.androidaps.R +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.utils.MenuListActivity +import info.nightscout.shared.weardata.EventData.ActionLoopStatus +import info.nightscout.shared.weardata.EventData.ActionPumpStatus +import info.nightscout.shared.weardata.EventData.ActionTddStatus + +class StatusMenuActivity : MenuListActivity() { + + override fun onCreate(savedInstanceState: Bundle?) { + setTitle(R.string.menu_status) + super.onCreate(savedInstanceState) + } + + override fun getElements(): List = + ArrayList().apply { + add(MenuItem(R.drawable.ic_status, getString(R.string.status_pump))) + add(MenuItem(R.drawable.ic_loop_closed, getString(R.string.status_loop))) + add(MenuItem(R.drawable.ic_tdd, getString(R.string.status_tdd))) + } + + override fun doAction(action: String) { + when (action) { + getString(R.string.status_pump) -> rxBus.send(EventWearToMobile(ActionPumpStatus(System.currentTimeMillis()))) + getString(R.string.status_loop) -> rxBus.send(EventWearToMobile(ActionLoopStatus(System.currentTimeMillis()))) + getString(R.string.status_tdd) -> rxBus.send(EventWearToMobile(ActionTddStatus(System.currentTimeMillis()))) + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java deleted file mode 100644 index 2af3ef34b6..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.java +++ /dev/null @@ -1,14 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -public class Constants { - - public static final long SECOND_IN_MS = 1000; - public static final long MINUTE_IN_MS = 60000; - public static final long HOUR_IN_MS = 3600000; - public static final long DAY_IN_MS = 86400000; - public static final long WEEK_IN_MS = DAY_IN_MS * 7; - public static final long MONTH_IN_MS = DAY_IN_MS * 30; - - public static final long STALE_MS = Constants.MINUTE_IN_MS * 12; - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.kt new file mode 100644 index 0000000000..3c8ce54949 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Constants.kt @@ -0,0 +1,13 @@ +package info.nightscout.androidaps.interaction.utils + +@Suppress("unused") +object Constants { + + const val SECOND_IN_MS: Long = 1000 + const val MINUTE_IN_MS: Long = 60000 + const val HOUR_IN_MS: Long = 3600000 + const val DAY_IN_MS: Long = 86400000 + const val WEEK_IN_MS = DAY_IN_MS * 7 + const val MONTH_IN_MS = DAY_IN_MS * 30 + const val STALE_MS = MINUTE_IN_MS * 12 +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java index bbdfa0aa04..18f2f3ca81 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/DisplayFormat.java @@ -12,7 +12,8 @@ public class DisplayFormat { @Inject SP sp; @Inject WearUtil wearUtil; - @Inject DisplayFormat() {} + @Inject DisplayFormat() { + } /** * Maximal and minimal lengths of fields/labels shown in complications, in characters @@ -65,27 +66,27 @@ public class DisplayFormat { public String shortTrend(final RawDisplayData raw) { String minutes = "--"; - if (raw.datetime > 0) { - minutes = shortTimeSince(raw.datetime); + if (raw.getSingleBg().getTimeStamp() > 0) { + minutes = shortTimeSince(raw.getSingleBg().getTimeStamp()); } - if (minutes.length() + raw.sDelta.length() + deltaSymbol().length() + 1 <= MAX_FIELD_LEN_SHORT) { - return minutes + " " + deltaSymbol() + raw.sDelta; + if (minutes.length() + raw.getSingleBg().getDelta().length() + deltaSymbol().length() + 1 <= MAX_FIELD_LEN_SHORT) { + return minutes + " " + deltaSymbol() + raw.getSingleBg().getDelta(); } // that only optimizes obvious things like 0 before . or at end, + at beginning - String delta = (new SmallestDoubleString(raw.sDelta)).minimise(MAX_FIELD_LEN_SHORT -1); + String delta = (new SmallestDoubleString(raw.getSingleBg().getDelta())).minimise(MAX_FIELD_LEN_SHORT - 1); if (minutes.length() + delta.length() + deltaSymbol().length() + 1 <= MAX_FIELD_LEN_SHORT) { return minutes + " " + deltaSymbol() + delta; } - String shortDelta = (new SmallestDoubleString(raw.sDelta)).minimise(MAX_FIELD_LEN_SHORT -(1+minutes.length())); + String shortDelta = (new SmallestDoubleString(raw.getSingleBg().getDelta())).minimise(MAX_FIELD_LEN_SHORT - (1 + minutes.length())); return minutes + " " + shortDelta; } public String longGlucoseLine(final RawDisplayData raw) { - return raw.sSgv + raw.sDirection + " " + deltaSymbol() + (new SmallestDoubleString(raw.sDelta)).minimise(8) + " (" + shortTimeSince(raw.datetime) + ")"; + return raw.getSingleBg().getSgvString() + raw.getSingleBg().getSlopeArrow() + " " + deltaSymbol() + (new SmallestDoubleString(raw.getSingleBg().getDelta())).minimise(8) + " (" + shortTimeSince(raw.getSingleBg().getTimeStamp()) + ")"; } public String longDetailsLine(final RawDisplayData raw) { @@ -95,62 +96,63 @@ public class DisplayFormat { final int SEP_SHORT_LEN = SEP_SHORT.length(); final String SEP_MIN = " "; - String line = raw.sCOB2 + SEP_LONG + raw.sIOB1 + SEP_LONG + basalRateSymbol()+raw.sBasalRate; + String line = + raw.getStatus().getCob() + SEP_LONG + raw.getStatus().getIobSum() + SEP_LONG + basalRateSymbol() + raw.getStatus().getCurrentBasal(); if (line.length() <= MAX_FIELD_LEN_LONG) { return line; } - line = raw.sCOB2 + SEP_SHORT + raw.sIOB1 + SEP_SHORT + raw.sBasalRate; + line = raw.getStatus().getCob() + SEP_SHORT + raw.getStatus().getIobSum() + SEP_SHORT + raw.getStatus().getCurrentBasal(); if (line.length() <= MAX_FIELD_LEN_LONG) { return line; } - int remainingMax = MAX_FIELD_LEN_LONG - (raw.sCOB2.length() + raw.sBasalRate.length() + SEP_SHORT_LEN*2); - final String smallestIoB = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_IOB, remainingMax)); - line = raw.sCOB2 + SEP_SHORT + smallestIoB + SEP_SHORT + raw.sBasalRate; + int remainingMax = MAX_FIELD_LEN_LONG - (raw.getStatus().getCob().length() + raw.getStatus().getCurrentBasal().length() + SEP_SHORT_LEN * 2); + final String smallestIoB = new SmallestDoubleString(raw.getStatus().getIobSum(), SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_IOB, remainingMax)); + line = raw.getStatus().getCob() + SEP_SHORT + smallestIoB + SEP_SHORT + raw.getStatus().getCurrentBasal(); if (line.length() <= MAX_FIELD_LEN_LONG) { return line; } - remainingMax = MAX_FIELD_LEN_LONG - (smallestIoB.length() + raw.sBasalRate.length() + SEP_SHORT_LEN*2); - final String simplifiedCob = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_COB, remainingMax)); + remainingMax = MAX_FIELD_LEN_LONG - (smallestIoB.length() + raw.getStatus().getCurrentBasal().length() + SEP_SHORT_LEN * 2); + final String simplifiedCob = new SmallestDoubleString(raw.getStatus().getCob(), SmallestDoubleString.Units.USE).minimise(Math.max(MIN_FIELD_LEN_COB, remainingMax)); - line = simplifiedCob + SEP_SHORT + smallestIoB + SEP_SHORT + raw.sBasalRate; + line = simplifiedCob + SEP_SHORT + smallestIoB + SEP_SHORT + raw.getStatus().getCurrentBasal(); if (line.length() <= MAX_FIELD_LEN_LONG) { return line; } - line = simplifiedCob + SEP_MIN + smallestIoB + SEP_MIN + raw.sBasalRate; + line = simplifiedCob + SEP_MIN + smallestIoB + SEP_MIN + raw.getStatus().getCurrentBasal(); return line; } public Pair detailedIob(RawDisplayData raw) { - final String iob1 = new SmallestDoubleString(raw.sIOB1, SmallestDoubleString.Units.USE).minimise(MAX_FIELD_LEN_SHORT); + final String iob1 = new SmallestDoubleString(raw.getStatus().getIobSum(), SmallestDoubleString.Units.USE).minimise(MAX_FIELD_LEN_SHORT); String iob2 = ""; - if (raw.sIOB2.contains("|")) { - String[] iobs = raw.sIOB2.replace("(", "").replace(")", "").split("\\|"); + if (raw.getStatus().getIobDetail().contains("|")) { + String[] iobs = raw.getStatus().getIobDetail().replace("(", "").replace(")", "").split("\\|"); String iobBolus = new SmallestDoubleString(iobs[0]).minimise(MIN_FIELD_LEN_IOB); if (iobBolus.trim().length() == 0) { iobBolus = "--"; } - String iobBasal = new SmallestDoubleString(iobs[1]).minimise((MAX_FIELD_LEN_SHORT -1) - Math.max(MIN_FIELD_LEN_IOB, iobBolus.length())); + String iobBasal = new SmallestDoubleString(iobs[1]).minimise((MAX_FIELD_LEN_SHORT - 1) - Math.max(MIN_FIELD_LEN_IOB, iobBolus.length())); if (iobBasal.trim().length() == 0) { iobBasal = "--"; } - iob2 = iobBolus+" "+iobBasal; + iob2 = iobBolus + " " + iobBasal; } - return Pair.create(iob1, iob2); + return Pair.Companion.create(iob1, iob2); } public Pair detailedCob(final RawDisplayData raw) { - SmallestDoubleString cobMini = new SmallestDoubleString(raw.sCOB2, SmallestDoubleString.Units.USE); + SmallestDoubleString cobMini = new SmallestDoubleString(raw.getStatus().getCob(), SmallestDoubleString.Units.USE); String cob2 = ""; if (cobMini.getExtra().length() > 0) { cob2 = cobMini.getExtra() + cobMini.getUnits(); } final String cob1 = cobMini.minimise(MAX_FIELD_LEN_SHORT); - return Pair.create(cob1, cob2); + return Pair.Companion.create(cob1, cob2); } } diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java deleted file mode 100644 index 5e97469c0c..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.java +++ /dev/null @@ -1,127 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.os.PowerManager; -import android.util.Log; - -import java.util.concurrent.ConcurrentHashMap; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.BuildConfig; - -/** - * Created for xDrip by jamorham on 07/03/2018 - * Adapted for AAPS by dlvoy on 2019-11-11 - * - * Tasks which are fired from events can be scheduled here and only execute when they become idle - * and are not being rescheduled within their wait window. - * - */ - -@Singleton -public class Inevitable { - - @Inject WearUtil wearUtil; - - @Inject Inevitable() {} - - private static final String TAG = Inevitable.class.getSimpleName(); - private static final int MAX_QUEUE_TIME = (int) Constants.MINUTE_IN_MS * 6; - private static final boolean debug = BuildConfig.DEBUG; - - private final ConcurrentHashMap tasks = new ConcurrentHashMap<>(); - - public void task(final String id, long idle_for, Runnable runnable) { - if (idle_for > MAX_QUEUE_TIME) { - throw new RuntimeException(id + " Requested time: " + idle_for + " beyond max queue time"); - } - final Task task = tasks.get(id); - if (task != null) { - // if it already exists then extend the time - task.extendTime(idle_for); - - if (debug) - Log.d(TAG, "Extending time for: " + id + " to " + wearUtil.dateTimeText(task.when)); - } else { - // otherwise create new task - if (runnable == null) return; // extension only if already exists - tasks.put(id, new Task(id, idle_for, runnable)); - - if (debug) { - Log.d(TAG, - "Creating task: " + id + " due: " + wearUtil.dateTimeText(tasks.get(id).when)); - } - - // create a thread to wait and execute in background - final Thread t = new Thread(() -> { - final PowerManager.WakeLock wl = wearUtil.getWakeLock(id, MAX_QUEUE_TIME + 5000); - try { - boolean running = true; - // wait for task to be due or killed - while (running) { - wearUtil.threadSleep(500); - final Task thisTask = tasks.get(id); - running = thisTask != null && !thisTask.poll(); - } - } finally { - wearUtil.releaseWakeLock(wl); - } - }); - t.setPriority(Thread.MIN_PRIORITY); - t.start(); - } - } - - public void stackableTask(String id, long idle_for, Runnable runnable) { - int stack = 0; - while (tasks.get(id = id + "-" + stack) != null) { - stack++; - } - if (stack > 0) { - Log.d(TAG, "Task stacked to: " + id); - } - task(id, idle_for, runnable); - } - - public void kill(final String id) { - tasks.remove(id); - } - - public boolean waiting(final String id) { - return tasks.containsKey(id); - } - - private class Task { - private long when; - private final Runnable what; - private final String id; - - Task(String id, long offset, Runnable what) { - this.what = what; - this.id = id; - extendTime(offset); - } - - public void extendTime(long offset) { - this.when = wearUtil.timestamp() + offset; - } - - public boolean poll() { - final long till = wearUtil.msTill(when); - if (till < 1) { - if (debug) Log.d(TAG, "Executing task! " + this.id); - tasks.remove(this.id); // early remove to allow overlapping scheduling - what.run(); - return true; - } else if (till > MAX_QUEUE_TIME) { - Log.wtf(TAG, "Task: " + this.id + " In queue too long: " + till); - tasks.remove(this.id); - return true; - } - return false; - } - - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.kt new file mode 100644 index 0000000000..410f358499 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Inevitable.kt @@ -0,0 +1,103 @@ +package info.nightscout.androidaps.interaction.utils + +import info.nightscout.androidaps.BuildConfig +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import java.util.concurrent.ConcurrentHashMap +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created for xDrip by jamorham on 07/03/2018 + * Adapted for AAPS by dlvoy on 2019-11-11 + * + * Tasks which are fired from events can be scheduled here and only execute when they become idle + * and are not being rescheduled within their wait window. + * + */ +@Singleton +class Inevitable @Inject internal constructor() { + + @Inject lateinit var wearUtil: WearUtil + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var dateUtil: DateUtil + + private val tasks = ConcurrentHashMap() + fun task(id: String, idle_for: Long, runnable: Runnable?) { + if (idle_for > MAX_QUEUE_TIME) { + throw RuntimeException("$id Requested time: $idle_for beyond max queue time") + } + val task = tasks[id] + if (task != null) { + // if it already exists then extend the time + task.extendTime(idle_for) + if (debug) aapsLogger.debug(LTag.WEAR, "Extending time for: " + id + " to " + dateUtil.dateAndTimeAndSecondsString(task.`when`)) + } else { + // otherwise create new task + if (runnable == null) return // extension only if already exists + tasks[id] = Task(id, idle_for, runnable) + if (debug) { + aapsLogger.debug( + LTag.WEAR, + "Creating task: " + id + " due: " + dateUtil.dateAndTimeAndSecondsString(tasks[id]!!.`when`) + ) + } + + // create a thread to wait and execute in background + val t = Thread { + val wl = wearUtil.getWakeLock(id, MAX_QUEUE_TIME + 5000) + try { + var running = true + // wait for task to be due or killed + while (running) { + wearUtil.threadSleep(500) + val thisTask = tasks[id] + running = thisTask != null && !thisTask.poll() + } + } finally { + wearUtil.releaseWakeLock(wl) + } + } + t.priority = Thread.MIN_PRIORITY + t.start() + } + } + + fun kill(id: String) { + tasks.remove(id) + } + + private inner class Task(private val id: String, offset: Long, private val what: Runnable) { + + var `when`: Long = 0 + fun extendTime(offset: Long) { + `when` = wearUtil.timestamp() + offset + } + + fun poll(): Boolean { + val till = wearUtil.msTill(`when`) + if (till < 1) { + if (debug) aapsLogger.debug(LTag.WEAR, "Executing task! $id") + tasks.remove(id) // early remove to allow overlapping scheduling + what.run() + return true + } else if (till > MAX_QUEUE_TIME) { + aapsLogger.debug(LTag.WEAR, "Task: $id In queue too long: $till") + tasks.remove(id) + return true + } + return false + } + + init { + extendTime(offset) + } + } + + companion object { + + private const val MAX_QUEUE_TIME = Constants.MINUTE_IN_MS.toInt() * 6 + private val debug = BuildConfig.DEBUG + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/MenuListActivity.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/MenuListActivity.java index fb53413d1e..3f55afebd2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/MenuListActivity.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/MenuListActivity.java @@ -1,6 +1,5 @@ package info.nightscout.androidaps.interaction.utils; -import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; @@ -9,6 +8,7 @@ import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; +import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import androidx.wear.widget.CurvedTextView; import androidx.wear.widget.WearableLinearLayoutManager; @@ -16,13 +16,22 @@ import androidx.wear.widget.WearableRecyclerView; import java.util.List; +import javax.inject.Inject; + +import dagger.android.DaggerActivity; import info.nightscout.androidaps.R; +import info.nightscout.androidaps.plugins.bus.RxBus; +import info.nightscout.shared.sharedPreferences.SP; /** * Created by adrian on 08/02/17. */ -public abstract class MenuListActivity extends Activity { +public abstract class MenuListActivity extends DaggerActivity { + + @Inject public RxBus rxBus; + @Inject public SP sp; + List elements; protected abstract List getElements(); @@ -96,7 +105,7 @@ public abstract class MenuListActivity extends Activity { } } - @Override + @NonNull @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false); diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java deleted file mode 100644 index 4207cbd743..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.java +++ /dev/null @@ -1,43 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import java.util.Objects; - -/** - * Same as android Pair, but clean room java class - does not require Android SDK for tests - */ -public class Pair { - - public final F first; - public final S second; - - public Pair(F first, S second) { - this.first = first; - this.second = second; - } - - public static Pair create(F f, S s) { - return new Pair<>(f, s); - } - - @Override - public boolean equals(java.lang.Object o) { - if (o instanceof Pair) { - return ((Pair) o).first.equals(first) && ((Pair) o).second.equals(second); - } else { - return false; - } - } - - @Override - public String toString() { - return "First: \""+first.toString()+"\" Second: \""+second.toString()+"\""; - } - - @Override - public int hashCode() { - return Objects.hash(first, second); - } - -} - - diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.kt new file mode 100644 index 0000000000..9d087b0bc8 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Pair.kt @@ -0,0 +1,21 @@ +package info.nightscout.androidaps.interaction.utils + +import java.util.* + +/** + * Same as android Pair, but clean room java class - does not require Android SDK for tests + */ +class Pair(val first: F, val second: S) { + + override fun equals(other: Any?): Boolean = + if (other is Pair<*, *>) other.first == first && other.second == second + else false + + override fun toString(): String = "First: \"" + first.toString() + "\" Second: \"" + second.toString() + "\"" + override fun hashCode(): Int = Objects.hash(first, second) + + companion object { + + fun create(f: F, s: S): Pair = Pair(f, s) + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java deleted file mode 100644 index afb2b42bd2..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.java +++ /dev/null @@ -1,151 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.content.Context; -import android.content.SharedPreferences; -import android.util.Base64; -import android.util.Log; - -import androidx.annotation.Nullable; - -import com.google.android.gms.wearable.DataMap; - -import java.util.HashSet; -import java.util.Set; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.androidaps.Aaps; -import info.nightscout.androidaps.complications.BaseComplicationProviderService; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; - -/** - * Created by dlvoy on 2019-11-12 - */ -@Singleton -public class Persistence { - - private final Context context; - private final AAPSLogger aapsLogger; - private final WearUtil wearUtil; - private final SharedPreferences preferences; - private final String COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY = - "info.nightscout.androidaps.complications.COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY"; - - @Inject - public Persistence(Context context, AAPSLogger aapsLogger, WearUtil wearUtil) { - this.context = context; - this.aapsLogger = aapsLogger; - this.wearUtil = wearUtil; - preferences = context.getSharedPreferences(COMPLICATION_PROVIDER_PREFERENCES_FILE_KEY, 0); - } - - // For mocking only - public byte[] base64decode(String str, int flags) { - return Base64.decode(str, flags); - } - - // For mocking only - public String base64encodeToString(byte[] input, int flags) { - return Base64.encodeToString(input, flags); - } - - @Nullable - public DataMap getDataMap(String key) { - if (preferences.contains(key)) { - final String rawB64Data = preferences.getString(key, null); - byte[] rawData = base64decode(rawB64Data, Base64.DEFAULT); - try { - return DataMap.fromByteArray(rawData); - } catch (IllegalArgumentException ex) { - // Should never happen, and if it happen - we ignore and fallback to null - } - } - return null; - } - - public void putDataMap(String key, DataMap dataMap) { - preferences.edit().putString(key, base64encodeToString(dataMap.toByteArray(), Base64.DEFAULT)).apply(); - } - - public String getString(String key, String defaultValue) { - return preferences.getString(key, defaultValue); - } - - public void putString(String key, String value) { - preferences.edit().putString(key, value).apply(); - } - - public boolean getBoolean(String key, boolean defaultValue) { - return preferences.getBoolean(key, defaultValue); - } - - public void putBoolean(String key, boolean value) { - preferences.edit().putBoolean(key, value).apply(); - } - - public long whenDataUpdated() { - return preferences.getLong("data_updated_at", 0); - } - - private void markDataUpdated() { - preferences.edit().putLong("data_updated_at", wearUtil.timestamp()).apply(); - } - - public Set getSetOf(String key) { - return explodeSet(getString(key, ""), "|"); - } - - public void addToSet(String key, String value) { - final Set set = explodeSet(getString(key, ""), "|"); - set.add(value); - putString(key, joinSet(set, "|")); - } - - public void removeFromSet(String key, String value) { - final Set set = explodeSet(getString(key, ""), "|"); - set.remove(value); - putString(key, joinSet(set, "|")); - } - - public void storeDataMap(String key, DataMap dataMap) { - putDataMap(key, dataMap); - markDataUpdated(); - } - - public String joinSet(Set set, String separator) { - StringBuilder sb = new StringBuilder(); - int i = 0; - for (String item : set) { - final String itemToAdd = item.trim(); - if (itemToAdd.length() > 0) { - if (i > 0) { - sb.append(separator); - } - i++; - sb.append(itemToAdd); - } - } - return sb.toString(); - } - - public Set explodeSet(String joined, String separator) { - // special RegEx literal \\Q starts sequence we escape, \\E ends is - // we use it to escape separator for use in RegEx - String[] items = joined.split("\\Q"+separator+"\\E"); - Set set = new HashSet<>(); - for (String item : items) { - final String itemToAdd = item.trim(); - if (itemToAdd.length() > 0) { - set.add(itemToAdd); - } - } - return set; - } - - public void turnOff() { - aapsLogger.debug(LTag.WEAR, "TURNING OFF all active complications"); - putString(BaseComplicationProviderService.KEY_COMPLICATIONS, ""); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt new file mode 100644 index 0000000000..bfad5b3571 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/Persistence.kt @@ -0,0 +1,185 @@ +package info.nightscout.androidaps.interaction.utils + +import android.util.Base64 +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.Companion.deserialize +import info.nightscout.shared.weardata.EventData.SingleBg +import info.nightscout.shared.weardata.EventData.TreatmentData +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by dlvoy on 2019-11-12 + * Refactored by MilosKozak 25/04/2022 + */ +@Singleton +class Persistence @Inject constructor( + private val aapsLogger: AAPSLogger, + private val dateUtil: DateUtil, + private val sp: SP +) { + + companion object { + + const val BG_DATA_PERSISTENCE_KEY = "bg_data" + const val GRAPH_DATA_PERSISTENCE_KEY = "graph_data" + const val TREATMENT_PERSISTENCE_KEY = "treatment_data" + const val STATUS_PERSISTENCE_KEY = "status_data" + + const val KEY_COMPLICATIONS = "complications" + const val KEY_LAST_SHOWN_SINCE_VALUE = "lastSince" + const val KEY_STALE_REPORTED = "staleReported" + const val KEY_DATA_UPDATED = "data_updated_at" + + } + + fun getString(key: String, defaultValue: String): String { + return sp.getString(key, defaultValue) + } + + fun putString(key: String, value: String) { + sp.putString(key, value) + } + + fun getBoolean(key: String, defaultValue: Boolean): Boolean { + return sp.getBoolean(key, defaultValue) + } + + fun putBoolean(key: String, value: Boolean) { + sp.putBoolean(key, value) + } + + fun whenDataUpdated(): Long { + return sp.getLong(KEY_DATA_UPDATED, 0) + } + + private fun markDataUpdated() { + sp.putLong(KEY_DATA_UPDATED, dateUtil.now()) + } + + fun getSetOf(key: String): Set { + return explodeSet(getString(key, ""), "|") + } + + fun addToSet(key: String, value: String) { + val set = explodeSet(getString(key, ""), "|") + set.add(value) + putString(key, joinSet(set, "|")) + } + + fun removeFromSet(key: String, value: String) { + val set = explodeSet(getString(key, ""), "|") + set.remove(value) + putString(key, joinSet(set, "|")) + } + + fun readSingleBg(): SingleBg? { + try { + val s = sp.getStringOrNull(BG_DATA_PERSISTENCE_KEY, null) + //aapsLogger.debug(LTag.WEAR, "Loaded BG data: $s") + if (s != null) { + return deserialize(s) as SingleBg + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, exception.toString()) + } + return null + } + + fun readStatus(): EventData.Status? { + try { + val s = sp.getStringOrNull(STATUS_PERSISTENCE_KEY, null) + //aapsLogger.debug(LTag.WEAR, "Loaded Status data: $s") + if (s != null) { + return deserialize(s) as EventData.Status + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, exception.toString()) + } + return null + } + + fun readTreatments(): TreatmentData? { + try { + val s = sp.getStringOrNull(TREATMENT_PERSISTENCE_KEY, null) + //aapsLogger.debug(LTag.WEAR, "Loaded Treatments data: $s") + if (s != null) { + return deserialize(s) as TreatmentData + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, exception.toString()) + } + return null + } + + fun readGraphData(): EventData.GraphData? { + try { + val s = sp.getStringOrNull(GRAPH_DATA_PERSISTENCE_KEY, null) + //aapsLogger.debug(LTag.WEAR, "Loaded Graph data: $s") + if (s != null) { + return deserialize(s) as EventData.GraphData + } + } catch (exception: Exception) { + aapsLogger.error(LTag.WEAR, exception.toString()) + } + return null + } + + fun store(singleBg: SingleBg) { + putString(BG_DATA_PERSISTENCE_KEY, singleBg.serialize()) + aapsLogger.debug(LTag.WEAR, "Stored BG data: $singleBg") + markDataUpdated() + } + + fun store(graphData: EventData.GraphData) { + putString(GRAPH_DATA_PERSISTENCE_KEY, graphData.serialize()) + aapsLogger.debug(LTag.WEAR, "Stored Graph data: $graphData") + } + + fun store(treatmentData: TreatmentData) { + putString(TREATMENT_PERSISTENCE_KEY, treatmentData.serialize()) + aapsLogger.debug(LTag.WEAR, "Stored Treatments data: $treatmentData") + } + + fun store(status: EventData.Status) { + putString(STATUS_PERSISTENCE_KEY, status.serialize()) + aapsLogger.debug(LTag.WEAR, "Stored Status data: $status") + } + + fun joinSet(set: Set, separator: String?): String { + val sb = StringBuilder() + var i = 0 + for (item in set) { + val itemToAdd = item.trim { it <= ' ' } + if (itemToAdd.isNotEmpty()) { + if (i > 0) sb.append(separator) + i++ + sb.append(itemToAdd) + } + } + return sb.toString() + } + + fun explodeSet(joined: String, separator: String): MutableSet { + // special RegEx literal \\Q starts sequence we escape, \\E ends is + // we use it to escape separator for use in RegEx + val items = joined.split(Regex("\\Q$separator\\E")).toTypedArray() + val set: MutableSet = HashSet() + for (item in items) { + val itemToAdd = item.trim { it <= ' ' } + if (itemToAdd.isNotEmpty()) { + set.add(itemToAdd) + } + } + return set + } + + fun turnOff() { + aapsLogger.debug(LTag.WEAR, "TURNING OFF all active complications") + putString(KEY_COMPLICATIONS, "") + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/PlusMinusEditText.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/PlusMinusEditText.java index 429537bf07..64503f089e 100644 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/PlusMinusEditText.java +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/PlusMinusEditText.java @@ -23,17 +23,16 @@ import java.util.concurrent.TimeUnit; public class PlusMinusEditText implements View.OnKeyListener, View.OnTouchListener, View.OnClickListener, View.OnGenericMotionListener { - Integer editTextID; public TextView editText; ImageView minusImage; ImageView plusImage; Double value; - Double minValue = 0d; - Double maxValue = 1d; - Double step = 1d; + Double minValue; + Double maxValue; + Double step; NumberFormat formatter; - boolean allowZero = false; + boolean allowZero; boolean roundRobin; private int mChangeCounter = 0; @@ -50,14 +49,13 @@ public class PlusMinusEditText implements View.OnKeyListener, private int repeated = 0; private int multiplier = 1; - private final int doubleLimit = 5; - public UpdateCounterTask(boolean inc) { mInc = inc; } public void run() { Message msg = new Message(); + int doubleLimit = 5; if (repeated % doubleLimit == 0) multiplier *= 2; repeated++; msg.arg1 = multiplier; @@ -125,10 +123,6 @@ public class PlusMinusEditText implements View.OnKeyListener, return value; } - public void setStep(Double step) { - this.step = step; - } - private void inc(int multiplier) { value += step * multiplier; if (value > maxValue) { diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.java deleted file mode 100644 index a190b7e65a..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.java +++ /dev/null @@ -1,30 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.content.Context; - -import androidx.annotation.NonNull; -import android.util.AttributeSet; -import android.widget.Toast; - -import info.nightscout.androidaps.BuildConfig; -import preference.WearListPreference; - -/** - * Created by adrian on 07/08/17. - */ - -public class VersionPreference extends WearListPreference { - public VersionPreference(Context context, AttributeSet attrs) { - super(context, attrs); - entries = new CharSequence[]{BuildConfig.BUILDVERSION}; - entryValues = new CharSequence[]{BuildConfig.BUILDVERSION}; - } - - @Override public CharSequence getSummary(@NonNull final Context context) { - return BuildConfig.BUILDVERSION; - } - @Override - public void onPreferenceClick(@NonNull Context context) { - Toast.makeText(context, "Build version:" + BuildConfig.BUILDVERSION, Toast.LENGTH_LONG).show(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt new file mode 100644 index 0000000000..d63d7ca252 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/VersionPreference.kt @@ -0,0 +1,27 @@ +package info.nightscout.androidaps.interaction.utils + +import android.content.Context +import android.util.AttributeSet +import preference.WearListPreference +import android.widget.Toast +import info.nightscout.androidaps.BuildConfig + +/** + * Created by adrian on 07/08/17. + */ +@Suppress("unused") +class VersionPreference(context: Context?, attrs: AttributeSet?) : WearListPreference(context, attrs) { + + override fun getSummary(context: Context): CharSequence { + return BuildConfig.BUILDVERSION + } + + override fun onPreferenceClick(context: Context) { + Toast.makeText(context, "Build version:" + BuildConfig.BUILDVERSION, Toast.LENGTH_LONG).show() + } + + init { + entries = arrayOf(BuildConfig.BUILDVERSION) + entryValues = arrayOf(BuildConfig.BUILDVERSION) + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.java deleted file mode 100644 index eba3b79033..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.java +++ /dev/null @@ -1,33 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.content.Context; -import android.util.AttributeSet; -import android.widget.Toast; - -import androidx.annotation.NonNull; - -import preference.WearListPreference; - - -public class WatchfaceSettingsPreference extends WearListPreference { - private final String pref_moreWatchfaceSettings; - private final String pref_lookInYourWatchfaceConfiguration; - - public WatchfaceSettingsPreference(Context context, AttributeSet attrs) { - super(context, attrs); - - this.pref_moreWatchfaceSettings =context.getResources().getString(context.getResources().getIdentifier("pref_moreWatchfaceSettings", "string", context.getApplicationContext().getPackageName())); - this.pref_lookInYourWatchfaceConfiguration=context.getResources().getString(context.getResources().getIdentifier("pref_lookInYourWatchfaceConfiguration", "string", context.getApplicationContext().getPackageName())); - - entries = new CharSequence[]{pref_moreWatchfaceSettings}; - entryValues = new CharSequence[]{""}; - } - - @Override public CharSequence getSummary(@NonNull final Context context) { - return ""; - } - @Override - public void onPreferenceClick(@NonNull Context context) { - Toast.makeText(context, pref_lookInYourWatchfaceConfiguration, Toast.LENGTH_LONG).show(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.kt new file mode 100644 index 0000000000..6ae373d8e8 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WatchfaceSettingsPreference.kt @@ -0,0 +1,25 @@ +package info.nightscout.androidaps.interaction.utils + +import android.content.Context +import android.util.AttributeSet +import android.widget.Toast +import info.nightscout.androidaps.R +import preference.WearListPreference + +@Suppress("unused") +class WatchfaceSettingsPreference(context: Context, attrs: AttributeSet?) : WearListPreference(context, attrs) { + + private val prefMoreWatchfaceSettings: String = context.getString(R.string.pref_moreWatchfaceSettings) + private val prefLookInYourWatchfaceConfiguration: String = context.getString(R.string.pref_lookInYourWatchfaceConfiguration) + + override fun getSummary(context: Context): CharSequence = "" + + override fun onPreferenceClick(context: Context) { + Toast.makeText(context, prefLookInYourWatchfaceConfiguration, Toast.LENGTH_LONG).show() + } + + init { + entries = arrayOf(prefMoreWatchfaceSettings) + entryValues = arrayOf("") + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java deleted file mode 100644 index 05654ea6ea..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.java +++ /dev/null @@ -1,103 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import android.content.Context; -import android.os.Bundle; -import android.os.PowerManager; - -import com.google.android.gms.wearable.DataMap; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import javax.inject.Inject; -import javax.inject.Singleton; - -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; - -/** - * Created by andy on 3/5/19. - * Adapted by dlvoy on 2019-11-06 using code from jamorham JoH class - */ - -@Singleton -public class WearUtil { - - @Inject public Context context; - @Inject public AAPSLogger aapsLogger; - - @Inject public WearUtil() { - } - - private final boolean debug_wakelocks = false; - private final Map rateLimits = new HashMap<>(); - private final String TAG = WearUtil.class.getName(); - - //============================================================================================== - // Time related util methods - //============================================================================================== - - public String dateTimeText(long timeInMs) { - Date d = new Date(timeInMs); - return "" + d.getDay() + "." + d.getMonth() + "." + d.getYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds(); - } - - public long timestamp() { - return System.currentTimeMillis(); - } - - public long msSince(long when) { - return (timestamp() - when); - } - - public long msTill(long when) { - return (when - timestamp()); - } - - //============================================================================================== - // Thread and power management utils - //============================================================================================== - - // return true if below rate limit - public synchronized boolean isBelowRateLimit(String named, int onceForSeconds) { - // check if over limit - if ((rateLimits.containsKey(named)) && (timestamp() - rateLimits.get(named) < (onceForSeconds * 1000))) { - aapsLogger.debug(LTag.WEAR, named + " rate limited to one for " + onceForSeconds + " seconds"); - return false; - } - // not over limit - rateLimits.put(named, timestamp()); - return true; - } - - public PowerManager.WakeLock getWakeLock(final String name, int millis) { - final PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); - PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AAPS::" + name); - wl.acquire(millis); - if (debug_wakelocks) - aapsLogger.debug(LTag.WEAR, "getWakeLock: " + name + " " + wl); - return wl; - } - - public void releaseWakeLock(PowerManager.WakeLock wl) { - if (debug_wakelocks) aapsLogger.debug(LTag.WEAR, "releaseWakeLock: " + wl.toString()); - if (wl == null) return; - if (wl.isHeld()) wl.release(); - } - - public void threadSleep(long millis) { - try { - Thread.sleep(millis); - } catch (InterruptedException e) { - // we simply ignore if sleep was interrupted - } - } - - /** - * Taken out to helper method to allow testing - */ - public DataMap bundleToDataMap(Bundle bundle) { - return DataMap.fromBundle(bundle); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt new file mode 100644 index 0000000000..1311e2dce6 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/interaction/utils/WearUtil.kt @@ -0,0 +1,75 @@ +package info.nightscout.androidaps.interaction.utils + +import android.content.Context +import android.os.Bundle +import android.os.PowerManager +import com.google.android.gms.wearable.DataMap +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import javax.inject.Inject +import javax.inject.Singleton + +/** + * Created by andy on 3/5/19. + * Adapted by dlvoy on 2019-11-06 using code from jamorham JoH class + */ +@Singleton +class WearUtil @Inject constructor() { + + @Inject lateinit var context: Context + @Inject lateinit var aapsLogger: AAPSLogger + + private val debugWakelocks = false + private val rateLimits: MutableMap = HashMap() + + //============================================================================================== + // Time related util methods + //============================================================================================== + fun timestamp(): Long { + return System.currentTimeMillis() + } + + fun msSince(`when`: Long): Long { + return timestamp() - `when` + } + + fun msTill(`when`: Long): Long { + return `when` - timestamp() + } + + //============================================================================================== + // Thread and power management utils + //============================================================================================== + // return true if below rate limit + @Synchronized fun isBelowRateLimit(named: String, onceForSeconds: Int): Boolean { + // check if over limit + if (rateLimits.containsKey(named) && timestamp() - rateLimits[named]!! < onceForSeconds * 1000) { + aapsLogger.debug(LTag.WEAR, "$named rate limited to one for $onceForSeconds seconds") + return false + } + // not over limit + rateLimits[named] = timestamp() + return true + } + + fun getWakeLock(name: String, millis: Int): PowerManager.WakeLock { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + val wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AAPS::$name") + wl.acquire(millis.toLong()) + if (debugWakelocks) aapsLogger.debug(LTag.WEAR, "getWakeLock: $name $wl") + return wl + } + + fun releaseWakeLock(wl: PowerManager.WakeLock?) { + if (debugWakelocks) aapsLogger.debug(LTag.WEAR, "releaseWakeLock: " + wl.toString()) + if (wl?.isHeld == true) wl.release() + } + + fun threadSleep(millis: Long) { + try { + Thread.sleep(millis) + } catch (e: InterruptedException) { + // we simply ignore if sleep was interrupted + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/ActionSource.kt b/wear/src/main/java/info/nightscout/androidaps/tile/ActionSource.kt index 9223060e68..492c10d9ec 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/ActionSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/ActionSource.kt @@ -1,10 +1,16 @@ package info.nightscout.androidaps.tile +import android.content.Context import android.content.res.Resources import info.nightscout.androidaps.R import info.nightscout.androidaps.interaction.actions.* +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.sharedPreferences.SP +import javax.inject.Inject +import javax.inject.Singleton -object ActionSource : StaticTileSource() { +@Singleton +class ActionSource @Inject constructor(context: Context, sp : SP, aapsLogger: AAPSLogger) : StaticTileSource(context, sp, aapsLogger) { override val preferencePrefix = "tile_action_" diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/ActionsTileService.kt b/wear/src/main/java/info/nightscout/androidaps/tile/ActionsTileService.kt index b30ec2a87a..959948443a 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/ActionsTileService.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/ActionsTileService.kt @@ -1,6 +1,18 @@ package info.nightscout.androidaps.tile +import dagger.android.AndroidInjection +import javax.inject.Inject + class ActionsTileService : TileBase() { + + @Inject lateinit var actionSource: ActionSource + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + override val resourceVersion = "ActionsTileService" - override val source = ActionSource + override val source get() = actionSource } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt b/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt index 36e2f224fb..00993b09bf 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardSource.kt @@ -2,93 +2,67 @@ package info.nightscout.androidaps.tile import android.content.Context import android.content.res.Resources -import android.util.Base64 -import android.util.Log -import androidx.preference.PreferenceManager -import com.google.android.gms.wearable.DataMap import info.nightscout.androidaps.R import info.nightscout.androidaps.interaction.actions.BackgroundActionActivity +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import java.util.* +import javax.inject.Inject +import javax.inject.Singleton -object QuickWizardSource : TileSource { +@Singleton +class QuickWizardSource @Inject constructor(private val context: Context, private val sp: SP, private val aapsLogger: AAPSLogger): TileSource { - override fun getSelectedActions(context: Context): List { + override fun getSelectedActions(): List { val quickList = mutableListOf() - val quickMap = getDataMap(context) + val quickMap = getQuickWizardData(sp) val sfm = secondsFromMidnight() - for (quick in quickMap) { - val validFrom = quick.getInt("from", 0) - val validTo = quick.getInt("to", 0) - val isActive = sfm in validFrom..validTo - val guid = quick.getString("guid", "") - if (isActive && guid != "") { + for (quick in quickMap.entries) { + val isActive = sfm in quick.validFrom..quick.validTo + if (isActive && quick.guid.isNotEmpty()) { quickList.add( Action( - buttonText = quick.getString("button_text", "?"), - buttonTextSub = "${quick.getInt("carbs", 0)} g", + buttonText = quick.buttonText, + buttonTextSub = "${quick.carbs} g", iconRes = R.drawable.ic_quick_wizard, activityClass = BackgroundActionActivity::class.java.name, - actionString = "quick_wizard $guid", - message = context.resources.getString(R.string.action_quick_wizard_confirmation), + action = EventData.ActionQuickWizardPreCheck(quick.guid), + message = context.resources.getString(R.string.action_quick_wizard_confirmation) ) ) - Log.i(TAG, "getSelectedActions: active " + quick.getString("button_text", "?") + " guid=" + guid) + aapsLogger.info(LTag.WEAR, """getSelectedActions: active ${quick.buttonText} guid=${quick.guid}""") } else { - Log.i(TAG, "getSelectedActions: not active " + quick.getString("button_text", "?") + " guid=" + guid) + aapsLogger.info(LTag.WEAR, """getSelectedActions: not active ${quick.buttonText} guid=${quick.guid}""") } - } - return quickList } - override fun getValidFor(context: Context): Long? { - val quickMap = getDataMap(context) - if (quickMap.size == 0) { - return null - } + override fun getValidFor(): Long? { + val quickMap = getQuickWizardData(sp) + if (quickMap.entries.size == 0) return null + val sfm = secondsFromMidnight() var validTill = 24 * 60 * 60 - for (quick in quickMap) { - val validFrom = quick.getInt("from", 0) - val validTo = quick.getInt("to", 0) - val isActive = sfm in validFrom..validTo - val guid = quick.getString("guid", "") - Log.i(TAG, "valid: " + validFrom + "-" + validTo) - if (guid != "") { - if (isActive && validTill > validTo) { - validTill = validTo - } - if (validFrom > sfm && validTill > validFrom) { - validTill = validFrom - } + for (quick in quickMap.entries) { + val isActive = sfm in quick.validFrom..quick.validTo + if (quick.guid.isNotEmpty()) { + if (isActive && validTill > quick.validTo) validTill = quick.validTo + if (quick.validFrom in (sfm + 1) until validTill) validTill = quick.validFrom } } val validWithin = 60 - val delta = (validTill - sfm + validWithin) * 1000L - Log.i(TAG, "getValidTill: sfm" + sfm + " till" + validTill + " d=" + delta) - return delta + //aapsLogger.info(LTag.WEAR, "getValidTill: sfm$sfm till$validTill d=$delta") + return (validTill - sfm + validWithin) * 1000L } - private fun getDataMap(context: Context): ArrayList { - val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context) - val key = context.resources.getString(R.string.key_quick_wizard_data_map) - if (sharedPrefs.contains(key)) { - val rawB64Data: String? = sharedPrefs.getString(key, null) - val rawData: ByteArray = Base64.decode(rawB64Data, Base64.DEFAULT) - try { - val map = DataMap.fromByteArray(rawData) - return map.getDataMapArrayList("quick_wizard") - - } catch (ex: IllegalArgumentException) { - Log.e(TAG, "getSelectedActions: IllegalArgumentException ", ex) - } - } - return arrayListOf() - } + private fun getQuickWizardData(sp: SP): EventData.QuickWizard = + EventData.deserialize(sp.getString(R.string.key_quick_wizard_data, EventData.QuickWizard(arrayListOf()).serialize())) as EventData.QuickWizard private fun secondsFromMidnight(): Int { val c = Calendar.getInstance() @@ -101,8 +75,5 @@ object QuickWizardSource : TileSource { return (passed / 1000).toInt() } - override fun getResourceReferences(resources: Resources): List { - return listOf(R.drawable.ic_quick_wizard) - } - + override fun getResourceReferences(resources: Resources): List = listOf(R.drawable.ic_quick_wizard) } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardTileService.kt b/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardTileService.kt index ef85e789a7..7dfc32a540 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardTileService.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/QuickWizardTileService.kt @@ -1,8 +1,18 @@ package info.nightscout.androidaps.tile -const val TAG = "QuickWizard" +import dagger.android.AndroidInjection +import javax.inject.Inject class QuickWizardTileService : TileBase() { + + @Inject lateinit var quickWizardSource: QuickWizardSource + + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + override val resourceVersion = "QuickWizardTileService" - override val source = QuickWizardSource + override val source get() = quickWizardSource } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt b/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt index c1f369275c..93d29d6927 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/StaticTileSource.kt @@ -4,32 +4,33 @@ import android.content.Context import android.content.SharedPreferences import android.content.res.Resources import androidx.annotation.DrawableRes -import androidx.preference.PreferenceManager +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData -class StaticAction( - val settingName: String, - buttonText: String, - buttonTextSub: String? = null, - activityClass: String, - @DrawableRes iconRes: Int, - actionString: String? = null, - message: String? = null, -) : Action(buttonText, buttonTextSub, activityClass, iconRes, actionString, message) +abstract class StaticTileSource(val context: Context, val sp: SP, val aapsLogger: AAPSLogger) : TileSource { -abstract class StaticTileSource : TileSource { + class StaticAction( + val settingName: String, + buttonText: String, + buttonTextSub: String? = null, + activityClass: String, + @DrawableRes iconRes: Int, + action: EventData? = null, + message: String? = null, + ) : Action(buttonText, buttonTextSub, activityClass, iconRes, action, message) abstract fun getActions(resources: Resources): List abstract val preferencePrefix: String abstract fun getDefaultConfig(): Map - override fun getSelectedActions(context: Context): List { - val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context) - setDefaultSettings(sharedPrefs) + override fun getSelectedActions(): List { + setDefaultSettings() val actionList: MutableList = mutableListOf() for (i in 1..4) { - val action = getActionFromPreference(context.resources, sharedPrefs, i) + val action = getActionFromPreference(i) if (action != null) { actionList.add(action) } @@ -40,23 +41,20 @@ abstract class StaticTileSource : TileSource { return actionList } - override fun getValidFor(context: Context): Long? = null + override fun getValidFor(): Long? = null - private fun getActionFromPreference(resources: Resources, sharedPrefs: SharedPreferences, index: Int): Action? { - val actionPref = sharedPrefs.getString(preferencePrefix + index, "none") - return getActions(resources).find { action -> action.settingName == actionPref } + private fun getActionFromPreference(index: Int): Action? { + val actionPref = sp.getString(preferencePrefix + index, "none") + return getActions(context.resources).find { action -> action.settingName == actionPref } } - private fun setDefaultSettings(sharedPrefs: SharedPreferences) { + private fun setDefaultSettings() { val defaults = getDefaultConfig() val firstKey = defaults.firstNotNullOf { settings -> settings.key } - if (!sharedPrefs.contains(firstKey)) { - val editor = sharedPrefs.edit() + if (!sp.contains(firstKey)) { for ((key, value) in defaults) { - editor.putString(key, value) + sp.putString(key, value) } - editor.apply() } } - } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt index 75cdbca36c..3ebbfdc7e2 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetSource.kt @@ -1,11 +1,18 @@ package info.nightscout.androidaps.tile +import android.content.Context import android.content.res.Resources import info.nightscout.androidaps.R import info.nightscout.androidaps.interaction.actions.BackgroundActionActivity import info.nightscout.androidaps.interaction.actions.TempTargetActivity +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import javax.inject.Inject +import javax.inject.Singleton -object TempTargetSource : StaticTileSource() { +@Singleton +class TempTargetSource @Inject constructor(context: Context, sp: SP, aapsLogger: AAPSLogger) : StaticTileSource(context, sp, aapsLogger) { override val preferencePrefix = "tile_tempt_" @@ -19,7 +26,8 @@ object TempTargetSource : StaticTileSource() { activityClass = BackgroundActionActivity::class.java.name, message = message, // actionString = "temptarget false 90 8.0 8.0", - actionString = "temptarget preset activity", + // actionString = "temptarget preset activity", + action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_ACTIVITY) ), StaticAction( settingName = "eating_soon", @@ -28,7 +36,8 @@ object TempTargetSource : StaticTileSource() { activityClass = BackgroundActionActivity::class.java.name, message = message, // actionString = "temptarget false 45 4.5 4.5", - actionString = "temptarget preset eating", + // actionString = "temptarget preset eating", + action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_EATING) ), StaticAction( settingName = "hypo", @@ -37,13 +46,15 @@ object TempTargetSource : StaticTileSource() { activityClass = BackgroundActionActivity::class.java.name, message = message, // actionString = "temptarget false 45 7.0 7.0", - actionString = "temptarget preset hypo", + // actionString = "temptarget preset hypo", + action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.PRESET_HYPO) ), StaticAction( settingName = "manual", buttonText = resources.getString(R.string.temp_target_manual), iconRes = R.drawable.ic_target_manual, activityClass = TempTargetActivity::class.java.name, + action = null ), StaticAction( settingName = "cancel", @@ -51,7 +62,8 @@ object TempTargetSource : StaticTileSource() { iconRes = R.drawable.ic_target_cancel, activityClass = BackgroundActionActivity::class.java.name, message = message, - actionString = "temptarget cancel", + //actionString = "temptarget cancel", + action = EventData.ActionTempTargetPreCheck(EventData.ActionTempTargetPreCheck.TempTargetCommand.CANCEL) ) ) } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt index e15b4d2dca..8b17893ac1 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TempTargetTileService.kt @@ -1,8 +1,18 @@ package info.nightscout.androidaps.tile +import dagger.android.AndroidInjection +import javax.inject.Inject + class TempTargetTileService : TileBase() { - override val resourceVersion = "TempTargetTileService" - override val source = TempTargetSource + @Inject lateinit var tempTargetSource: TempTargetSource + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + + override val resourceVersion = "TempTargetTileService" + override val source get() = tempTargetSource } diff --git a/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt b/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt index 031dbf223e..4bf01205fe 100644 --- a/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt +++ b/wear/src/main/java/info/nightscout/androidaps/tile/TileBase.kt @@ -1,15 +1,13 @@ package info.nightscout.androidaps.tile -import android.content.Context import android.os.Build import androidx.annotation.DrawableRes import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat -import androidx.preference.PreferenceManager import androidx.wear.tiles.ActionBuilders import androidx.wear.tiles.ColorBuilders.argb -import androidx.wear.tiles.DeviceParametersBuilders.SCREEN_SHAPE_ROUND import androidx.wear.tiles.DeviceParametersBuilders.DeviceParameters +import androidx.wear.tiles.DeviceParametersBuilders.SCREEN_SHAPE_ROUND import androidx.wear.tiles.DimensionBuilders.SpProp import androidx.wear.tiles.DimensionBuilders.dp import androidx.wear.tiles.DimensionBuilders.sp @@ -29,11 +27,17 @@ import androidx.wear.tiles.TileService import androidx.wear.tiles.TimelineBuilders.Timeline import androidx.wear.tiles.TimelineBuilders.TimelineEntry import com.google.common.util.concurrent.ListenableFuture +import dagger.android.AndroidInjection import info.nightscout.androidaps.R +import info.nightscout.androidaps.comm.DataLayerListenerServiceWear +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.guava.future +import javax.inject.Inject import kotlin.math.sqrt private const val SPACING_ACTIONS = 3f @@ -44,8 +48,8 @@ private const val LARGE_SCREEN_WIDTH_DP = 210 interface TileSource { fun getResourceReferences(resources: android.content.res.Resources): List - fun getSelectedActions(context: Context): List - fun getValidFor(context: Context): Long? + fun getSelectedActions(): List + fun getValidFor(): Long? } open class Action( @@ -53,7 +57,7 @@ open class Action( val buttonTextSub: String? = null, val activityClass: String, @DrawableRes val iconRes: Int, - val actionString: String? = null, + val action: EventData? = null, val message: String? = null, ) @@ -63,12 +67,21 @@ enum class WearControl { abstract class TileBase : TileService() { + @Inject lateinit var sp: SP + @Inject lateinit var aapsLogger: AAPSLogger + abstract val resourceVersion: String abstract val source: TileSource private val serviceJob = Job() private val serviceScope = CoroutineScope(Dispatchers.IO + serviceJob) + // Not derived from DaggerService, do injection here + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + } + override fun onTileRequest( requestParams: RequestBuilders.TileRequest ): ListenableFuture = serviceScope.future { @@ -93,11 +106,11 @@ abstract class TileBase : TileService() { private fun getSelectedActions(): List { // TODO check why thi scan not be don in scope of the coroutine - return source.getSelectedActions(this) + return source.getSelectedActions() } private fun validFor(): Long? { - return source.getValidFor(this) + return source.getValidFor() } @RequiresApi(Build.VERSION_CODES.N) @@ -172,13 +185,13 @@ abstract class TileBase : TileService() { val builder = ActionBuilders.AndroidActivity.Builder() .setClassName(action.activityClass) .setPackageName(this.packageName) - if (action.actionString != null) { - val actionString = ActionBuilders.AndroidStringExtra.Builder().setValue(action.actionString).build() - builder.addKeyToExtraMapping("actionString", actionString) + if (action.action != null) { + val actionString = ActionBuilders.AndroidStringExtra.Builder().setValue(action.action.serialize()).build() + builder.addKeyToExtraMapping(DataLayerListenerServiceWear.KEY_ACTION, actionString) } if (action.message != null) { val message = ActionBuilders.AndroidStringExtra.Builder().setValue(action.message).build() - builder.addKeyToExtraMapping("message", message) + builder.addKeyToExtraMapping(DataLayerListenerServiceWear.KEY_MESSAGE, message) } return ActionBuilders.LaunchAction.Builder() @@ -197,12 +210,8 @@ abstract class TileBase : TileService() { Modifiers.Builder() .setBackground( Background.Builder() - .setColor( - argb(ContextCompat.getColor(baseContext, BUTTON_COLOR)) - ) - .setCorner( - Corner.Builder().setRadius(dp(circleDiameter / 2)).build() - ) + .setColor(argb(ContextCompat.getColor(baseContext, BUTTON_COLOR))) + .setCorner(Corner.Builder().setRadius(dp(circleDiameter / 2)).build()) .build() ) .setSemantics( @@ -239,9 +248,7 @@ abstract class TileBase : TileService() { .setFontStyle( FontStyle.Builder() .setWeight(FONT_WEIGHT_BOLD) - .setColor( - argb(ContextCompat.getColor(baseContext, R.color.white)) - ) + .setColor(argb(ContextCompat.getColor(baseContext, R.color.white))) .setSize(buttonTextSize(deviceParameters, text)) .build() ) @@ -253,9 +260,7 @@ abstract class TileBase : TileService() { .setText(textSub) .setFontStyle( FontStyle.Builder() - .setColor( - argb(ContextCompat.getColor(baseContext, R.color.white)) - ) + .setColor(argb(ContextCompat.getColor(baseContext, R.color.white))) .setSize(buttonTextSize(deviceParameters, textSub)) .build() ) @@ -283,11 +288,10 @@ abstract class TileBase : TileService() { } private fun getWearControl(): WearControl { - val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this) - if (!sharedPrefs.contains("wearcontrol")) { + if (!sp.contains(R.string.key_wear_control)) { return WearControl.NO_DATA } - val wearControlPref = sharedPrefs.getBoolean("wearcontrol", false) + val wearControlPref = sp.getBoolean(R.string.key_wear_control, false) if (wearControlPref) { return WearControl.ENABLED } diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt new file mode 100644 index 0000000000..39e7252498 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsLargeWatchface.kt @@ -0,0 +1,116 @@ +package info.nightscout.androidaps.watchfaces + +import android.graphics.Color +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R + +class AapsLargeWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_home_large + + override fun setColorDark() { + mLinearLayout?.setBackgroundColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_background else R.color.dark_mLinearLayout)) + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mTimestamp1_home)) + else mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_uploaderBattery)) + else mUploaderBattery?.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)) + + mStatus?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mStatus_home)) + } + + override fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mLinearLayout?.setBackgroundColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.light_background else R.color.light_stripe_background)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + else mTimestamp?.setTextColor(Color.RED) + + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + else mUploaderBattery?.setTextColor(Color.RED) + + mStatus?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + mTime?.setTextColor(Color.BLACK) + } else { + mRelativeLayout?.setBackgroundColor(Color.BLACK) + mLinearLayout?.setBackgroundColor(if (dividerMatchesBg) Color.BLACK else Color.LTGRAY) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(Color.YELLOW) + mDirection?.setTextColor(Color.YELLOW) + mDelta?.setTextColor(Color.YELLOW) + } + + 0L -> { + mSgv?.setTextColor(Color.WHITE) + mDirection?.setTextColor(Color.WHITE) + mDelta?.setTextColor(Color.WHITE) + } + + -1L -> { + mSgv?.setTextColor(Color.RED) + mDirection?.setTextColor(Color.RED) + mDelta?.setTextColor(Color.RED) + } + } + mUploaderBattery?.setTextColor(if (dividerMatchesBg) Color.WHITE else Color.BLACK) + mTimestamp?.setTextColor(if (dividerMatchesBg) Color.WHITE else Color.BLACK) + mStatus?.setTextColor(if (dividerMatchesBg) Color.WHITE else Color.BLACK) + mTime?.setTextColor(Color.WHITE) + } + } + + override fun setColorLowRes() { + mLinearLayout?.setBackgroundColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_background else R.color.dark_mLinearLayout)) + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTimestamp?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mTimestamp1_home)) + mUploaderBattery?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_uploaderBattery)) + mStatus?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mStatus_home)) + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt new file mode 100644 index 0000000000..5665af5c09 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsV2Watchface.kt @@ -0,0 +1,181 @@ +package info.nightscout.androidaps.watchfaces + +import android.graphics.Color +import androidx.annotation.ColorInt +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R + +class AapsV2Watchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_home_2 + + override fun setColorDark() { + @ColorInt val dividerTxtColor = if (dividerMatchesBg) ContextCompat.getColor(this, R.color.dark_midColor) else Color.BLACK + @ColorInt val dividerBatteryOkColor = ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_uploaderBattery) + @ColorInt val dividerBgColor = ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_background else R.color.dark_statusView) + mLinearLayout?.setBackgroundColor(dividerBgColor) + mLinearLayout2?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mIOB1?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mIOB2?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mCOB1?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mCOB2?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDay?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mMonth?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mLoop?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + setTextSizes() + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + else mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(dividerBatteryOkColor) + else mUploaderBattery?.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)) + + mRigBattery?.setTextColor(dividerTxtColor) + mDelta?.setTextColor(dividerTxtColor) + mAvgDelta?.setTextColor(dividerTxtColor) + mBasalRate?.setTextColor(dividerTxtColor) + mBgi?.setTextColor(dividerTxtColor) + when (loopLevel) { + -1 -> mLoop?.setBackgroundResource(R.drawable.loop_grey_25) + 1 -> mLoop?.setBackgroundResource(R.drawable.loop_green_25) + else -> mLoop?.setBackgroundResource(R.drawable.loop_red_25) + } + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_highColor) + lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) + pointSize = 2 + setupCharts() + } + } + + override fun setColorLowRes() { + @ColorInt val dividerTxtColor = if (dividerMatchesBg) ContextCompat.getColor(this, R.color.dark_midColor) else Color.BLACK + @ColorInt val dividerBgColor = ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_background else R.color.dark_statusView) + mLinearLayout?.setBackgroundColor(dividerBgColor) + mLinearLayout2?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mLoop?.setBackgroundResource(R.drawable.loop_grey_25) + mLoop?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + mDelta?.setTextColor(dividerTxtColor) + mAvgDelta?.setTextColor(dividerTxtColor) + mRigBattery?.setTextColor(dividerTxtColor) + mUploaderBattery?.setTextColor(dividerTxtColor) + mBasalRate?.setTextColor(dividerTxtColor) + mBgi?.setTextColor(dividerTxtColor) + mIOB1?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mIOB2?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mCOB1?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mCOB2?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDay?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mMonth?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_midColor) + lowColor = ContextCompat.getColor(this, R.color.dark_midColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark_lowres) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light_lowres) + pointSize = 2 + setupCharts() + } + setTextSizes() + } + + override fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + @ColorInt val dividerTxtColor = if (dividerMatchesBg) Color.BLACK else ContextCompat.getColor(this, R.color.dark_midColor) + @ColorInt val dividerBgColor = ContextCompat.getColor(this, if (dividerMatchesBg) R.color.light_background else R.color.light_stripe_background) + mLinearLayout?.setBackgroundColor(dividerBgColor) + mLinearLayout2?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + mTime?.setTextColor(Color.BLACK) + mIOB1?.setTextColor(Color.BLACK) + mIOB2?.setTextColor(Color.BLACK) + mCOB1?.setTextColor(Color.BLACK) + mCOB2?.setTextColor(Color.BLACK) + mDay?.setTextColor(Color.BLACK) + mMonth?.setTextColor(Color.BLACK) + mLoop?.setTextColor(Color.BLACK) + setTextSizes() + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(Color.BLACK) + else mTimestamp?.setTextColor(Color.RED) + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(dividerTxtColor) + else mUploaderBattery?.setTextColor(Color.RED) + mRigBattery?.setTextColor(dividerTxtColor) + mDelta?.setTextColor(dividerTxtColor) + mAvgDelta?.setTextColor(dividerTxtColor) + mBasalRate?.setTextColor(dividerTxtColor) + mBgi?.setTextColor(dividerTxtColor) + when (loopLevel) { + -1 -> mLoop?.setBackgroundResource(R.drawable.loop_grey_25) + 1 -> mLoop?.setBackgroundResource(R.drawable.loop_green_25) + else -> mLoop?.setBackgroundResource(R.drawable.loop_red_25) + } + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.light_highColor) + lowColor = ContextCompat.getColor(this, R.color.light_lowColor) + midColor = ContextCompat.getColor(this, R.color.light_midColor) + gridColor = ContextCompat.getColor(this, R.color.light_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_light) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) + pointSize = 2 + setupCharts() + } + } else { + setColorDark() + } + } + + private fun setTextSizes() { + if (status.detailedIob) { + mIOB1?.textSize = 14f + mIOB2?.textSize = 10f + } else { + mIOB1?.textSize = 10f + mIOB2?.textSize = 14f + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt new file mode 100644 index 0000000000..48e457a3d1 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/AapsWatchface.kt @@ -0,0 +1,114 @@ +package info.nightscout.androidaps.watchfaces + +import android.graphics.Color +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R + +class AapsWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_home + + override fun setColorDark() { + mLinearLayout?.setBackgroundColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_background else R.color.dark_statusView)) + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mTimestamp1_home)) + else mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_uploaderBattery)) + else mUploaderBattery?.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)) + mStatus?.setTextColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.dark_midColor else R.color.dark_mStatus_home)) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_highColor) + lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) + pointSize = 2 + setupCharts() + } + } + + override fun setColorLowRes() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_midColor) + lowColor = ContextCompat.getColor(this, R.color.dark_midColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark_lowres) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light_lowres) + pointSize = 2 + setupCharts() + } + } + + override fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mLinearLayout?.setBackgroundColor(ContextCompat.getColor(this, if (dividerMatchesBg) R.color.light_background else R.color.light_stripe_background)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + else mTimestamp?.setTextColor(Color.RED) + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + else mUploaderBattery?.setTextColor(Color.RED) + mStatus?.setTextColor(if (dividerMatchesBg) Color.BLACK else Color.WHITE) + mTime?.setTextColor(Color.BLACK) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.light_highColor) + lowColor = ContextCompat.getColor(this, R.color.light_lowColor) + midColor = ContextCompat.getColor(this, R.color.light_midColor) + gridColor = ContextCompat.getColor(this, R.color.light_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_light) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) + pointSize = 2 + setupCharts() + } + } else { + setColorDark() + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java deleted file mode 100644 index 73fcac445a..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BIGChart.java +++ /dev/null @@ -1,696 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.LinearGradient; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.Rect; -import android.graphics.Shader; -import android.os.Bundle; -import android.os.PowerManager; -import android.os.SystemClock; -import android.preference.PreferenceManager; -import androidx.core.content.ContextCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import android.support.wearable.view.WatchViewStub; -import android.support.wearable.watchface.WatchFaceStyle; -import android.text.format.DateFormat; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.Display; -import android.view.LayoutInflater; -import android.view.View; -import android.view.WindowInsets; -import android.view.WindowManager; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.google.android.gms.wearable.DataMap; -import com.ustwo.clockwise.common.WatchFaceTime; -import com.ustwo.clockwise.common.WatchMode; -import com.ustwo.clockwise.common.WatchShape; -import com.ustwo.clockwise.wearable.WatchFace; - -import java.util.ArrayList; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.BasalWatchData; -import info.nightscout.androidaps.data.BgWatchData; -import info.nightscout.androidaps.data.BolusWatchData; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.data.TempWatchData; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -import lecho.lib.hellocharts.view.LineChartView; - -/** - * Created by adrianLxM. - */ -public class BIGChart extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { - public final static IntentFilter INTENT_FILTER; - public static final int SCREENSIZE_SMALL = 280; - public TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; - public RelativeLayout mRelativeLayout; - public long sgvLevel = 0; - public int batteryLevel = 1; - public int ageLevel = 1; - public int highColor = Color.YELLOW; - public int lowColor = Color.RED; - public int midColor = Color.WHITE; - public int gridColour = Color.WHITE; - public int basalBackgroundColor = Color.BLUE; - public int basalCenterColor = Color.BLUE; - public int bolusColor = Color.MAGENTA; - public int carbsColor = Color.GREEN; - public int pointSize = 2; - public boolean lowResMode = false; - public boolean layoutSet = false; - public BgGraphBuilder bgGraphBuilder; - public LineChartView chart; - public long datetime; - public ArrayList bgDataList = new ArrayList<>(); - public ArrayList tempWatchDataList = new ArrayList<>(); - public ArrayList basalWatchDataList = new ArrayList<>(); - public ArrayList bolusWatchDataList = new ArrayList<>(); - public ArrayList predictionList = new ArrayList<>(); - - public PowerManager.WakeLock wakeLock; - public View layoutView; - private final Point displaySize = new Point(); - private int specW, specH; - private int animationAngle = 0; - private boolean isAnimated = false; - - private LocalBroadcastManager localBroadcastManager; - private MessageReceiver messageReceiver; - - protected SharedPreferences sharedPrefs; - private String rawString = "000 | 000 | 000"; - private String batteryString = "--"; - private String sgvString = "--"; - private String externalStatusString = "no status"; - private String cobString = ""; - - private TextView statusView; - private long chartTapTime = 0L; - private long sgvTapTime = 0L; - - @Override - public void onCreate() { - super.onCreate(); - Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay(); - display.getSize(displaySize); - wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:BIGChart"); - - specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, - View.MeasureSpec.EXACTLY); - specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, - View.MeasureSpec.EXACTLY); - sharedPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - sharedPrefs.registerOnSharedPreferenceChangeListener(this); - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - DisplayMetrics metrics = getResources().getDisplayMetrics(); - if(metrics.widthPixels < SCREENSIZE_SMALL || metrics.heightPixels < SCREENSIZE_SMALL){ - layoutView = inflater.inflate(R.layout.activity_bigchart_small, null); - } else { - layoutView = inflater.inflate(R.layout.activity_bigchart, null); - } - performViewSetup(); - } - - @Override - protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { - super.onLayout(shape, screenBounds, screenInsets); - layoutView.onApplyWindowInsets(screenInsets); - } - - public void performViewSetup() { - final WatchViewStub stub = layoutView.findViewById(R.id.watch_view_stub); - IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); - - messageReceiver = new MessageReceiver(); - localBroadcastManager = LocalBroadcastManager.getInstance(this); - localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - - stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { - @Override - public void onLayoutInflated(WatchViewStub stub) { - mTime = stub.findViewById(R.id.watch_time); - mSgv = stub.findViewById(R.id.sgv); - mTimestamp = stub.findViewById(R.id.timestamp); - mDelta = stub.findViewById(R.id.delta); - mAvgDelta = stub.findViewById(R.id.avgdelta); - mRelativeLayout = stub.findViewById(R.id.main_layout); - chart = stub.findViewById(R.id.chart); - statusView = stub.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - }); - ListenerService.requestData(this); - wakeLock.acquire(50); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; - - if (tapType == TAP_TYPE_TAP&& - x >=chart.getLeft() && - x <= chart.getRight()&& - y >= chart.getTop() && - y <= chart.getBottom()){ - if (eventTime - chartTapTime < 800){ - changeChartTimeframe(); - } - chartTapTime = eventTime; - } else if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& - y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe%5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); - } - - protected void onWatchModeChanged(WatchMode watchMode) { - - if(lowResMode ^ isLowRes(watchMode)){ //if there was a change in lowResMode - lowResMode = isLowRes(watchMode); - setColor(); - } else if (! sharedPrefs.getBoolean("dark", true)){ - //in bright mode: different colours if active: - setColor(); - } - } - - private boolean isLowRes(WatchMode watchMode) { - return (watchMode == WatchMode.LOW_BIT) || (watchMode == WatchMode.LOW_BIT_BURN_IN); - } - - - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - - - public int ageLevel() { - if(timeSince() <= (1000 * 60 * 12)) { - return 1; - } else { - return 0; - } - } - - public double timeSince() { - return System.currentTimeMillis() - datetime; - } - - public String readingAge(boolean shortString) { - if (datetime == 0) { return shortString?"--'":"-- Minute ago"; } - int minutesAgo = (int) Math.floor(timeSince()/(1000*60)); - if (minutesAgo == 1) { - return minutesAgo + (shortString?"'":" Minute ago"); - } - return minutesAgo + (shortString?"'":" Minutes ago"); - } - - @Override - public void onDestroy() { - if(localBroadcastManager != null && messageReceiver != null){ - localBroadcastManager.unregisterReceiver(messageReceiver);} - if (sharedPrefs != null){ - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } - super.onDestroy(); - } - - static { - INTENT_FILTER = new IntentFilter(); - INTENT_FILTER.addAction(Intent.ACTION_TIME_TICK); - INTENT_FILTER.addAction(Intent.ACTION_TIMEZONE_CHANGED); - INTENT_FILTER.addAction(Intent.ACTION_TIME_CHANGED); - } - - @Override - protected void onDraw(Canvas canvas) { - if(layoutSet) { - this.mRelativeLayout.draw(canvas); - Log.d("onDraw", "draw"); - } - } - - @Override - protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) { - if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - wakeLock.acquire(50); - final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this); - mTime.setText(timeFormat.format(System.currentTimeMillis())); - showAgeAndStatus(); - - if(ageLevel()<=0) { - mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - - missedReadingAlert(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - } - - public class MessageReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - Bundle bundle = intent.getBundleExtra("data"); - if (layoutSet && bundle !=null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(50); - sgvLevel = dataMap.getLong("sgvLevel"); - batteryLevel = dataMap.getInt("batteryLevel"); - datetime = dataMap.getLong("timestamp"); - rawString = dataMap.getString("rawString"); - sgvString = dataMap.getString("sgvString"); - batteryString = dataMap.getString("battery"); - mSgv.setText(dataMap.getString("sgvString")); - - if(ageLevel()<=0) { - mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - - final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(BIGChart.this); - mTime.setText(timeFormat.format(System.currentTimeMillis())); - - showAgeAndStatus(); - - String delta = dataMap.getString("delta"); - - if (delta.endsWith(" mg/dl")) { - mDelta.setText(delta.substring(0, delta.length() - 6)); - } else if (delta.endsWith(" mmol/l")||delta.endsWith(" mmol")) { - mDelta.setText(delta.substring(0, delta.length() - 5)); - } else { - mDelta.setText(delta); - } - - - String avgDelta = dataMap.getString("avgDelta"); - - if (delta.endsWith(" mg/dl")) { - mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 6)); - } else if (avgDelta.endsWith(" mmol/l")||avgDelta.endsWith(" mmol")) { - mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 5)); - } else { - mAvgDelta.setText(avgDelta); - } - - if (chart != null) { - addToWatchSet(dataMap); - setupCharts(); - } - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - - //start animation? - // dataMap.getDataMapArrayList("entries") == null -> not on "resend data". - if (!lowResMode && (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (sgvString.equals("100") || sgvString.equals("5.5") || sgvString.equals("5,5")))) { - startAnimation(); - } - } - //status - bundle = intent.getBundleExtra("status"); - if (layoutSet && bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(50); - externalStatusString = dataMap.getString("externalStatusString"); - cobString = dataMap.getString("cob"); - - - showAgeAndStatus(); - - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - } - //basals and temps - bundle = intent.getBundleExtra("basals"); - if (layoutSet && bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(500); - - loadBasalsAndTemps(dataMap); - - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - } - } - } - - private void loadBasalsAndTemps(DataMap dataMap) { - ArrayList temps = dataMap.getDataMapArrayList("temps"); - if (temps != null) { - tempWatchDataList = new ArrayList<>(); - for (DataMap temp : temps) { - TempWatchData twd = new TempWatchData(); - twd.startTime = temp.getLong("starttime"); - twd.startBasal = temp.getDouble("startBasal"); - twd.endTime = temp.getLong("endtime"); - twd.endBasal = temp.getDouble("endbasal"); - twd.amount = temp.getDouble("amount"); - tempWatchDataList.add(twd); - } - } - ArrayList basals = dataMap.getDataMapArrayList("basals"); - if (basals != null) { - basalWatchDataList = new ArrayList<>(); - for (DataMap basal : basals) { - BasalWatchData bwd = new BasalWatchData(); - bwd.startTime = basal.getLong("starttime"); - bwd.endTime = basal.getLong("endtime"); - bwd.amount = basal.getDouble("amount"); - basalWatchDataList.add(bwd); - } - } - ArrayList boluses = dataMap.getDataMapArrayList("boluses"); - if (boluses != null) { - bolusWatchDataList = new ArrayList<>(); - for (DataMap bolus : boluses) { - BolusWatchData bwd = new BolusWatchData(); - bwd.date = bolus.getLong("date"); - bwd.bolus = bolus.getDouble("bolus"); - bwd.carbs = bolus.getDouble("carbs"); - bwd.isSMB = bolus.getBoolean("isSMB"); - bwd.isValid = bolus.getBoolean("isValid"); - bolusWatchDataList.add(bwd); - } - } - ArrayList predictions = dataMap.getDataMapArrayList("predictions"); - if (boluses != null) { - predictionList = new ArrayList<>(); - for (DataMap prediction : predictions) { - BgWatchData bwd = new BgWatchData(); - bwd.timestamp = prediction.getLong("timestamp"); - bwd.sgv = prediction.getDouble("sgv"); - bwd.color = prediction.getInt("color"); - predictionList.add(bwd); - } - } - } - - private void showAgeAndStatus() { - - if( mTimestamp != null){ - mTimestamp.setText(readingAge(true)); - } - - boolean showStatus = sharedPrefs.getBoolean("showExternalStatus", true); - boolean showAvgDelta = sharedPrefs.getBoolean("showAvgDelta", true); - - if(showAvgDelta){ - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - - if(showStatus){ - String status = externalStatusString; - if (sharedPrefs.getBoolean("show_cob", true)) { - status = externalStatusString + " " + cobString; - } - - statusView.setText(status); - statusView.setVisibility(View.VISIBLE); - } else { - statusView.setVisibility(View.GONE); - } - } - - public void setColor() { - if(lowResMode){ - setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - - } - - - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){ - setColor(); - if(layoutSet){ - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - invalidate(); - } - - protected void updateRainbow() { - animationAngle = (animationAngle + 1) % 360; - //Animation matrix: - int[] rainbow = {Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE - , Color.CYAN}; - Shader shader = new LinearGradient(0, 0, 0, 20, rainbow, - null, Shader.TileMode.MIRROR); - Matrix matrix = new Matrix(); - matrix.setRotate(animationAngle); - shader.setLocalMatrix(matrix); - mSgv.getPaint().setShader(shader); - invalidate(); - } - - private synchronized boolean isAnimated() { - return isAnimated; - } - - private synchronized void setIsAnimated(boolean isAnimated) { - this.isAnimated = isAnimated; - } - - void startAnimation() { - Log.d("CircleWatchface", "start startAnimation"); - - Thread animator = new Thread() { - - - public void run() { - setIsAnimated(true); - for (int i = 0; i <= 8 * 1000 / 40; i++) { - updateRainbow(); - SystemClock.sleep(40); - } - mSgv.getPaint().setShader(null); - setIsAnimated(false); - invalidate(); - setColor(); - - System.gc(); - } - }; - - animator.start(); - } - - protected void setColorLowRes() { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColour = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark_lowres); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light_lowres); - pointSize = 2; - setupCharts(); - } - - } - - protected void setColorDark() { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - if (sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColour = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - pointSize = 2; - setupCharts(); - } - - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_time)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_status)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - if (sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp1)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp)); - } - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.light_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.light_midColor); - gridColour = ContextCompat.getColor(getApplicationContext(), R.color.light_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - pointSize = 2; - setupCharts(); - } - } else { - setColorDark(); - } - } - - public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince()/(1000*60)); - if(minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - ListenerService.requestData(this); // attempt endTime recover missing data - } - } - - public void addToWatchSet(DataMap dataMap) { - - ArrayList entries = dataMap.getDataMapArrayList("entries"); - if (entries != null) { - bgDataList = new ArrayList(); - for (DataMap entry : entries) { - double sgv = entry.getDouble("sgvDouble"); - double high = entry.getDouble("high"); - double low = entry.getDouble("low"); - long timestamp = entry.getLong("timestamp"); - int color = entry.getInt("color", 0); - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } - } else { - double sgv = dataMap.getDouble("sgvDouble"); - double high = dataMap.getDouble("high"); - double low = dataMap.getDouble("low"); - long timestamp = dataMap.getLong("timestamp"); - int color = dataMap.getInt("color", 0); - - final int size = bgDataList.size(); - if (size > 0) { - if (bgDataList.get(size - 1).timestamp == timestamp) - return; // Ignore duplicates. - } - - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } - - for (int i = 0; i < bgDataList.size(); i++) { - if (bgDataList.get(i).timestamp < (System.currentTimeMillis() - (1000 * 60 * 60 * 5))) { - bgDataList.remove(i); //Get rid of anything more than 5 hours old - break; - } - } - } - - public void setupCharts() { - if(bgDataList.size() > 0) { //Dont crash things just because we dont have values, people dont like crashy things - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); - } else { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), bgDataList, predictionList, tempWatchDataList, basalWatchDataList, bolusWatchDataList, pointSize, highColor, lowColor, midColor, gridColour, basalBackgroundColor, basalCenterColor, bolusColor, carbsColor, timeframe); - } - - chart.setLineChartData(bgGraphBuilder.lineData()); - chart.setViewportCalculationEnabled(true); - chart.setMaximumViewport(chart.getMaximumViewport()); - } else { - ListenerService.requestData(this); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java deleted file mode 100644 index c28ac459ea..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.java +++ /dev/null @@ -1,755 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.content.res.Resources; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.Rect; -import android.graphics.Typeface; -import android.os.BatteryManager; -import android.os.PowerManager; -import android.os.Vibrator; -import android.preference.PreferenceManager; -import android.support.wearable.view.WatchViewStub; -import android.text.format.DateFormat; -import android.view.Display; -import android.view.View; -import android.view.WindowInsets; -import android.view.WindowManager; -import android.widget.ImageView; -import android.widget.LinearLayout; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import androidx.core.content.ContextCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import com.google.android.gms.wearable.DataMap; -import com.ustwo.clockwise.common.WatchFaceTime; -import com.ustwo.clockwise.common.WatchMode; -import com.ustwo.clockwise.common.WatchShape; -import com.ustwo.clockwise.wearable.WatchFace; - -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import javax.inject.Inject; - -import dagger.android.AndroidInjection; -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.Persistence; -import info.nightscout.androidaps.interaction.utils.WearUtil; -import info.nightscout.shared.logging.AAPSLogger; -import info.nightscout.shared.logging.LTag; -import lecho.lib.hellocharts.view.LineChartView; - -/** - * Created by emmablack on 12/29/14. - * Updated by andrew-warrington on 02-Jan-2018. - * Refactored by dlvoy on 2019-11-2019 - */ - -public abstract class BaseWatchFace extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { - - @Inject WearUtil wearUtil; - @Inject Persistence persistence; - @Inject AAPSLogger aapsLogger; - - public final static IntentFilter INTENT_FILTER; - - static { - INTENT_FILTER = new IntentFilter(); - INTENT_FILTER.addAction(Intent.ACTION_TIME_TICK); - INTENT_FILTER.addAction(Intent.ACTION_TIMEZONE_CHANGED); - INTENT_FILTER.addAction(Intent.ACTION_TIME_CHANGED); - } - - static IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); - - public final Point displaySize = new Point(); - public TextView mTime, mHour, mMinute, mTimePeriod, mSgv, mDirection, mTimestamp, mUploaderBattery, mRigBattery, mDelta, mAvgDelta, mStatus, mBasalRate, mIOB1, mIOB2, mCOB1, mCOB2, mBgi, mLoop, mDay, mDayName, mMonth, isAAPSv2, mHighLight, mLowLight; - public ImageView mGlucoseDial, mDeltaGauge, mHourHand, mMinuteHand; - public RelativeLayout mRelativeLayout; - public LinearLayout mLinearLayout, mLinearLayout2, mDate, mChartTap, mMainMenuTap; - public int ageLevel = 1; - public int loopLevel = -1; - public int highColor = Color.YELLOW; - public int lowColor = Color.RED; - public int midColor = Color.WHITE; - public int gridColor = Color.WHITE; - public int basalBackgroundColor = Color.BLUE; - public int basalCenterColor = Color.BLUE; - public int bolusColor = Color.MAGENTA; - public boolean lowResMode = false; - public boolean layoutSet = false; - public boolean bIsRound = false; - public boolean dividerMatchesBg = false; - public int pointSize = 2; - public BgGraphBuilder bgGraphBuilder; - public LineChartView chart; - public RawDisplayData rawData; - public PowerManager.WakeLock wakeLock; - // related endTime manual layout - public View layoutView; - public int specW, specH; - public boolean forceSquareCanvas = false; // Set to true by the Steampunk watch face. - public String sMinute = "0"; - public String sHour = "0"; - protected SharedPreferences sharedPrefs; - private LocalBroadcastManager localBroadcastManager; - private MessageReceiver messageReceiver; - private BroadcastReceiver batteryReceiver; - private int colorDarkHigh, colorDarkMid, colorDarkLow; - private java.text.DateFormat timeFormat; - private SimpleDateFormat sdfDay, sdfMonth, sdfHour, sdfPeriod, sdfDayName, sdfMinute; - private Paint mBackgroundPaint, mTimePaint, mSvgPaint, mDirectionPaint; - private Date mDateTime; - private String mLastSvg = "", mLastDirection = ""; - private float mYOffset = 0; - - @Override - public void onCreate() { - // Not derived from DaggerService, do injection here - AndroidInjection.inject(this); - super.onCreate(); - - colorDarkHigh = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); - colorDarkMid = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - colorDarkLow = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); - - rawData = new RawDisplayData(wearUtil); - Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - display.getSize(displaySize); - wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:BaseWatchFace"); - - specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY); - if (forceSquareCanvas) { - specH = specW; - } else { - specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY); - } - sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - sharedPrefs.registerOnSharedPreferenceChangeListener(this); - - persistence.turnOff(); - - setupBatteryReceiver(); - initFormats(); - setupSimpleUi(); - } - - private void setupBatteryReceiver() { - String setting = sharedPrefs.getString("simplify_ui", "off"); - if ((setting.equals("charging") || setting.equals("ambient_charging")) && batteryReceiver == null) { - IntentFilter intentBatteryFilter = new IntentFilter(); - intentBatteryFilter.addAction(BatteryManager.ACTION_CHARGING); - intentBatteryFilter.addAction(BatteryManager.ACTION_DISCHARGING); - batteryReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - setDataFields(); - invalidate(); - } - }; - registerReceiver(batteryReceiver, intentBatteryFilter); - } - } - - private void initFormats() { - Locale locale = Locale.getDefault(); - timeFormat = DateFormat.getTimeFormat(BaseWatchFace.this); - sdfMinute = new SimpleDateFormat("mm", locale); - sdfHour = DateFormat.is24HourFormat(this) ? new SimpleDateFormat("HH", locale) : new SimpleDateFormat("hh", locale); - sdfPeriod = new SimpleDateFormat("a", locale); - sdfDay = new SimpleDateFormat("dd", locale); - sdfDayName = new SimpleDateFormat("E", locale); - sdfMonth = new SimpleDateFormat("MMM", locale); - } - - private void setupSimpleUi() { - mDateTime = new Date(); - - int black = ContextCompat.getColor(getApplicationContext(), R.color.black); - mBackgroundPaint = new Paint(); - mBackgroundPaint.setColor(black); - - final Typeface NORMAL_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL); - final Typeface BOLD_TYPEFACE = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD); - int white = ContextCompat.getColor(getApplicationContext(), R.color.white); - - Resources resources = this.getResources(); - float textSizeSvg = resources.getDimension(R.dimen.simple_ui_svg_text_size); - float textSizeDirection = resources.getDimension(R.dimen.simple_ui_direction_text_size); - float textSizeTime = resources.getDimension(R.dimen.simple_ui_time_text_size); - mYOffset = resources.getDimension(R.dimen.simple_ui_y_offset); - - mSvgPaint = createTextPaint(NORMAL_TYPEFACE, white, textSizeSvg); - mDirectionPaint = createTextPaint(BOLD_TYPEFACE, white, textSizeDirection); - mTimePaint = createTextPaint(NORMAL_TYPEFACE, white, textSizeTime); - } - - private Paint createTextPaint(Typeface typeface, int colour, float textSize) { - Paint paint = new Paint(); - paint.setColor(colour); - paint.setTypeface(typeface); - paint.setAntiAlias(true); - paint.setTextSize(textSize); - return paint; - } - - @Override - protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { - super.onLayout(shape, screenBounds, screenInsets); - layoutView.onApplyWindowInsets(screenInsets); - bIsRound = screenInsets.isRound(); - } - - public void performViewSetup() { - final WatchViewStub layoutStub = layoutView.findViewById(R.id.watch_view_stub); - IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); - - messageReceiver = new MessageReceiver(); - localBroadcastManager = LocalBroadcastManager.getInstance(this); - localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - - layoutStub.setOnLayoutInflatedListener((WatchViewStub stub) -> { - mTime = stub.findViewById(R.id.watch_time); - mHour = stub.findViewById(R.id.hour); - mMinute = stub.findViewById(R.id.minute); - mTimePeriod = stub.findViewById(R.id.timePeriod); - mDay = stub.findViewById(R.id.day); - mDayName = stub.findViewById(R.id.dayname); - mMonth = stub.findViewById(R.id.month); - mDate = stub.findViewById(R.id.date_time); - mLoop = stub.findViewById(R.id.loop); - mSgv = stub.findViewById(R.id.sgv); - mDirection = stub.findViewById(R.id.direction); - mTimestamp = stub.findViewById(R.id.timestamp); - mIOB1 = stub.findViewById(R.id.iob_text); - mIOB2 = stub.findViewById(R.id.iobView); - mCOB1 = stub.findViewById(R.id.cob_text); - mCOB2 = stub.findViewById(R.id.cobView); - mBgi = stub.findViewById(R.id.bgiView); - mStatus = stub.findViewById(R.id.externaltstatus); - mBasalRate = stub.findViewById(R.id.tmpBasal); - mUploaderBattery = stub.findViewById(R.id.uploader_battery); - mRigBattery = stub.findViewById(R.id.rig_battery); - mDelta = stub.findViewById(R.id.delta); - mAvgDelta = stub.findViewById(R.id.avgdelta); - isAAPSv2 = stub.findViewById(R.id.AAPSv2); - mHighLight = stub.findViewById(R.id.highLight); - mLowLight = stub.findViewById(R.id.lowLight); - mRelativeLayout = stub.findViewById(R.id.main_layout); - mLinearLayout = stub.findViewById(R.id.secondary_layout); - mLinearLayout2 = stub.findViewById(R.id.tertiary_layout); - mGlucoseDial = stub.findViewById(R.id.glucose_dial); - mDeltaGauge = stub.findViewById(R.id.delta_pointer); - mHourHand = stub.findViewById(R.id.hour_hand); - mMinuteHand = stub.findViewById(R.id.minute_hand); - mChartTap = stub.findViewById(R.id.chart_zoom_tap); - mMainMenuTap = stub.findViewById(R.id.main_menu_tap); - chart = stub.findViewById(R.id.chart); - layoutSet = true; - setupCharts(); - setDataFields(); - missedReadingAlert(); - }); - wakeLock.acquire(50); - } - - public int ageLevel() { - if (timeSince() <= (1000 * 60 * 12)) { - return 1; - } - return 0; - } - - public double timeSince() { - return System.currentTimeMillis() - rawData.datetime; - } - - public String readingAge(boolean shortString) { - if (rawData.datetime == 0) { - return shortString ? "--" : "-- Minute ago"; - } - int minutesAgo = (int) Math.floor(timeSince() / (1000 * 60)); - if (minutesAgo == 1) { - return minutesAgo + (shortString ? "'" : " Minute ago"); - } - return minutesAgo + (shortString ? "'" : " Minutes ago"); - } - - @Override - public void onDestroy() { - if (localBroadcastManager != null && messageReceiver != null) { - localBroadcastManager.unregisterReceiver(messageReceiver); - } - if (sharedPrefs != null) { - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } - if (batteryReceiver != null) { - unregisterReceiver(batteryReceiver); - } - super.onDestroy(); - } - - @Override - protected long getInteractiveModeUpdateRate() { - return 60 * 1000L; // Only call onTimeChanged every 60 seconds - } - - @Override - protected void onDraw(Canvas canvas) { - if (isSimpleUi()) { - onDrawSimpleUi(canvas); - } else { - if (layoutSet) { - mRelativeLayout.measure(specW, specH); - int y = forceSquareCanvas ? displaySize.x : displaySize.y; // Square Steampunk - mRelativeLayout.layout(0, 0, displaySize.x, y); - mRelativeLayout.draw(canvas); - } - } - } - - protected void onDrawSimpleUi(Canvas canvas) { - canvas.drawRect(0, 0, displaySize.x, displaySize.y, mBackgroundPaint); - float xHalf = displaySize.x / 2f; - float yThird = displaySize.y / 3f; - - boolean isOutdated = rawData.datetime > 0 && ageLevel() <= 0; - mSvgPaint.setStrikeThruText(isOutdated); - - mSvgPaint.setColor(getBgColour(rawData.sgvLevel)); - mDirectionPaint.setColor(getBgColour(rawData.sgvLevel)); - - String sSvg = rawData.sSgv; - float svgWidth = mSvgPaint.measureText(sSvg); - - String sDirection = " " + rawData.sDirection + "\uFE0E"; - float directionWidth = mDirectionPaint.measureText(sDirection); - - float xSvg = xHalf - (svgWidth + directionWidth) / 2; - canvas.drawText(sSvg, xSvg, yThird + mYOffset, mSvgPaint); - float xDirection = xSvg + svgWidth; - canvas.drawText(sDirection, xDirection, yThird + mYOffset, mDirectionPaint); - - String sTime = timeFormat.format(mDateTime); - float xTime = xHalf - mTimePaint.measureText(sTime) / 2f; - canvas.drawText(timeFormat.format(mDateTime), xTime, yThird * 2f + mYOffset, mTimePaint); - } - - int getBgColour(long level) { - if (level == 1) { - return colorDarkHigh; - } - if (level == 0) { - return colorDarkMid; - } - return colorDarkLow; - } - - @Override - protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) { - if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - long now = System.currentTimeMillis(); - mDateTime.setTime(now); - - PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50); - missedReadingAlert(); - checkVibrateHourly(oldTime, newTime); - if (!isSimpleUi()) { - setDataFields(); - } - wearUtil.releaseWakeLock(wl); - } - } - - private boolean isCharging() { - Intent mBatteryStatus = this.registerReceiver(null, iFilter); - int status = mBatteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1); - return status == BatteryManager.BATTERY_STATUS_CHARGING || - status == BatteryManager.BATTERY_STATUS_FULL; - } - - private void checkVibrateHourly(WatchFaceTime oldTime, WatchFaceTime newTime) { - boolean hourlyVibratePref = sharedPrefs.getBoolean("vibrate_Hourly", false); - if (hourlyVibratePref && layoutSet && newTime.hasHourChanged(oldTime)) { - aapsLogger.info(LTag.WEAR, "hourlyVibratePref", "true --> " + newTime); - Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE); - long[] vibrationPattern = {0, 150, 125, 100}; - vibrator.vibrate(vibrationPattern, -1); - } - } - - public void setDataFields() { - setDateAndTime(); - if (mSgv != null) { - if (sharedPrefs.getBoolean("showBG", true)) { - mSgv.setText(rawData.sSgv); - mSgv.setVisibility(View.VISIBLE); - } else { - // Leave the textview there but invisible, as a height holder for the empty space above the white line - mSgv.setVisibility(View.INVISIBLE); - mSgv.setText(""); - } - } - - strikeThroughSgvIfNeeded(); - - if (mDirection != null) { - if (sharedPrefs.getBoolean("show_direction", true)) { - mDirection.setText(rawData.sDirection + "\uFE0E"); - mDirection.setVisibility(View.VISIBLE); - } else { - mDirection.setVisibility(View.GONE); - } - } - - if (mDelta != null) { - if (sharedPrefs.getBoolean("showDelta", true)) { - mDelta.setText(rawData.sDelta); - mDelta.setVisibility(View.VISIBLE); - } else { - mDelta.setVisibility(View.GONE); - } - } - - if (mAvgDelta != null) { - if (sharedPrefs.getBoolean("showAvgDelta", true)) { - mAvgDelta.setText(rawData.sAvgDelta); - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - } - - if (mCOB1 != null && mCOB2 != null) { - mCOB2.setText(rawData.sCOB2); - if (sharedPrefs.getBoolean("show_cob", true)) { - mCOB1.setVisibility(View.VISIBLE); - mCOB2.setVisibility(View.VISIBLE); - } else { - mCOB1.setVisibility(View.GONE); - mCOB2.setVisibility(View.GONE); - } - // Deal with cases where there is only the value shown for COB, and not the label - } else if (mCOB2 != null) { - mCOB2.setText(rawData.sCOB2); - if (sharedPrefs.getBoolean("show_cob", true)) { - mCOB2.setVisibility(View.VISIBLE); - } else { - mCOB2.setVisibility(View.GONE); - } - } - - if (mIOB1 != null && mIOB2 != null) { - if (sharedPrefs.getBoolean("show_iob", true)) { - mIOB1.setVisibility(View.VISIBLE); - mIOB2.setVisibility(View.VISIBLE); - if (rawData.detailedIOB) { - mIOB1.setText(rawData.sIOB1); - mIOB2.setText(rawData.sIOB2); - } else { - mIOB1.setText(getString(R.string.activity_IOB)); - mIOB2.setText(rawData.sIOB1); - } - } else { - mIOB1.setVisibility(View.GONE); - mIOB2.setVisibility(View.GONE); - } - // Deal with cases where there is only the value shown for IOB, and not the label - } else if (mIOB2 != null) { - if (sharedPrefs.getBoolean("show_iob", true)) { - mIOB2.setVisibility(View.VISIBLE); - if (rawData.detailedIOB) { - mIOB2.setText(rawData.sIOB2); - } else { - mIOB2.setText(rawData.sIOB1); - } - } else { - mIOB2.setText(""); - } - } - - if (mTimestamp != null) { - if (sharedPrefs.getBoolean("showAgo", true)) { - if (isAAPSv2 != null) { - mTimestamp.setText(readingAge(true)); - } else { - boolean shortString = sharedPrefs.getBoolean("showExternalStatus", true); - mTimestamp.setText(readingAge(shortString)); - } - mTimestamp.setVisibility(View.VISIBLE); - } else { - mTimestamp.setVisibility(View.GONE); - } - } - - if (mUploaderBattery != null) { - if (sharedPrefs.getBoolean("show_uploader_battery", true)) { - if (isAAPSv2 != null) { - mUploaderBattery.setText(rawData.sUploaderBattery + "%"); - mUploaderBattery.setVisibility(View.VISIBLE); - } else { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - mUploaderBattery.setText("U: " + rawData.sUploaderBattery + "%"); - } else { - mUploaderBattery.setText("Uploader: " + rawData.sUploaderBattery + "%"); - } - } - } else { - mUploaderBattery.setVisibility(View.GONE); - } - } - - if (mRigBattery != null) { - if (sharedPrefs.getBoolean("show_rig_battery", false)) { - mRigBattery.setText(rawData.sRigBattery); - mRigBattery.setVisibility(View.VISIBLE); - } else { - mRigBattery.setVisibility(View.GONE); - } - } - - if (mBasalRate != null) { - if (sharedPrefs.getBoolean("show_temp_basal", true)) { - mBasalRate.setText(rawData.sBasalRate); - mBasalRate.setVisibility(View.VISIBLE); - } else { - mBasalRate.setVisibility(View.GONE); - } - } - - if (mBgi != null) { - if (rawData.showBGI) { - mBgi.setText(rawData.sBgi); - mBgi.setVisibility(View.VISIBLE); - } else { - mBgi.setVisibility(View.GONE); - } - } - - if (mStatus != null) { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - mStatus.setText(rawData.externalStatusString); - mStatus.setVisibility(View.VISIBLE); - } else { - mStatus.setVisibility(View.GONE); - } - } - - if (mLoop != null) { - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - mLoop.setVisibility(View.VISIBLE); - if (rawData.openApsStatus != -1) { - int mins = (int) ((System.currentTimeMillis() - rawData.openApsStatus) / 1000 / 60); - mLoop.setText(mins + "'"); - if (mins > 14) { - loopLevel = 0; - mLoop.setBackgroundResource(R.drawable.loop_red_25); - } else { - loopLevel = 1; - mLoop.setBackgroundResource(R.drawable.loop_green_25); - } - } else { - loopLevel = -1; - mLoop.setText("-"); - mLoop.setBackgroundResource(R.drawable.loop_grey_25); - } - } else { - mLoop.setVisibility(View.GONE); - } - } - - setColor(); - } - - @Override - protected void on24HourFormatChanged(boolean is24HourFormat) { - initFormats(); - if (!isSimpleUi()) { - setDataFields(); - } - invalidate(); - } - - public void setDateAndTime() { - if (mTime != null) { - mTime.setText(timeFormat.format(mDateTime)); - } - - sMinute = sdfMinute.format(mDateTime); - sHour = sdfHour.format(mDateTime); - if (mHour != null && mMinute != null) { - mHour.setText(sHour); - mMinute.setText(sMinute); - } - - if (mTimePeriod != null) { - if (!DateFormat.is24HourFormat(this)) { - mTimePeriod.setVisibility(View.VISIBLE); - mTimePeriod.setText(sdfPeriod.format(mDateTime).toUpperCase()); - } else { - mTimePeriod.setVisibility(View.GONE); - } - } - - if (mDate != null && mDay != null && mMonth != null) { - if (sharedPrefs.getBoolean("show_date", false)) { - if (mDayName != null) { - mDayName.setText(sdfDayName.format(mDateTime)); - } - - mDay.setText(sdfDay.format(mDateTime)); - mMonth.setText(sdfMonth.format(mDateTime)); - mDate.setVisibility(View.VISIBLE); - } else { - mDate.setVisibility(View.GONE); - } - } - } - - public void setColor() { - dividerMatchesBg = sharedPrefs.getBoolean("match_divider", false); - if (lowResMode) { - setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - } - - public void strikeThroughSgvIfNeeded() { - if (mSgv != null) { - if (sharedPrefs.getBoolean("showBG", true)) { - if (ageLevel() <= 0 && rawData.datetime > 0) { - mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - } - } - } - - protected void onWatchModeChanged(WatchMode watchMode) { - lowResMode = isLowRes(watchMode); - if (isSimpleUi()) { - setSimpleUiAntiAlias(); - } else { - setDataFields(); - } - invalidate(); - } - - void setSimpleUiAntiAlias() { - boolean antiAlias = getCurrentWatchMode() == WatchMode.AMBIENT; - mSvgPaint.setAntiAlias(antiAlias); - mDirectionPaint.setAntiAlias(antiAlias); - mTimePaint.setAntiAlias(antiAlias); - } - - private boolean isLowRes(WatchMode watchMode) { - return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN; - } - - private boolean isSimpleUi() { - String simplify = sharedPrefs.getString("simplify_ui", "off"); - if (simplify.equals("off")) { - return false; - } - if ((simplify.equals("ambient") || simplify.equals("ambient_charging")) && getCurrentWatchMode() == WatchMode.AMBIENT) { - return true; - } - return (simplify.equals("charging") || simplify.equals("ambient_charging")) && isCharging(); - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - setupBatteryReceiver(); - if ("delta_granularity".equals(key)) { - ListenerService.requestData(this); - } - if (layoutSet) { - setDataFields(); - } - invalidate(); - } - - protected abstract void setColorDark(); - - protected abstract void setColorBright(); - - protected abstract void setColorLowRes(); - - public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince() / (1000 * 60)); - if (rawData.datetime == 0 || minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - ListenerService.requestData(this); // Attempt endTime recover missing data - } - } - - public void setupCharts() { - if (isSimpleUi()) { - return; - } - if (rawData.bgDataList.size() > 0) { // Dont crash things just because we dont have values, people dont like crashy things - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - if (lowResMode) { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), rawData, pointSize, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); - } else { - bgGraphBuilder = new BgGraphBuilder(getApplicationContext(), rawData, pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe); - } - - chart.setLineChartData(bgGraphBuilder.lineData()); - chart.setViewportCalculationEnabled(true); - chart.setMaximumViewport(chart.getMaximumViewport()); - } - } - - public class MessageReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - PowerManager.WakeLock wl = wearUtil.getWakeLock("readingPrefs", 50); - - final DataMap dataMap = rawData.updateDataFromMessage(intent, wakeLock); - if (chart != null && dataMap != null) { - rawData.addToWatchSet(dataMap); - setupCharts(); - } - rawData.updateStatusFromMessage(intent, wakeLock); - rawData.updateBasalsFromMessage(intent, wakeLock); - - if (isSimpleUi()) { - if (needUpdate()) { - invalidate(); - } - } else { - setupCharts(); - setDataFields(); - invalidate(); - } - wearUtil.releaseWakeLock(wl); - } - } - - private boolean needUpdate() { - if (mLastSvg.equals(rawData.sSgv) && mLastDirection.equals(rawData.sDirection)) { - return false; - } - mLastSvg = rawData.sSgv; - mLastDirection = rawData.sDirection; - return true; - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt new file mode 100644 index 0000000000..12ea214fac --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BaseWatchFace.kt @@ -0,0 +1,595 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.BroadcastReceiver +import android.content.Context +import android.content.Intent +import android.content.IntentFilter +import android.graphics.* +import android.os.BatteryManager +import android.os.Vibrator +import android.support.wearable.watchface.WatchFaceStyle +import android.view.LayoutInflater +import android.view.View +import android.view.WindowInsets +import android.view.WindowManager +import android.widget.ImageView +import android.widget.LinearLayout +import android.widget.RelativeLayout +import android.widget.TextView +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchFaceTime +import com.ustwo.clockwise.common.WatchMode +import com.ustwo.clockwise.common.WatchShape +import com.ustwo.clockwise.wearable.WatchFace +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.events.EventWearPreferenceChange +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.extensions.toVisibility +import info.nightscout.androidaps.extensions.toVisibilityKeepSpace +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.ActionResendData +import info.nightscout.shared.weardata.EventData.SingleBg +import info.nightscout.shared.weardata.EventData.TreatmentData +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import lecho.lib.hellocharts.view.LineChartView +import javax.inject.Inject +import kotlin.math.floor + +/** + * Created by emmablack on 12/29/14. + * Updated by andrew-warrington on 02-Jan-2018. + * Refactored by dlvoy on 2019-11-2019 + * Refactored by MilosKozak 24/04/2022 + */ +abstract class BaseWatchFace : WatchFace() { + + @Inject lateinit var wearUtil: WearUtil + @Inject lateinit var persistence: Persistence + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var rxBus: RxBus + @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var sp: SP + @Inject lateinit var dateUtil: DateUtil + + private var disposable = CompositeDisposable() + + private val rawData = RawDisplayData() + + protected val singleBg get() = rawData.singleBg + protected val status get() = rawData.status + protected val treatmentData get() = rawData.treatmentData + protected val graphData get() = rawData.graphData + + // Layout + @LayoutRes abstract fun layoutResource(): Int + + private val displaySize = Point() + var mTime: TextView? = null + var mHour: TextView? = null + var mMinute: TextView? = null + var mSgv: TextView? = null + var mDirection: TextView? = null + var mTimestamp: TextView? = null + var mUploaderBattery: TextView? = null + var mRigBattery: TextView? = null + var mDelta: TextView? = null + var mAvgDelta: TextView? = null + var mStatus: TextView? = null + var mBasalRate: TextView? = null + var mIOB1: TextView? = null + var mIOB2: TextView? = null + var mCOB1: TextView? = null + var mCOB2: TextView? = null + var mBgi: TextView? = null + var mLoop: TextView? = null + var mDay: TextView? = null + var mDayName: TextView? = null + var mMonth: TextView? = null + var isAAPSv2: TextView? = null + var mHighLight: TextView? = null + var mLowLight: TextView? = null + var mGlucoseDial: ImageView? = null + var mDeltaGauge: ImageView? = null + var mHourHand: ImageView? = null + var mMinuteHand: ImageView? = null + var mRelativeLayout: RelativeLayout? = null + var mLinearLayout: LinearLayout? = null + var mLinearLayout2: LinearLayout? = null + var mDate: LinearLayout? = null + var mChartTap: LinearLayout? = null // Steampunk only + var mMainMenuTap: LinearLayout? = null // Steampunk,Digital only + var chart: LineChartView? = null + + var ageLevel = 1 + var loopLevel = -1 + var highColor = Color.YELLOW + var lowColor = Color.RED + var midColor = Color.WHITE + var gridColor = Color.WHITE + var basalBackgroundColor = Color.BLUE + var basalCenterColor = Color.BLUE + var bolusColor = Color.MAGENTA + private var lowResMode = false + private var layoutSet = false + var bIsRound = false + var dividerMatchesBg = false + var pointSize = 2 + + // Tapping times + private var sgvTapTime: Long = 0 + private var chartTapTime: Long = 0 + private var mainMenuTapTime: Long = 0 + + // related endTime manual layout + var layoutView: View? = null + var specW = 0 + var specH = 0 + var forceSquareCanvas = false // Set to true by the Steampunk watch face. + private var batteryReceiver: BroadcastReceiver? = null + private var colorDarkHigh = 0 + private var colorDarkMid = 0 + private var colorDarkLow = 0 + private var mBackgroundPaint = Paint() + + private lateinit var mTimePaint: Paint + private lateinit var mSvgPaint: Paint + private lateinit var mDirectionPaint: Paint + + private var mLastSvg = "" + private var mLastDirection = "" + private var mYOffset = 0f + override fun onCreate() { + // Not derived from DaggerService, do injection here + AndroidInjection.inject(this) + super.onCreate() + colorDarkHigh = ContextCompat.getColor(this, R.color.dark_highColor) + colorDarkMid = ContextCompat.getColor(this, R.color.dark_midColor) + colorDarkLow = ContextCompat.getColor(this, R.color.dark_lowColor) + @Suppress("DEPRECATION") + (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay.getSize(displaySize) + specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY) + specH = if (forceSquareCanvas) specW else View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY) + disposable += rxBus + .toObservable(EventWearPreferenceChange::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { event: EventWearPreferenceChange -> + setupBatteryReceiver() + if (event.changedKey != null && event.changedKey == "delta_granularity") rxBus.send(EventWearToMobile(ActionResendData("BaseWatchFace:onSharedPreferenceChanged"))) + if (layoutSet) setDataFields() + invalidate() + } + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + // this event is received as last batch of data + rawData.updateFromPersistence(persistence) + if (!isSimpleUi || !needUpdate()) { + setupCharts() + setDataFields() + } + invalidate() + } + rawData.updateFromPersistence(persistence) + persistence.turnOff() + setupBatteryReceiver() + setupSimpleUi() + layoutView = (getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater).inflate(layoutResource(), null) + performViewSetup() + rxBus.send(EventWearToMobile(ActionResendData("BaseWatchFace::onCreate"))) + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + chart?.let { chart -> + if (tapType == TAP_TYPE_TAP && x >= chart.left && x <= chart.right && y >= chart.top && y <= chart.bottom) { + if (eventTime - chartTapTime < 800) { + changeChartTimeframe() + } + chartTapTime = eventTime + return + } + } + mSgv?.let { mSgv -> + val extra = (mSgv.right - mSgv.left) / 2 + if (tapType == TAP_TYPE_TAP && x + extra >= mSgv.left && x - extra <= mSgv.right && y >= mSgv.top && y <= mSgv.bottom) { + if (eventTime - sgvTapTime < 800) { + startActivity(Intent(this, MainMenuActivity::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + sgvTapTime = eventTime + } + } + mChartTap?.let { mChartTap -> + if (tapType == TAP_TYPE_TAP && x >= mChartTap.left && x <= mChartTap.right && y >= mChartTap.top && y <= mChartTap.bottom) { + if (eventTime - chartTapTime < 800) { + changeChartTimeframe() + } + chartTapTime = eventTime + return + } + } + mMainMenuTap?.let { mMainMenuTap -> + if (tapType == TAP_TYPE_TAP && x >= mMainMenuTap.left && x <= mMainMenuTap.right && y >= mMainMenuTap.top && y <= mMainMenuTap.bottom) { + if (eventTime - mainMenuTapTime < 800) { + startActivity(Intent(this, MainMenuActivity::class.java).also { it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) + } + mainMenuTapTime = eventTime + return + } + } + } + + open fun changeChartTimeframe() { + var timeframe = sp.getInt(R.string.key_chart_time_frame, 3) + timeframe = timeframe % 5 + 1 + sp.putInt(R.string.key_chart_time_frame, timeframe) + } + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() + } + + private fun setupBatteryReceiver() { + val setting = sp.getString("simplify_ui", "off") + if ((setting == "charging" || setting == "ambient_charging") && batteryReceiver == null) { + val intentBatteryFilter = IntentFilter() + intentBatteryFilter.addAction(BatteryManager.ACTION_CHARGING) + intentBatteryFilter.addAction(BatteryManager.ACTION_DISCHARGING) + batteryReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + setDataFields() + invalidate() + } + } + registerReceiver(batteryReceiver, intentBatteryFilter) + } + } + + private fun setupSimpleUi() { + val black = ContextCompat.getColor(this, R.color.black) + mBackgroundPaint.color = black + val white = ContextCompat.getColor(this, R.color.white) + val resources = this.resources + val textSizeSvg = resources.getDimension(R.dimen.simple_ui_svg_text_size) + val textSizeDirection = resources.getDimension(R.dimen.simple_ui_direction_text_size) + val textSizeTime = resources.getDimension(R.dimen.simple_ui_time_text_size) + mYOffset = resources.getDimension(R.dimen.simple_ui_y_offset) + mSvgPaint = createTextPaint(NORMAL_TYPEFACE, white, textSizeSvg) + mDirectionPaint = createTextPaint(BOLD_TYPEFACE, white, textSizeDirection) + mTimePaint = createTextPaint(NORMAL_TYPEFACE, white, textSizeTime) + } + + private fun createTextPaint(typeface: Typeface, colour: Int, textSize: Float): Paint { + val paint = Paint() + paint.color = colour + paint.typeface = typeface + paint.isAntiAlias = true + paint.textSize = textSize + return paint + } + + override fun onLayout(shape: WatchShape, screenBounds: Rect, screenInsets: WindowInsets) { + super.onLayout(shape, screenBounds, screenInsets) + layoutView?.onApplyWindowInsets(screenInsets) + bIsRound = screenInsets.isRound + } + + private fun performViewSetup() { + mTime = layoutView?.findViewById(R.id.watch_time) + mHour = layoutView?.findViewById(R.id.hour) + mMinute = layoutView?.findViewById(R.id.minute) + mDay = layoutView?.findViewById(R.id.day) + mDayName = layoutView?.findViewById(R.id.dayname) + mMonth = layoutView?.findViewById(R.id.month) + mDate = layoutView?.findViewById(R.id.date_time) + mLoop = layoutView?.findViewById(R.id.loop) + mSgv = layoutView?.findViewById(R.id.sgv) + mDirection = layoutView?.findViewById(R.id.direction) + mTimestamp = layoutView?.findViewById(R.id.timestamp) + mIOB1 = layoutView?.findViewById(R.id.iob_text) + mIOB2 = layoutView?.findViewById(R.id.iobView) + mCOB1 = layoutView?.findViewById(R.id.cob_text) + mCOB2 = layoutView?.findViewById(R.id.cobView) + mBgi = layoutView?.findViewById(R.id.bgiView) + mStatus = layoutView?.findViewById(R.id.externaltstatus) + mBasalRate = layoutView?.findViewById(R.id.tmpBasal) + mUploaderBattery = layoutView?.findViewById(R.id.uploader_battery) + mRigBattery = layoutView?.findViewById(R.id.rig_battery) + mDelta = layoutView?.findViewById(R.id.delta) + mAvgDelta = layoutView?.findViewById(R.id.avgdelta) + isAAPSv2 = layoutView?.findViewById(R.id.AAPSv2) + mHighLight = layoutView?.findViewById(R.id.highLight) + mLowLight = layoutView?.findViewById(R.id.lowLight) + mRelativeLayout = layoutView?.findViewById(R.id.main_layout) + mLinearLayout = layoutView?.findViewById(R.id.secondary_layout) + mLinearLayout2 = layoutView?.findViewById(R.id.tertiary_layout) + mGlucoseDial = layoutView?.findViewById(R.id.glucose_dial) + mDeltaGauge = layoutView?.findViewById(R.id.delta_pointer) + mHourHand = layoutView?.findViewById(R.id.hour_hand) + mMinuteHand = layoutView?.findViewById(R.id.minute_hand) + mChartTap = layoutView?.findViewById(R.id.chart_zoom_tap) + mMainMenuTap = layoutView?.findViewById(R.id.main_menu_tap) + chart = layoutView?.findViewById(R.id.chart) + layoutSet = true + setupCharts() + setDataFields() + missedReadingAlert() + } + + fun ageLevel(): Int = + if (timeSince() <= 1000 * 60 * 12) 1 else 0 + + fun timeSince(): Double { + return (System.currentTimeMillis() - singleBg.timeStamp).toDouble() + } + + protected fun readingAge(shortString: Boolean): String { + if (singleBg.timeStamp == 0L) { + return if (shortString) "--" else "-- Minute ago" + } + val minutesAgo = floor(timeSince() / (1000 * 60)).toInt() + return if (minutesAgo == 1) { + minutesAgo.toString() + if (shortString) "'" else " Minute ago" + } else minutesAgo.toString() + if (shortString) "'" else " Minutes ago" + } + + override fun onDestroy() { + disposable.clear() + if (batteryReceiver != null) { + unregisterReceiver(batteryReceiver) + } + super.onDestroy() + } + + override fun getInteractiveModeUpdateRate(): Long { + return 60 * 1000L // Only call onTimeChanged every 60 seconds + } + + override fun onDraw(canvas: Canvas) { + if (isSimpleUi) { + onDrawSimpleUi(canvas) + } else { + if (layoutSet) { + mRelativeLayout?.measure(specW, specH) + val y = if (forceSquareCanvas) displaySize.x else displaySize.y // Square Steampunk + mRelativeLayout?.layout(0, 0, displaySize.x, y) + mRelativeLayout?.draw(canvas) + } + } + } + + private fun onDrawSimpleUi(canvas: Canvas) { + canvas.drawRect(0f, 0f, displaySize.x.toFloat(), displaySize.y.toFloat(), mBackgroundPaint) + val xHalf = displaySize.x / 2f + val yThird = displaySize.y / 3f + val isOutdated = singleBg.timeStamp > 0 && ageLevel() <= 0 + mSvgPaint.isStrikeThruText = isOutdated + mSvgPaint.color = getBgColour(singleBg.sgvLevel) + mDirectionPaint.color = getBgColour(singleBg.sgvLevel) + val sSvg = singleBg.sgvString + val svgWidth = mSvgPaint.measureText(sSvg) + val sDirection = " " + singleBg.sgvString + "\uFE0E" + val directionWidth = mDirectionPaint.measureText(sDirection) + val xSvg = xHalf - (svgWidth + directionWidth) / 2 + canvas.drawText(sSvg, xSvg, yThird + mYOffset, mSvgPaint) + val xDirection = xSvg + svgWidth + canvas.drawText(sDirection, xDirection, yThird + mYOffset, mDirectionPaint) + val sTime = dateUtil.timeString() + val xTime = xHalf - mTimePaint.measureText(sTime) / 2f + canvas.drawText(sTime, xTime, yThird * 2f + mYOffset, mTimePaint) + } + + private fun getBgColour(level: Long): Int { + if (level == 1L) { + return colorDarkHigh + } + return if (level == 0L) { + colorDarkMid + } else colorDarkLow + } + + override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { + if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { + missedReadingAlert() + checkVibrateHourly(oldTime, newTime) + if (!isSimpleUi) setDataFields() + } + } + + private val isCharging: Boolean + get() { + val mBatteryStatus = this.registerReceiver(null, iFilter) + val status = mBatteryStatus?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) + return status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL + } + + @Suppress("DEPRECATION") + private fun checkVibrateHourly(oldTime: WatchFaceTime, newTime: WatchFaceTime) { + val hourlyVibratePref = sp.getBoolean("vibrate_Hourly", false) + if (hourlyVibratePref && layoutSet && newTime.hasHourChanged(oldTime)) { + aapsLogger.info(LTag.WEAR, "hourlyVibratePref", "true --> $newTime") + val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator + val vibrationPattern = longArrayOf(0, 150, 125, 100) + vibrator.vibrate(vibrationPattern, -1) + } + } + + @SuppressLint("SetTextI18n") + open fun setDataFields() { + setDateAndTime() + mSgv?.text = singleBg.sgvString + mSgv?.visibility = sp.getBoolean(R.string.key_show_bg, true).toVisibilityKeepSpace() + strikeThroughSgvIfNeeded() + mDirection?.text = "${singleBg.sgvString}\uFE0E" + mDirection?.visibility = sp.getBoolean("show_direction", true).toVisibility() + mDelta?.text = singleBg.delta + mDelta?.visibility = sp.getBoolean(R.string.key_show_delta, true).toVisibility() + mAvgDelta?.text = singleBg.avgDelta + mAvgDelta?.visibility = sp.getBoolean(R.string.key_show_avg_delta, true).toVisibility() + mCOB1?.visibility = sp.getBoolean(R.string.key_show_cob, true).toVisibility() + mCOB2?.text = status.cob + mCOB2?.visibility = sp.getBoolean(R.string.key_show_cob, true).toVisibility() + mIOB1?.visibility = sp.getBoolean("show_iob", true).toVisibility() + mIOB2?.visibility = sp.getBoolean("show_iob", true).toVisibility() + mIOB1?.text = if (sp.getBoolean("show_iob", true)) status.iobSum else getString(R.string.activity_IOB) + mIOB2?.text = if (sp.getBoolean("show_iob", true)) status.iobDetail else status.iobSum + mTimestamp?.visibility = sp.getBoolean(R.string.key_show_ago, true).toVisibility() + mTimestamp?.text = readingAge(if (isAAPSv2 != null) true else sp.getBoolean(R.string.key_show_external_status, true)) + mUploaderBattery?.visibility = sp.getBoolean("show_uploader_battery", true).toVisibility() + mUploaderBattery?.text = + when { + isAAPSv2 != null -> status.battery + "%" + sp.getBoolean(R.string.key_show_external_status, true) -> "U: ${status.battery}%" + else -> "Uploader: ${status.battery}%" + } + mRigBattery?.visibility = sp.getBoolean("show_rig_battery", false).toVisibility() + mRigBattery?.text = status.rigBattery + mBasalRate?.text = status.currentBasal + mBasalRate?.visibility = sp.getBoolean("show_temp_basal", true).toVisibility() + mBgi?.text = status.bgi + mBgi?.visibility = status.showBgi.toVisibility() + mStatus?.text = status.externalStatus + mStatus?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + mLoop?.visibility = sp.getBoolean(R.string.key_show_external_status, true).toVisibility() + if (status.openApsStatus != -1L) { + val minutes = ((System.currentTimeMillis() - status.openApsStatus) / 1000 / 60).toInt() + mLoop?.text = "$minutes'" + if (minutes > 14) { + loopLevel = 0 + mLoop?.setBackgroundResource(R.drawable.loop_red_25) + } else { + loopLevel = 1 + mLoop?.setBackgroundResource(R.drawable.loop_green_25) + } + } else { + loopLevel = -1 + mLoop?.text = "-" + mLoop?.setBackgroundResource(R.drawable.loop_grey_25) + } + setColor() + } + + override fun on24HourFormatChanged(is24HourFormat: Boolean) { + if (!isSimpleUi) { + setDataFields() + } + invalidate() + } + + protected fun setDateAndTime() { + mTime?.text = dateUtil.timeString() + mHour?.text = dateUtil.hourString() + mMinute?.text = dateUtil.minuteString() + mDate?.visibility = sp.getBoolean(R.string.key_show_date, false).toVisibility() + mDayName?.text = dateUtil.dayNameString() + mDay?.text = dateUtil.dayString() + mMonth?.text = dateUtil.monthString() + } + + private fun setColor() { + dividerMatchesBg = sp.getBoolean("match_divider", false) + when { + lowResMode -> setColorLowRes() + sp.getBoolean("dark", true) -> setColorDark() + else -> setColorBright() + } + } + + protected fun strikeThroughSgvIfNeeded() { + mSgv?.let { mSgv -> + if (ageLevel() <= 0 && singleBg.timeStamp > 0) mSgv.paintFlags = mSgv.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG + else mSgv.paintFlags = mSgv.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() + } + } + + override fun onWatchModeChanged(watchMode: WatchMode) { + lowResMode = isLowRes(watchMode) + if (isSimpleUi) setSimpleUiAntiAlias() + else setDataFields() + invalidate() + } + + private fun setSimpleUiAntiAlias() { + val antiAlias = currentWatchMode == WatchMode.AMBIENT + mSvgPaint.isAntiAlias = antiAlias + mDirectionPaint.isAntiAlias = antiAlias + mTimePaint.isAntiAlias = antiAlias + } + + private fun isLowRes(watchMode: WatchMode): Boolean { + return watchMode == WatchMode.LOW_BIT || watchMode == WatchMode.LOW_BIT_BURN_IN + } + + private val isSimpleUi: Boolean + get() { + val simplify = sp.getString("simplify_ui", "off") + return if (simplify == "off") false + else if ((simplify == "ambient" || simplify == "ambient_charging") && currentWatchMode == WatchMode.AMBIENT) true + else (simplify == "charging" || simplify == "ambient_charging") && isCharging + } + + protected abstract fun setColorDark() + protected abstract fun setColorBright() + protected abstract fun setColorLowRes() + private fun missedReadingAlert() { + val minutesSince = floor(timeSince() / (1000 * 60)).toInt() + if (singleBg.timeStamp == 0L || minutesSince >= 16 && (minutesSince - 16) % 5 == 0) { + // Attempt endTime recover missing data + rxBus.send(EventWearToMobile(ActionResendData("BaseWatchFace:missedReadingAlert"))) + } + } + + fun setupCharts() { + if (isSimpleUi) { + return + } + if (chart != null && graphData.entries.size > 0) { + val timeframe = sp.getInt(R.string.key_chart_time_frame, 3) + val bgGraphBuilder = + if (lowResMode) + BgGraphBuilder( + sp, dateUtil, graphData.entries, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, pointSize, + midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe + ) + else + BgGraphBuilder( + sp, dateUtil, graphData.entries, treatmentData.predictions, treatmentData.temps, treatmentData.basals, treatmentData.boluses, + pointSize, highColor, lowColor, midColor, gridColor, basalBackgroundColor, basalCenterColor, bolusColor, Color.GREEN, timeframe + ) + chart?.lineChartData = bgGraphBuilder.lineData() + chart?.isViewportCalculationEnabled = true + } + } + + private fun needUpdate(): Boolean { + if (mLastSvg == singleBg.sgvString && mLastDirection == singleBg.sgvString) { + return false + } + mLastSvg = singleBg.sgvString + mLastDirection = singleBg.sgvString + return true + } + + companion object { + + var iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED) + val NORMAL_TYPEFACE: Typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.NORMAL) + val BOLD_TYPEFACE: Typeface = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD) + const val SCREEN_SIZE_SMALL = 280 + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java deleted file mode 100644 index 3cae85f962..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.java +++ /dev/null @@ -1,528 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Context; -import android.graphics.DashPathEffect; -import android.preference.PreferenceManager; -import android.text.format.DateFormat; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TimeZone; - -import info.nightscout.androidaps.data.BasalWatchData; -import info.nightscout.androidaps.data.BgWatchData; -import info.nightscout.androidaps.data.BolusWatchData; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.data.TempWatchData; -import lecho.lib.hellocharts.model.Axis; -import lecho.lib.hellocharts.model.AxisValue; -import lecho.lib.hellocharts.model.Line; -import lecho.lib.hellocharts.model.LineChartData; -import lecho.lib.hellocharts.model.PointValue; -import lecho.lib.hellocharts.model.Viewport; - -/** - * Created by emmablack on 11/15/14. - */ -public class BgGraphBuilder { - public static final double MAX_PREDICTION__TIME_RATIO = (3d / 5); - public static final double UPPER_CUTOFF_SGV = 400; - private final long predictionEndTime; - private final List predictionsList; - private final ArrayList bolusWatchDataList; - private final ArrayList basalWatchDataList; - public List tempWatchDataList; - private final int timespan; - public long end_time; - public long start_time; - public double fuzzyTimeDenom = (1000 * 60 * 1); - public Context context; - public double highMark; - public double lowMark; - public List bgDataList = new ArrayList(); - - public int pointSize; - public int highColor; - public int lowColor; - public int midColor; - public int gridColour; - public int basalCenterColor; - public int basalBackgroundColor; - private final int bolusInvalidColor; - private final int carbsColor; - - public boolean singleLine = false; - - private final List inRangeValues = new ArrayList(); - private final List highValues = new ArrayList(); - private final List lowValues = new ArrayList(); - public Viewport viewport; - - - //used for low resolution screen. - public BgGraphBuilder(Context context, List aBgList, List predictionsList, List tempWatchDataList, ArrayList basalWatchDataList, ArrayList bolusWatchDataList, int aPointSize, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) { - this.start_time = System.currentTimeMillis() - (1000 * 60 * 60 * timespan); //timespan hours ago - this.bgDataList = aBgList; - this.predictionsList = predictionsList; - this.context = context; - this.highMark = aBgList.get(aBgList.size() - 1).high; - this.lowMark = aBgList.get(aBgList.size() - 1).low; - this.pointSize = aPointSize; - this.singleLine = false; - this.midColor = aMidColor; - this.lowColor = aMidColor; - this.highColor = aMidColor; - this.timespan = timespan; - this.tempWatchDataList = tempWatchDataList; - this.basalWatchDataList = basalWatchDataList; - this.bolusWatchDataList = (bolusWatchDataList!=null)?bolusWatchDataList:new ArrayList(); - this.gridColour = gridColour; - this.basalCenterColor = basalCenterColor; - this.basalBackgroundColor = basalBackgroundColor; - this.bolusInvalidColor = bolusInvalidColor; - this.carbsColor = carbsColor; - this.end_time = System.currentTimeMillis() + (1000 * 60 * 6 * timespan); //Now plus 30 minutes padding (for 5 hours. Less if less.) - this.predictionEndTime = getPredictionEndTime(); - this.end_time = (predictionEndTime>end_time)?predictionEndTime:end_time; - } - - public BgGraphBuilder(Context context, List aBgList, List predictionsList, List tempWatchDataList, ArrayList basalWatchDataList, ArrayList bolusWatchDataList, int aPointSize, int aHighColor, int aLowColor, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) { - this.start_time = System.currentTimeMillis() - (1000 * 60 * 60 * timespan); //timespan hours ago - this.bgDataList = aBgList; - this.predictionsList = predictionsList; - this.context = context; - this.highMark = aBgList.get(aBgList.size() - 1).high; - this.lowMark = aBgList.get(aBgList.size() - 1).low; - this.pointSize = aPointSize; - this.highColor = aHighColor; - this.lowColor = aLowColor; - this.midColor = aMidColor; - this.timespan = timespan; - this.tempWatchDataList = tempWatchDataList; - this.basalWatchDataList = basalWatchDataList; - this.bolusWatchDataList = (bolusWatchDataList!=null)?bolusWatchDataList:new ArrayList(); - this.gridColour = gridColour; - this.basalCenterColor = basalCenterColor; - this.basalBackgroundColor = basalBackgroundColor; - this.bolusInvalidColor = bolusInvalidColor; - this.carbsColor = carbsColor; - this.end_time = System.currentTimeMillis() + (1000 * 60 * 6 * timespan); //Now plus 30 minutes padding (for 5 hours. Less if less.) - this.predictionEndTime = getPredictionEndTime(); - this.end_time = (predictionEndTime>end_time)?predictionEndTime:end_time; - } - - public BgGraphBuilder(Context context, RawDisplayData raw, int aPointSize, int aHighColor, int aLowColor, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) { - this(context, - raw.bgDataList, - raw.predictionList, - raw.tempWatchDataList, - raw.basalWatchDataList, - raw.bolusWatchDataList, - aPointSize, - aHighColor, - aLowColor, - aMidColor, - gridColour, - basalBackgroundColor, - basalCenterColor, - bolusInvalidColor, - carbsColor, - timespan); - } - - public BgGraphBuilder(Context context, RawDisplayData raw, int aPointSize, int aMidColor, int gridColour, int basalBackgroundColor, int basalCenterColor, int bolusInvalidColor, int carbsColor, int timespan) { - this(context, - raw.bgDataList, - raw.predictionList, - raw.tempWatchDataList, - raw.basalWatchDataList, - raw.bolusWatchDataList, - aPointSize, - aMidColor, - gridColour, - basalBackgroundColor, - basalCenterColor, - bolusInvalidColor, - carbsColor, - timespan); - } - - public LineChartData lineData() { - LineChartData lineData = new LineChartData(defaultLines()); - lineData.setAxisYLeft(yAxis()); - lineData.setAxisXBottom(xAxis()); - return lineData; - } - - public List defaultLines() { - - addBgReadingValues(); - List lines = new ArrayList(); - lines.add(highLine()); - lines.add(lowLine()); - lines.add(inRangeValuesLine()); - lines.add(lowValuesLine()); - lines.add(highValuesLine()); - - double minChart = lowMark; - double maxChart = highMark; - - for ( BgWatchData bgd:bgDataList) { - if(bgd.sgv > maxChart){ - maxChart = bgd.sgv; - } - if(bgd.sgv < minChart){ - minChart = bgd.sgv; - } - } - - double maxBasal = 0.1; - for (BasalWatchData bwd: basalWatchDataList) { - if(bwd.amount > maxBasal){ - maxBasal = bwd.amount; - } - } - - double maxTemp = maxBasal; - for (TempWatchData twd: tempWatchDataList) { - if(twd.amount > maxTemp){ - maxTemp = twd.amount; - } - } - - double factor = (maxChart-minChart)/maxTemp; - // in case basal is the highest, don't paint it totally at the top. - factor = Math.min(factor, ((maxChart-minChart)/maxBasal)*(2/3d)); - - boolean highlight = PreferenceManager - .getDefaultSharedPreferences(context) - .getBoolean("highlight_basals", false); - - for (TempWatchData twd: tempWatchDataList) { - if(twd.endTime > start_time) { - lines.add(tempValuesLine(twd, (float) minChart, factor, false, highlight?(pointSize+1):pointSize)); - if(highlight){ - lines.add(tempValuesLine(twd, (float) minChart, factor, true, 1)); - } - } - } - - addPredictionLines(lines); - lines.add(basalLine((float) minChart, factor, highlight)); - lines.add(bolusLine((float) minChart)); - lines.add(bolusInvalidLine((float) minChart)); - lines.add(carbsLine((float) minChart)); - lines.add(smbLine((float) minChart)); - - return lines; - } - - private Line basalLine(float offset, double factor, boolean highlight) { - - List pointValues = new ArrayList(); - - for (BasalWatchData bwd: basalWatchDataList) { - if(bwd.endTime > start_time) { - long begin = Math.max(start_time, bwd.startTime); - pointValues.add(new PointValue(fuzz(begin), offset + (float) (factor * bwd.amount))); - pointValues.add(new PointValue(fuzz(bwd.endTime), offset + (float) (factor * bwd.amount))); - } - } - - Line basalLine = new Line(pointValues); - basalLine.setHasPoints(false); - basalLine.setColor(basalCenterColor); - basalLine.setPathEffect(new DashPathEffect(new float[]{4f, 3f}, 4f)); - basalLine.setStrokeWidth(highlight?2:1); - return basalLine; - - - } - - private Line bolusLine(float offset) { - - List pointValues = new ArrayList(); - - for (BolusWatchData bwd: bolusWatchDataList) { - if(bwd.date > start_time && bwd.date <= end_time && !bwd.isSMB && bwd.isValid && bwd.bolus > 0) { - pointValues.add(new PointValue(fuzz(bwd.date), offset -2)); - } - } - Line line = new Line(pointValues); - line.setColor(basalCenterColor); - line.setHasLines(false); - line.setPointRadius(pointSize*2); - line.setHasPoints(true); - return line; - } - - private Line smbLine(float offset) { - - List pointValues = new ArrayList(); - - for (BolusWatchData bwd: bolusWatchDataList) { - if(bwd.date > start_time && bwd.date <= end_time && bwd.isSMB && bwd.isValid && bwd.bolus > 0) { - pointValues.add(new PointValue(fuzz(bwd.date), offset -2)); - } - } - Line line = new Line(pointValues); - line.setColor(basalCenterColor); - line.setHasLines(false); - line.setPointRadius(pointSize); - line.setHasPoints(true); - return line; - } - - private Line bolusInvalidLine(float offset) { - - List pointValues = new ArrayList(); - - for (BolusWatchData bwd: bolusWatchDataList) { - if(bwd.date > start_time && bwd.date <= end_time && !(bwd.isValid && (bwd.bolus > 0 || bwd.carbs > 0))) { - pointValues.add(new PointValue(fuzz(bwd.date), offset -2)); - } - } - Line line = new Line(pointValues); - line.setColor(bolusInvalidColor); - line.setHasLines(false); - line.setPointRadius(pointSize); - line.setHasPoints(true); - return line; - } - - private Line carbsLine(float offset) { - - List pointValues = new ArrayList(); - - for (BolusWatchData bwd: bolusWatchDataList) { - if(bwd.date > start_time && bwd.date <= end_time && !bwd.isSMB && bwd.isValid && bwd.carbs > 0) { - pointValues.add(new PointValue(fuzz(bwd.date), offset +2)); - } - } - Line line = new Line(pointValues); - line.setColor(carbsColor); - line.setHasLines(false); - line.setPointRadius(pointSize*2); - line.setHasPoints(true); - return line; - } - - - private void addPredictionLines(List lines) { - Map> values = new HashMap<>(); - long endTime = getPredictionEndTime(); - for (BgWatchData bwd : predictionsList) { - if (bwd.timestamp <= endTime) { - double value = Math.min(bwd.sgv, UPPER_CUTOFF_SGV); - if (!values.containsKey(bwd.color)) { - values.put(bwd.color, new ArrayList<>()); - } - values.get(bwd.color).add(new PointValue(fuzz(bwd.timestamp), (float) value)); - } - } - for (Map.Entry> entry : values.entrySet()) { - Line line = new Line(entry.getValue()); - line.setColor(entry.getKey()); - line.setHasLines(false); - int size = pointSize / 2; - size = (size > 0) ? size : 1; - line.setPointRadius(size); - line.setHasPoints(true); - lines.add(line); - } - } - - public Line highValuesLine() { - Line highValuesLine = new Line(highValues); - highValuesLine.setColor(highColor); - highValuesLine.setHasLines(false); - highValuesLine.setPointRadius(pointSize); - highValuesLine.setHasPoints(true); - return highValuesLine; - } - - public Line lowValuesLine() { - Line lowValuesLine = new Line(lowValues); - lowValuesLine.setColor(lowColor); - lowValuesLine.setHasLines(false); - lowValuesLine.setPointRadius(pointSize); - lowValuesLine.setHasPoints(true); - return lowValuesLine; - } - - public Line inRangeValuesLine() { - Line inRangeValuesLine = new Line(inRangeValues); - inRangeValuesLine.setColor(midColor); - if(singleLine) { - inRangeValuesLine.setHasLines(true); - inRangeValuesLine.setHasPoints(false); - inRangeValuesLine.setStrokeWidth(pointSize); - } else { - inRangeValuesLine.setPointRadius(pointSize); - inRangeValuesLine.setHasPoints(true); - inRangeValuesLine.setHasLines(false); - } - return inRangeValuesLine; - } - - - public Line tempValuesLine(TempWatchData twd, float offset, double factor, boolean isHighlightLine, int strokeWidth) { - List lineValues = new ArrayList(); - long begin = Math.max(start_time, twd.startTime); - lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.startBasal))); - lineValues.add(new PointValue(fuzz(begin), offset + (float) (factor * twd.amount))); - lineValues.add(new PointValue(fuzz(twd.endTime), offset + (float) (factor * twd.amount))); - lineValues.add(new PointValue(fuzz(twd.endTime), offset + (float) (factor * twd.endBasal))); - Line valueLine = new Line(lineValues); - valueLine.setHasPoints(false); - if (isHighlightLine){ - valueLine.setColor(basalCenterColor); - valueLine.setStrokeWidth(1); - }else { - valueLine.setColor(basalBackgroundColor); - valueLine.setStrokeWidth(strokeWidth); - } - return valueLine; - } - - - - - private void addBgReadingValues() { - if(singleLine) { - for (BgWatchData bgReading : bgDataList) { - if(bgReading.timestamp > start_time) { - if (bgReading.sgv >= 450) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) 450)); - } else if (bgReading.sgv >= highMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= lowMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= 40) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= 11) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) 40)); - } - } - } - } else { - for (BgWatchData bgReading : bgDataList) { - if (bgReading.timestamp > start_time) { - if (bgReading.sgv >= 450) { - highValues.add(new PointValue(fuzz(bgReading.timestamp), (float) 450)); - } else if (bgReading.sgv >= highMark) { - highValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= lowMark) { - inRangeValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= 40) { - lowValues.add(new PointValue(fuzz(bgReading.timestamp), (float) bgReading.sgv)); - } else if (bgReading.sgv >= 11) { - lowValues.add(new PointValue(fuzz(bgReading.timestamp), (float) 40)); - } - } - } - } - } - - public Line highLine() { - List highLineValues = new ArrayList(); - highLineValues.add(new PointValue(fuzz(start_time), (float) highMark)); - highLineValues.add(new PointValue(fuzz(end_time), (float) highMark)); - Line highLine = new Line(highLineValues); - highLine.setHasPoints(false); - highLine.setStrokeWidth(1); - highLine.setColor(highColor); - return highLine; - } - - public Line lowLine() { - List lowLineValues = new ArrayList(); - lowLineValues.add(new PointValue(fuzz(start_time), (float) lowMark)); - lowLineValues.add(new PointValue(fuzz(end_time), (float) lowMark)); - Line lowLine = new Line(lowLineValues); - lowLine.setHasPoints(false); - lowLine.setColor(lowColor); - lowLine.setStrokeWidth(1); - return lowLine; - } - - /////////AXIS RELATED////////////// - - - public Axis yAxis() { - Axis yAxis = new Axis(); - yAxis.setAutoGenerated(true); - List axisValues = new ArrayList(); - yAxis.setValues(axisValues); - yAxis.setHasLines(false); - yAxis.setLineColor(gridColour); - return yAxis; - } - - public Axis xAxis() { - final boolean is24 = DateFormat.is24HourFormat(context); - SimpleDateFormat timeFormat = new SimpleDateFormat(is24? "HH" : "h a"); - timeFormat.setTimeZone(TimeZone.getDefault()); - long timeNow = System.currentTimeMillis(); - - Axis xAxis = new Axis(); - xAxis.setAutoGenerated(false); - List xAxisValues = new ArrayList(); - - //get the time-tick at the full hour after start_time - GregorianCalendar startGC = new GregorianCalendar(); - startGC.setTimeInMillis(start_time); - startGC.set(Calendar.MILLISECOND, 0); - startGC.set(Calendar.SECOND, 0); - startGC.set(Calendar.MINUTE, 0); - startGC.add(Calendar.HOUR, 1); - long start_hour = startGC.getTimeInMillis(); - - //Display current time on the graph - SimpleDateFormat longTimeFormat = new SimpleDateFormat(is24? "HH:mm" : "h:mm a"); - xAxisValues.add(new AxisValue(fuzz(timeNow)).setLabel((longTimeFormat.format(timeNow)))); - - long hourTick = start_hour; - - // add all full hours within the timeframe - while (hourTick < end_time){ - if(Math.abs(hourTick - timeNow) > (8 * (end_time-start_time)/60)){ - xAxisValues.add(new AxisValue(fuzz(hourTick)).setLabel(timeFormat.format(hourTick))); - } else { - //don't print hour label if too close to now to avoid overlaps - xAxisValues.add(new AxisValue(fuzz(hourTick)).setLabel("")); - } - - //increment by one hour - hourTick += 60*60*1000; - } - - xAxis.setValues(xAxisValues); - xAxis.setTextSize(10); - xAxis.setHasLines(true); - xAxis.setLineColor(gridColour); - xAxis.setTextColor(gridColour); - - return xAxis; - } - - public long getPredictionEndTime() { - long maxPredictionDate = System.currentTimeMillis(); - for (BgWatchData prediction : - predictionsList) { - if (maxPredictionDate < prediction.timestamp) { - maxPredictionDate = prediction.timestamp; - } - } - return (long) Math.min(maxPredictionDate, System.currentTimeMillis() + MAX_PREDICTION__TIME_RATIO *timespan*1000*60*60); - } - - public float fuzz(long value) { - return (float) Math.round(value / fuzzyTimeDenom); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.kt new file mode 100644 index 0000000000..48b7d340f4 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BgGraphBuilder.kt @@ -0,0 +1,367 @@ +package info.nightscout.androidaps.watchfaces + +import android.graphics.DashPathEffect +import info.nightscout.androidaps.R +import info.nightscout.androidaps.utils.DateUtil +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.SingleBg +import info.nightscout.shared.weardata.EventData.TreatmentData.Basal +import lecho.lib.hellocharts.model.Axis +import lecho.lib.hellocharts.model.AxisValue +import lecho.lib.hellocharts.model.Line +import lecho.lib.hellocharts.model.LineChartData +import lecho.lib.hellocharts.model.PointValue +import java.util.* +import kotlin.math.abs +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToLong + +class BgGraphBuilder( + private val sp: SP, + private val dateUtil: DateUtil, + private val bgDataList: List, + private val predictionsList: List, + private val tempWatchDataList: List, + private val basalWatchDataList: ArrayList, + private val bolusWatchDataList: ArrayList, + private val pointSize: Int, + private val highColor: Int, + private val lowColor: Int, + private val midColor: Int, + private val gridColour: Int, + private val basalBackgroundColor: Int, + private val basalCenterColor: Int, + private val bolusInvalidColor: Int, + private val carbsColor: Int, + private val timeSpan: Int +) { + + private val predictionEndTime: Long + private var endingTime: Long = System.currentTimeMillis() + 1000L * 60 * 6 * timeSpan + private var startingTime: Long = System.currentTimeMillis() - 1000L * 60 * 60 * timeSpan + private var fuzzyTimeDiv = (1000 * 60 * 1).toDouble() + private var highMark: Double = bgDataList[bgDataList.size - 1].high + private var lowMark: Double = bgDataList[bgDataList.size - 1].low + private val inRangeValues: MutableList = ArrayList() + private val highValues: MutableList = ArrayList() + private val lowValues: MutableList = ArrayList() + + init { + predictionEndTime = getPredictionEndTime() + endingTime = max(predictionEndTime, endingTime) + } + + //used for low resolution screen. + constructor( + sp: SP, dateUtil: DateUtil, + aBgList: List, + predictionsList: List, + tempWatchDataList: List, + basalWatchDataList: ArrayList, + bolusWatchDataList: ArrayList, + aPointSize: Int, aMidColor: Int, gridColour: Int, basalBackgroundColor: Int, basalCenterColor: Int, bolusInvalidColor: Int, carbsColor: Int, timeSpan: Int + ) : this( + sp, dateUtil, + aBgList, predictionsList, tempWatchDataList, basalWatchDataList, + bolusWatchDataList, aPointSize, aMidColor, aMidColor, aMidColor, gridColour, + basalBackgroundColor, basalCenterColor, bolusInvalidColor, carbsColor, timeSpan + ) + + fun lineData(): LineChartData { + val lineData = LineChartData(defaultLines()) + lineData.axisYLeft = yAxis() + lineData.axisXBottom = xAxis() + return lineData + } + + private fun defaultLines(): List { + addBgReadingValues() + val lines: MutableList = ArrayList() + lines.add(highLine()) + lines.add(lowLine()) + lines.add(inRangeValuesLine()) + lines.add(lowValuesLine()) + lines.add(highValuesLine()) + var minChart = lowMark + var maxChart = highMark + for ((_, _, _, _, _, _, _, sgv) in bgDataList) { + if (sgv > maxChart) maxChart = sgv + if (sgv < minChart) minChart = sgv + } + var maxBasal = 0.1 + for ((_, _, amount) in basalWatchDataList) { + if (amount > maxBasal) maxBasal = amount + } + var maxTemp = maxBasal + for ((_, _, _, _, amount) in tempWatchDataList) { + if (amount > maxTemp) maxTemp = amount + } + var factor = (maxChart - minChart) / maxTemp + // in case basal is the highest, don't paint it totally at the top. + factor = min(factor, (maxChart - minChart) / maxBasal * (2 / 3.0)) + val highlight = sp.getBoolean(R.string.key_highlight_basals, false) + for (twd in tempWatchDataList) { + if (twd.endTime > startingTime) { + lines.add(tempValuesLine(twd, minChart.toFloat(), factor, false, if (highlight) pointSize + 1 else pointSize)) + if (highlight) lines.add(tempValuesLine(twd, minChart.toFloat(), factor, true, 1)) + } + } + addPredictionLines(lines) + lines.add(basalLine(minChart.toFloat(), factor, highlight)) + lines.add(bolusLine(minChart.toFloat())) + lines.add(bolusInvalidLine(minChart.toFloat())) + lines.add(carbsLine(minChart.toFloat())) + lines.add(smbLine(minChart.toFloat())) + return lines + } + + private fun basalLine(offset: Float, factor: Double, highlight: Boolean): Line { + val pointValues: MutableList = ArrayList() + for ((startTime, endTime, amount) in basalWatchDataList) { + if (endTime > startingTime) { + val begin = max(startingTime, startTime) + pointValues.add(PointValue(fuzz(begin), offset + (factor * amount).toFloat())) + pointValues.add(PointValue(fuzz(endTime), offset + (factor * amount).toFloat())) + } + } + return Line(pointValues).also { basalLine -> + basalLine.setHasPoints(false) + basalLine.color = basalCenterColor + basalLine.pathEffect = DashPathEffect(floatArrayOf(4f, 3f), 4f) + basalLine.strokeWidth = if (highlight) 2 else 1 + } + } + + private fun bolusLine(offset: Float): Line { + val pointValues: MutableList = ArrayList() + for ((date, bolus, _, isSMB, isValid) in bolusWatchDataList) { + if (date in (startingTime + 1)..endingTime && !isSMB && isValid && bolus > 0) { + pointValues.add(PointValue(fuzz(date), offset - 2)) + } + } + return Line(pointValues).also { line -> + line.color = basalCenterColor + line.setHasLines(false) + line.pointRadius = pointSize * 2 + line.setHasPoints(true) + } + } + + private fun smbLine(offset: Float): Line { + val pointValues: MutableList = ArrayList() + for ((date, bolus, _, isSMB, isValid) in bolusWatchDataList) { + if (date in (startingTime + 1)..endingTime && isSMB && isValid && bolus > 0) { + pointValues.add(PointValue(fuzz(date), offset - 2)) + } + } + return Line(pointValues).also { line -> + line.color = basalCenterColor + line.setHasLines(false) + line.pointRadius = pointSize + line.setHasPoints(true) + } + } + + private fun bolusInvalidLine(offset: Float): Line { + val pointValues: MutableList = ArrayList() + for ((date, bolus, carbs, _, isValid) in bolusWatchDataList) { + if (date in (startingTime + 1)..endingTime && !(isValid && (bolus > 0 || carbs > 0))) { + pointValues.add(PointValue(fuzz(date), offset - 2)) + } + } + return Line(pointValues).also { line -> + line.color = bolusInvalidColor + line.setHasLines(false) + line.pointRadius = pointSize + line.setHasPoints(true) + } + } + + private fun carbsLine(offset: Float): Line { + val pointValues: MutableList = ArrayList() + for ((date, _, carbs, isSMB, isValid) in bolusWatchDataList) { + if (date in (startingTime + 1)..endingTime && !isSMB && isValid && carbs > 0) { + pointValues.add(PointValue(fuzz(date), offset + 2)) + } + } + return Line(pointValues).also { line -> + line.color = carbsColor + line.setHasLines(false) + line.pointRadius = pointSize * 2 + line.setHasPoints(true) + } + } + + private fun addPredictionLines(lines: MutableList) { + val values: MutableMap> = HashMap() + val endTime = getPredictionEndTime() + for ((timeStamp, _, _, _, _, _, _, sgv, _, _, color) in predictionsList) { + if (timeStamp <= endTime) { + val value = min(sgv, UPPER_CUTOFF_SGV) + if (!values.containsKey(color)) { + values[color] = ArrayList() + } + values[color]!!.add(PointValue(fuzz(timeStamp), value.toFloat())) + } + } + for ((key, value) in values) { + val line = Line(value) + line.color = key + line.setHasLines(false) + var size = pointSize / 2 + size = if (size > 0) size else 1 + line.pointRadius = size + line.setHasPoints(true) + lines.add(line) + } + } + + private fun highValuesLine(): Line = + Line(highValues).also { highValuesLine -> + highValuesLine.color = highColor + highValuesLine.setHasLines(false) + highValuesLine.pointRadius = pointSize + highValuesLine.setHasPoints(true) + } + + private fun lowValuesLine(): Line = + Line(lowValues).also { lowValuesLine -> + lowValuesLine.color = lowColor + lowValuesLine.setHasLines(false) + lowValuesLine.pointRadius = pointSize + lowValuesLine.setHasPoints(true) + } + + private fun inRangeValuesLine(): Line = + Line(inRangeValues).also { inRangeValuesLine -> + inRangeValuesLine.color = midColor + inRangeValuesLine.pointRadius = pointSize + inRangeValuesLine.setHasPoints(true) + inRangeValuesLine.setHasLines(false) + } + + private fun tempValuesLine(twd: EventData.TreatmentData.TempBasal, offset: Float, factor: Double, isHighlightLine: Boolean, strokeWidth: Int): Line { + val lineValues: MutableList = ArrayList() + val begin = max(startingTime, twd.startTime) + lineValues.add(PointValue(fuzz(begin), offset + (factor * twd.startBasal).toFloat())) + lineValues.add(PointValue(fuzz(begin), offset + (factor * twd.amount).toFloat())) + lineValues.add(PointValue(fuzz(twd.endTime), offset + (factor * twd.amount).toFloat())) + lineValues.add(PointValue(fuzz(twd.endTime), offset + (factor * twd.endBasal).toFloat())) + return Line(lineValues).also { valueLine -> + valueLine.setHasPoints(false) + if (isHighlightLine) { + valueLine.color = basalCenterColor + valueLine.strokeWidth = 1 + } else { + valueLine.color = basalBackgroundColor + valueLine.strokeWidth = strokeWidth + } + } + } + + private fun addBgReadingValues() { + for ((timeStamp, _, _, _, _, _, _, sgv) in bgDataList) { + if (timeStamp > startingTime) { + when { + sgv >= 450 -> highValues.add(PointValue(fuzz(timeStamp), 450.toFloat())) + sgv >= highMark -> highValues.add(PointValue(fuzz(timeStamp), sgv.toFloat())) + sgv >= lowMark -> inRangeValues.add(PointValue(fuzz(timeStamp), sgv.toFloat())) + sgv >= 40 -> lowValues.add(PointValue(fuzz(timeStamp), sgv.toFloat())) + sgv >= 11 -> lowValues.add(PointValue(fuzz(timeStamp), 40.toFloat())) + } + } + } + } + + private fun highLine(): Line { + val highLineValues: MutableList = ArrayList() + highLineValues.add(PointValue(fuzz(startingTime), highMark.toFloat())) + highLineValues.add(PointValue(fuzz(endingTime), highMark.toFloat())) + return Line(highLineValues).also { highLine -> + highLine.setHasPoints(false) + highLine.strokeWidth = 1 + highLine.color = highColor + } + } + + private fun lowLine(): Line { + val lowLineValues: MutableList = ArrayList() + lowLineValues.add(PointValue(fuzz(startingTime), lowMark.toFloat())) + lowLineValues.add(PointValue(fuzz(endingTime), lowMark.toFloat())) + return Line(lowLineValues).also { lowLine -> + lowLine.setHasPoints(false) + lowLine.color = lowColor + lowLine.strokeWidth = 1 + } + } + + /////////AXIS RELATED////////////// + private fun yAxis(): Axis = + Axis().also { yAxis -> + yAxis.isAutoGenerated = true + val axisValues: List = ArrayList() + yAxis.values = axisValues + yAxis.setHasLines(false) + yAxis.lineColor = gridColour + } + + private fun xAxis(): Axis { + val timeNow = System.currentTimeMillis() + val xAxis = Axis() + xAxis.isAutoGenerated = false + val xAxisValues: MutableList = ArrayList() + + //get the time-tick at the full hour after start_time + val startGC = GregorianCalendar() + startGC.timeInMillis = startingTime + startGC[Calendar.MILLISECOND] = 0 + startGC[Calendar.SECOND] = 0 + startGC[Calendar.MINUTE] = 0 + startGC.add(Calendar.HOUR, 1) + + //Display current time on the graph + xAxisValues.add(AxisValue(fuzz(timeNow)).setLabel(dateUtil.timeString(timeNow))) + var hourTick = startGC.timeInMillis + + // add all full hours within the timeframe + while (hourTick < endingTime) { + if (abs(hourTick - timeNow) > 8 * (endingTime - startingTime) / 60) { + xAxisValues.add(AxisValue(fuzz(hourTick)).setLabel(dateUtil.hourString(hourTick))) + } else { + //don't print hour label if too close to now to avoid overlaps + xAxisValues.add(AxisValue(fuzz(hourTick)).setLabel("")) + } + + //increment by one hour + hourTick += (60 * 60 * 1000).toLong() + } + xAxis.values = xAxisValues + xAxis.textSize = 10 + xAxis.setHasLines(true) + xAxis.lineColor = gridColour + xAxis.textColor = gridColour + return xAxis + } + + private fun getPredictionEndTime(): Long { + var maxPredictionDate = System.currentTimeMillis() + for ((timeStamp) in predictionsList) { + if (maxPredictionDate < timeStamp) { + maxPredictionDate = timeStamp + } + } + return min(maxPredictionDate.toDouble(), System.currentTimeMillis() + MAX_PREDICTION__TIME_RATIO * timeSpan * 1000 * 60 * 60).toLong() + } + + private fun fuzz(value: Long): Float { + return (value / fuzzyTimeDiv).roundToLong().toFloat() + } + + companion object { + + const val MAX_PREDICTION__TIME_RATIO = 3.0 / 5 + const val UPPER_CUTOFF_SGV = 400.0 + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt new file mode 100644 index 0000000000..8fe6eaae33 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/BigChartWatchface.kt @@ -0,0 +1,121 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R + +class BigChartWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = + if (resources.displayMetrics.widthPixels < SCREEN_SIZE_SMALL || resources.displayMetrics.heightPixels < SCREEN_SIZE_SMALL) R.layout.activity_bigchart_small + else R.layout.activity_bigchart + + override fun setDataFields() { + super.setDataFields() + mStatus?.text = status.externalStatus + if (sp.getBoolean(R.string.key_show_cob, true)) (" " + this.status.cob) else "" + } + + override fun setColorLowRes() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_midColor) + lowColor = ContextCompat.getColor(this, R.color.dark_midColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark_lowres) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light_lowres) + pointSize = 2 + setupCharts() + } + } + + override fun setColorDark() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + } else { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + } + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_highColor) + lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) + pointSize = 2 + setupCharts() + } + } + + override fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp1)) + else mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp)) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.light_highColor) + lowColor = ContextCompat.getColor(this, R.color.light_lowColor) + midColor = ContextCompat.getColor(this, R.color.light_midColor) + gridColor = ContextCompat.getColor(this, R.color.light_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_light) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) + pointSize = 2 + setupCharts() + } + } else { + setColorDark() + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java deleted file mode 100644 index f4c7d18a90..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.java +++ /dev/null @@ -1,731 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.LinearGradient; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.RectF; -import android.graphics.Shader; -import android.os.Bundle; -import android.os.PowerManager; -import android.os.SystemClock; -import android.preference.PreferenceManager; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import android.support.wearable.watchface.WatchFaceStyle; -import android.util.Log; -import android.util.TypedValue; -import android.view.Display; -import android.view.LayoutInflater; -import android.view.View; -import android.view.WindowManager; -import android.widget.TextView; - -import com.google.android.gms.wearable.DataMap; -import com.ustwo.clockwise.common.WatchFaceTime; -import com.ustwo.clockwise.wearable.WatchFace; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.HashSet; -import java.util.TreeSet; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.BgWatchData; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - - -public class CircleWatchface extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { - public final float PADDING = 20f; - public final float CIRCLE_WIDTH = 10f; - public final int BIG_HAND_WIDTH = 16; - public final int SMALL_HAND_WIDTH = 8; - public final int NEAR = 2; //how near do the hands have endTime be endTime activate overlapping mode - public final boolean ALWAYS_HIGHLIGT_SMALL = false; - - //variables for time - private float angleBig = 0f; - private float angleSMALL = 0f; - private int hour, minute; - private int color; - private final Paint circlePaint = new Paint(); - private final Paint removePaint = new Paint(); - private RectF rect, rectDelete; - private boolean overlapping; - - private int animationAngle = 0; - private boolean isAnimated = false; - - - public Point displaySize = new Point(); - private final MessageReceiver messageReceiver = new MessageReceiver(); - - private int sgvLevel = 0; - private String sgvString = "999"; - private String statusString = "no status"; - - - private int batteryLevel = 0; - private long datetime = 0; - private String direction = ""; - private String delta = ""; - private String avgDelta = ""; - public TreeSet bgDataList = new TreeSet<>(); - - private int specW; - private int specH; - private View myLayout; - - protected SharedPreferences sharedPrefs; - private TextView mSgv; - private long sgvTapTime = 0; - - - @Override - public void onCreate() { - super.onCreate(); - - PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); - PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:CircleWatchface"); - wakeLock.acquire(30000); - - Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay(); - display.getSize(displaySize); - - specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, - View.MeasureSpec.EXACTLY); - specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, - View.MeasureSpec.EXACTLY); - - sharedPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - sharedPrefs.registerOnSharedPreferenceChangeListener(this); - - //register Message Receiver - LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, new IntentFilter(Intent.ACTION_SEND)); - - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - myLayout = inflater.inflate(R.layout.modern_layout, null); - prepareLayout(); - prepareDrawTime(); - - //ListenerService.requestData(this); //usually connection is not set up yet - - wakeLock.release(); - } - - - @Override - public void onDestroy() { - if (messageReceiver != null) { - LocalBroadcastManager.getInstance(this).unregisterReceiver(messageReceiver); - } - if (sharedPrefs != null) { - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } - super.onDestroy(); - } - - @Override - protected synchronized void onDraw(Canvas canvas) { - Log.d("CircleWatchface", "start onDraw"); - canvas.drawColor(getBackgroundColor()); - drawTime(canvas); - drawOtherStuff(canvas); - myLayout.draw(canvas); - - } - - private synchronized void prepareLayout() { - - Log.d("CircleWatchface", "start startPrepareLayout"); - - // prepare fields - - TextView textView; - mSgv = myLayout.findViewById(R.id.sgvString); - textView = myLayout.findViewById(R.id.sgvString); - if (sharedPrefs.getBoolean("showBG", true)) { - textView.setVisibility(View.VISIBLE); - textView.setText(getSgvString()); - textView.setTextColor(getTextColor()); - - } else { - //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - textView.setVisibility(View.INVISIBLE); - } - - textView = myLayout.findViewById(R.id.statusString); - if (sharedPrefs.getBoolean("showExternalStatus", true)) { - textView.setVisibility(View.VISIBLE); - textView.setText(getStatusString()); - textView.setTextColor(getTextColor()); - - } else { - //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - textView.setVisibility(View.GONE); - } - - textView = myLayout.findViewById(R.id.agoString); - if (sharedPrefs.getBoolean("showAgo", true)) { - textView.setVisibility(View.VISIBLE); - - if (sharedPrefs.getBoolean("showBigNumbers", false)) { - textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26); - } else { - ((TextView) myLayout.findViewById(R.id.agoString)).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); - } - textView.setText(getMinutes()); - textView.setTextColor(getTextColor()); - } else { - //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - textView.setVisibility(View.INVISIBLE); - } - - textView = myLayout.findViewById(R.id.deltaString); - if (sharedPrefs.getBoolean("showDelta", true)) { - textView.setVisibility(View.VISIBLE); - textView.setText(getDelta()); - textView.setTextColor(getTextColor()); - if (sharedPrefs.getBoolean("showBigNumbers", false)) { - textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25); - } else { - textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); - } - if (sharedPrefs.getBoolean("showAvgDelta", true)) { - textView.append(" " + getAvgDelta()); - } - - } else { - //Also possible: View.INVISIBLE instead of View.GONE (no layout change) - textView.setVisibility(View.INVISIBLE); - } - - myLayout.measure(specW, specH); - myLayout.layout(0, 0, myLayout.getMeasuredWidth(), - myLayout.getMeasuredHeight()); - } - - public String getMinutes() { - String minutes = "--'"; - if (getDatetime() != 0) { - minutes = ((int) Math.floor((System.currentTimeMillis() - getDatetime()) / 60000.0)) + "'"; - } - return minutes; - } - - private void drawTime(Canvas canvas) { - - //draw circle - circlePaint.setColor(color); - circlePaint.setStrokeWidth(CIRCLE_WIDTH); - canvas.drawArc(rect, 0, 360, false, circlePaint); - //"remove" hands from circle - removePaint.setStrokeWidth(CIRCLE_WIDTH * 3); - - canvas.drawArc(rectDelete, angleBig, (float) BIG_HAND_WIDTH, false, removePaint); - canvas.drawArc(rectDelete, angleSMALL, (float) SMALL_HAND_WIDTH, false, removePaint); - - - if (overlapping) { - //add small hand with extra - circlePaint.setStrokeWidth(CIRCLE_WIDTH * 2); - circlePaint.setColor(color); - canvas.drawArc(rect, angleSMALL, (float) SMALL_HAND_WIDTH, false, circlePaint); - - //remove inner part of hands - removePaint.setStrokeWidth(CIRCLE_WIDTH); - canvas.drawArc(rect, angleBig, (float) BIG_HAND_WIDTH, false, removePaint); - canvas.drawArc(rect, angleSMALL, (float) SMALL_HAND_WIDTH, false, removePaint); - } - - } - - private synchronized void prepareDrawTime() { - Log.d("CircleWatchface", "start prepareDrawTime"); - - hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY) % 12; - minute = Calendar.getInstance().get(Calendar.MINUTE); - angleBig = (((hour + minute / 60f) / 12f * 360) - 90 - BIG_HAND_WIDTH / 2f + 360) % 360; - angleSMALL = ((minute / 60f * 360) - 90 - SMALL_HAND_WIDTH / 2f + 360) % 360; - - - color = 0; - switch (getSgvLevel()) { - case -1: - color = getLowColor(); - break; - case 0: - color = getInRangeColor(); - break; - case 1: - color = getHighColor(); - break; - } - - - if (isAnimated()) { - //Animation matrix: - int[] rainbow = {Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE - , Color.CYAN}; - Shader shader = new LinearGradient(0, 0, 0, 20, rainbow, - null, Shader.TileMode.MIRROR); - Matrix matrix = new Matrix(); - matrix.setRotate(animationAngle); - shader.setLocalMatrix(matrix); - circlePaint.setShader(shader); - } else { - circlePaint.setShader(null); - } - - - circlePaint.setStyle(Paint.Style.STROKE); - circlePaint.setStrokeWidth(CIRCLE_WIDTH); - circlePaint.setAntiAlias(true); - circlePaint.setColor(color); - - removePaint.setStyle(Paint.Style.STROKE); - removePaint.setStrokeWidth(CIRCLE_WIDTH); - removePaint.setAntiAlias(true); - removePaint.setColor(getBackgroundColor()); - - rect = new RectF(PADDING, PADDING, displaySize.x - PADDING, displaySize.y - PADDING); - rectDelete = new RectF(PADDING - CIRCLE_WIDTH / 2, PADDING - CIRCLE_WIDTH / 2, displaySize.x - PADDING + CIRCLE_WIDTH / 2, displaySize.y - PADDING + CIRCLE_WIDTH / 2); - overlapping = ALWAYS_HIGHLIGT_SMALL || areOverlapping(angleSMALL, angleSMALL + SMALL_HAND_WIDTH + NEAR, angleBig, angleBig + BIG_HAND_WIDTH + NEAR); - Log.d("CircleWatchface", "end prepareDrawTime"); - - } - - synchronized void animationStep() { - animationAngle = (animationAngle + 1) % 360; - prepareDrawTime(); - invalidate(); - } - - - private boolean areOverlapping(float aBegin, float aEnd, float bBegin, float bEnd) { - return - aBegin <= bBegin && aEnd >= bBegin || - aBegin <= bBegin && (bEnd > 360) && bEnd % 360 > aBegin || - bBegin <= aBegin && bEnd >= aBegin || - bBegin <= aBegin && aEnd > 360 && aEnd % 360 > bBegin; - } - - @Override - protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) { - if (oldTime.hasMinuteChanged(newTime)) { - PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); - PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:CircleWatchface_onTimeChanged"); - wakeLock.acquire(30000); - /*Preparing the layout just on every minute tick: - * - hopefully better battery life - * - drawback: might update the minutes since last reading up endTime one minute late*/ - prepareLayout(); - prepareDrawTime(); - invalidate(); //redraw the time - wakeLock.release(); - - } - } - - - // defining color for dark and bright - public int getLowColor() { - if (sharedPrefs.getBoolean("dark", true)) { - return Color.argb(255, 255, 120, 120); - } else { - return Color.argb(255, 255, 80, 80); - } - } - - public int getInRangeColor() { - if (sharedPrefs.getBoolean("dark", true)) { - return Color.argb(255, 120, 255, 120); - } else { - return Color.argb(255, 0, 240, 0); - - } - } - - public int getHighColor() { - if (sharedPrefs.getBoolean("dark", true)) { - return Color.argb(255, 255, 255, 120); - } else { - return Color.argb(255, 255, 200, 0); - } - - } - - public int getBackgroundColor() { - if (sharedPrefs.getBoolean("dark", true)) { - return Color.BLACK; - } else { - return Color.WHITE; - - } - } - - public int getTextColor() { - if (sharedPrefs.getBoolean("dark", true)) { - return Color.WHITE; - } else { - return Color.BLACK; - - } - } - - public void drawOtherStuff(Canvas canvas) { - Log.d("CircleWatchface", "start onDrawOtherStuff. bgDataList.size(): " + bgDataList.size()); - - if (isAnimated()) return; // too many repaints when animated - if (sharedPrefs.getBoolean("showRingHistory", false)) { - //Perfect low and High indicators - if (bgDataList.size() > 0) { - addIndicator(canvas, 100, Color.LTGRAY); - addIndicator(canvas, (float) bgDataList.iterator().next().low, getLowColor()); - addIndicator(canvas, (float) bgDataList.iterator().next().high, getHighColor()); - - - if (sharedPrefs.getBoolean("softRingHistory", true)) { - for (BgWatchData data : bgDataList) { - addReadingSoft(canvas, data); - } - } else { - for (BgWatchData data : bgDataList) { - addReading(canvas, data); - } - } - } - } - } - - public int holdInMemory() { - return 6; - } - - //getters & setters - - private synchronized int getSgvLevel() { - return sgvLevel; - } - - private synchronized void setSgvLevel(int sgvLevel) { - this.sgvLevel = sgvLevel; - } - - private synchronized int getBatteryLevel() { - return batteryLevel; - } - - private synchronized void setBatteryLevel(int batteryLevel) { - this.batteryLevel = batteryLevel; - } - - - private synchronized long getDatetime() { - return datetime; - } - - private synchronized void setDatetime(long datetime) { - this.datetime = datetime; - } - - private synchronized String getDirection() { - return direction; - } - - private void setDirection(String direction) { - this.direction = direction; - } - - String getSgvString() { - return sgvString; - } - - void setSgvString(String sgvString) { - this.sgvString = sgvString; - } - - String getStatusString() { - return statusString; - } - - void setStatusString(String statusString) { - this.statusString = statusString; - } - - public String getDelta() { - return delta; - } - - private void setDelta(String delta) { - this.delta = delta; - } - - private String getAvgDelta() { - return avgDelta; - } - - private void setAvgDelta(String avgDelta) { - this.avgDelta = avgDelta; - } - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { - prepareDrawTime(); - prepareLayout(); - invalidate(); - } - - private synchronized boolean isAnimated() { - return isAnimated; - } - - private synchronized void setIsAnimated(boolean isAnimated) { - this.isAnimated = isAnimated; - } - - void startAnimation() { - Log.d("CircleWatchface", "start startAnimation"); - - Thread animator = new Thread() { - - - public void run() { - setIsAnimated(true); - for (int i = 0; i <= 8 * 1000 / 40; i++) { - animationStep(); - SystemClock.sleep(40); - } - setIsAnimated(false); - prepareDrawTime(); - invalidate(); - System.gc(); - } - }; - - animator.start(); - } - - - public class MessageReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); - PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:MessageReceiver"); - wakeLock.acquire(30000); - Bundle bundle = intent.getBundleExtra("data"); - if (bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - setSgvLevel((int) dataMap.getLong("sgvLevel")); - Log.d("CircleWatchface", "sgv level : " + getSgvLevel()); - setSgvString(dataMap.getString("sgvString")); - Log.d("CircleWatchface", "sgv string : " + getSgvString()); - setDelta(dataMap.getString("delta")); - setAvgDelta(dataMap.getString("avgDelta")); - setDatetime(dataMap.getLong("timestamp")); - addToWatchSet(dataMap); - - - //start animation? - // dataMap.getDataMapArrayList("entries") == null -> not on "resend data". - if (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (getSgvString().equals("100") || getSgvString().equals("5.5") || getSgvString().equals("5,5"))) { - startAnimation(); - } - - prepareLayout(); - prepareDrawTime(); - invalidate(); - } - //status - bundle = intent.getBundleExtra("status"); - if (bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(50); - setStatusString(dataMap.getString("externalStatusString")); - - prepareLayout(); - prepareDrawTime(); - invalidate(); - } - wakeLock.release(); - } - } - - public synchronized void addToWatchSet(DataMap dataMap) { - - if (!sharedPrefs.getBoolean("showRingHistory", false)) { - bgDataList.clear(); - return; - } - - Log.d("CircleWatchface", "start addToWatchSet"); - ArrayList entries = dataMap.getDataMapArrayList("entries"); - if (entries == null) { - double sgv = dataMap.getDouble("sgvDouble"); - double high = dataMap.getDouble("high"); - double low = dataMap.getDouble("low"); - long timestamp = dataMap.getLong("timestamp"); - int color = dataMap.getInt("color", 0); - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } else if (!sharedPrefs.getBoolean("animation", false)) { - // don't load history at once if animations are set (less resource consumption) - Log.d("addToWatchSet", "entries.size(): " + entries.size()); - - for (DataMap entry : entries) { - double sgv = entry.getDouble("sgvDouble"); - double high = entry.getDouble("high"); - double low = entry.getDouble("low"); - long timestamp = entry.getLong("timestamp"); - int color = entry.getInt("color", 0); - bgDataList.add(new BgWatchData(sgv, high, low, timestamp, color)); - } - } else - - Log.d("addToWatchSet", "start removing bgDataList.size(): " + bgDataList.size()); - HashSet removeSet = new HashSet<>(); - double threshold = (System.currentTimeMillis() - (1000 * 60 * 5 * holdInMemory())); - for (BgWatchData data : bgDataList) { - if (data.timestamp < threshold) { - removeSet.add(data); - - } - } - bgDataList.removeAll(removeSet); - Log.d("addToWatchSet", "after bgDataList.size(): " + bgDataList.size()); - removeSet = null; - System.gc(); - } - - public int darken(int color, double fraction) { - int red = Color.red(color); - int green = Color.green(color); - int blue = Color.blue(color); - red = darkenColor(red, fraction); - green = darkenColor(green, fraction); - blue = darkenColor(blue, fraction); - int alpha = Color.alpha(color); - - return Color.argb(alpha, red, green, blue); - } - - private int darkenColor(int color, double fraction) { - - //if (sharedPrefs.getBoolean("dark", false)) { - return (int) Math.max(color - (color * fraction), 0); - //} - // return (int)Math.min(color + (color * fraction), 255); - } - - - public void addArch(Canvas canvas, float offset, int color, float size) { - Paint paint = new Paint(); - paint.setColor(color); - RectF rectTemp = new RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, (displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2), (displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2)); - canvas.drawArc(rectTemp, 270, size, true, paint); - } - - public void addArch(Canvas canvas, float start, float offset, int color, float size) { - Paint paint = new Paint(); - paint.setColor(color); - RectF rectTemp = new RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, (displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2), (displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2)); - canvas.drawArc(rectTemp, start + 270, size, true, paint); - } - - public void addIndicator(Canvas canvas, float bg, int color) { - float convertedBg; - convertedBg = bgToAngle(bg); - convertedBg += 270; - Paint paint = new Paint(); - paint.setColor(color); - float offset = 9; - RectF rectTemp = new RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, (displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2), (displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2)); - canvas.drawArc(rectTemp, convertedBg, 2, true, paint); - } - - private float bgToAngle(float bg) { - if (bg > 100) { - return (((bg - 100f) / 300f) * 225f) + 135; - } else { - return ((bg / 100) * 135); - } - } - - - public void addReadingSoft(Canvas canvas, BgWatchData entry) { - - Log.d("CircleWatchface", "addReadingSoft"); - double size; - int color = Color.LTGRAY; - if (sharedPrefs.getBoolean("dark", true)) { - color = Color.DKGRAY; - } - - float offsetMultiplier = (((displaySize.x / 2f) - PADDING) / 12f); - float offset = (float) Math.max(1, Math.ceil((System.currentTimeMillis() - entry.timestamp) / (1000 * 60 * 5.0))); - size = bgToAngle((float) entry.sgv); - addArch(canvas, offset * offsetMultiplier + 10, color, (float) size); - addArch(canvas, (float) size, offset * offsetMultiplier + 10, getBackgroundColor(), (float) (360 - size)); - addArch(canvas, (offset + .8f) * offsetMultiplier + 10, getBackgroundColor(), 360); - } - - public void addReading(Canvas canvas, BgWatchData entry) { - Log.d("CircleWatchface", "addReading"); - - double size; - int color = Color.LTGRAY; - int indicatorColor = Color.DKGRAY; - if (sharedPrefs.getBoolean("dark", true)) { - color = Color.DKGRAY; - indicatorColor = Color.LTGRAY; - } - int barColor = Color.GRAY; - if (entry.sgv >= entry.high) { - indicatorColor = getHighColor(); - barColor = darken(getHighColor(), .5); - } else if (entry.sgv <= entry.low) { - indicatorColor = getLowColor(); - barColor = darken(getLowColor(), .5); - } - float offsetMultiplier = (((displaySize.x / 2f) - PADDING) / 12f); - float offset = (float) Math.max(1, Math.ceil((System.currentTimeMillis() - entry.timestamp) / (1000 * 60 * 5.0))); - size = bgToAngle((float) entry.sgv); - addArch(canvas, offset * offsetMultiplier + 11, barColor, (float) size - 2); // Dark Color Bar - addArch(canvas, (float) size - 2, offset * offsetMultiplier + 11, indicatorColor, 2f); // Indicator at end of bar - addArch(canvas, (float) size, offset * offsetMultiplier + 11, color, (float) (360f - size)); // Dark fill - addArch(canvas, (offset + .8f) * offsetMultiplier + 11, getBackgroundColor(), 360); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv != null ? (mSgv.getRight() - mSgv.getLeft()) / 2 : 0; - - if (tapType == TAP_TYPE_TAP && - x + extra >= mSgv.getLeft() && - x - extra <= mSgv.getRight() && - y >= mSgv.getTop() && - y <= mSgv.getBottom()) { - if (eventTime - sgvTapTime < 800) { - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - -} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt new file mode 100644 index 0000000000..20e9f511ce --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CircleWatchface.kt @@ -0,0 +1,444 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.content.Intent +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.Paint +import android.graphics.Point +import android.graphics.RectF +import android.os.PowerManager +import android.support.wearable.watchface.WatchFaceStyle +import android.util.TypedValue +import android.view.LayoutInflater +import android.view.View +import android.view.WindowManager +import android.widget.TextView +import com.ustwo.clockwise.common.WatchFaceTime +import com.ustwo.clockwise.wearable.WatchFace +import dagger.android.AndroidInjection +import info.nightscout.androidaps.R +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.events.EventWearToMobile +import info.nightscout.androidaps.interaction.menus.MainMenuActivity +import info.nightscout.androidaps.interaction.utils.Persistence +import info.nightscout.androidaps.plugins.bus.RxBus +import info.nightscout.androidaps.utils.rx.AapsSchedulers +import info.nightscout.shared.logging.AAPSLogger +import info.nightscout.shared.logging.LTag +import info.nightscout.shared.sharedPreferences.SP +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.ActionResendData +import info.nightscout.shared.weardata.EventData.SingleBg +import io.reactivex.rxjava3.disposables.CompositeDisposable +import io.reactivex.rxjava3.kotlin.plusAssign +import java.util.* +import javax.inject.Inject +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.max + +class CircleWatchface : WatchFace() { + + @Inject lateinit var rxBus: RxBus + + @Inject lateinit var aapsSchedulers: AapsSchedulers + @Inject lateinit var aapsLogger: AAPSLogger + @Inject lateinit var sp: SP + @Inject lateinit var persistence: Persistence + + private var disposable = CompositeDisposable() + + private val rawData = RawDisplayData() + + private val singleBg get() = rawData.singleBg + private val status get() = rawData.status + private val graphData get() = rawData.graphData + + companion object { + + const val PADDING = 20f + const val CIRCLE_WIDTH = 10f + const val BIG_HAND_WIDTH = 16 + const val SMALL_HAND_WIDTH = 8 + const val NEAR = 2 //how near do the hands have endTime be endTime activate overlapping mode + const val ALWAYS_HIGHLIGHT_SMALL = false + const val fraction = .5 + } + + //variables for time + private var angleBig = 0f + private var angleSMALL = 0f + private var color = 0 + private val circlePaint = Paint() + private val removePaint = Paint() + private lateinit var rect: RectF + private lateinit var rectDelete: RectF + private var overlapping = false + private var displaySize = Point() + private var bgDataList = ArrayList() + private var specW = 0 + private var specH = 0 + private var myLayout: View? = null + private var mSgv: TextView? = null + private var sgvTapTime: Long = 0 + + @SuppressLint("InflateParams") + override fun onCreate() { + AndroidInjection.inject(this) + super.onCreate() + val powerManager = getSystemService(POWER_SERVICE) as PowerManager + val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:CircleWatchface") + wakeLock.acquire(30000) + val display = (getSystemService(WINDOW_SERVICE) as WindowManager).defaultDisplay + display.getSize(displaySize) + specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, View.MeasureSpec.EXACTLY) + specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, View.MeasureSpec.EXACTLY) + + //register Message Receiver + val inflater = getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater + myLayout = inflater.inflate(R.layout.activity_circle, null) + prepareLayout() + prepareDrawTime() + disposable += rxBus + .toObservable(EventData.Status::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + // this event is received as last batch of data + aapsLogger.debug(LTag.WEAR, "Status received") + rawData.updateFromPersistence(persistence) + addToWatchSet() + prepareLayout() + prepareDrawTime() + invalidate() + } + disposable += rxBus + .toObservable(EventData.Preferences::class.java) + .observeOn(aapsSchedulers.main) + .subscribe { + prepareDrawTime() + prepareLayout() + invalidate() + } + rawData.updateFromPersistence(persistence) + rxBus.send(EventWearToMobile(ActionResendData("CircleWatchFace::onCreate"))) + wakeLock.release() + } + + override fun onDestroy() { + disposable.clear() + super.onDestroy() + } + + @Synchronized override fun onDraw(canvas: Canvas) { + aapsLogger.debug(LTag.WEAR, "start onDraw") + canvas.drawColor(backgroundColor) + drawTime(canvas) + drawOtherStuff(canvas) + myLayout?.draw(canvas) + } + + @Synchronized private fun prepareLayout() { + aapsLogger.debug(LTag.WEAR, "start startPrepareLayout") + + // prepare fields + mSgv = myLayout?.findViewById(R.id.sgvString) + if (sp.getBoolean(R.string.key_show_bg, true)) { + mSgv?.visibility = View.VISIBLE + mSgv?.text = singleBg.sgvString + mSgv?.setTextColor(textColor) + } else { + //Also possible: View.INVISIBLE instead of View.GONE (no layout change) + mSgv?.visibility = View.INVISIBLE + } + var textView = myLayout?.findViewById(R.id.statusString) + if (sp.getBoolean(R.string.key_show_external_status, true)) { + textView?.visibility = View.VISIBLE + textView?.text = status.externalStatus + textView?.setTextColor(textColor) + } else { + //Also possible: View.INVISIBLE instead of View.GONE (no layout change) + textView?.visibility = View.GONE + } + textView = myLayout?.findViewById(R.id.agoString) + if (sp.getBoolean(R.string.key_show_ago, true)) { + textView?.visibility = View.VISIBLE + if (sp.getBoolean(R.string.key_show_big_numbers, false)) { + textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 26f) + } else { + (myLayout?.findViewById(R.id.agoString) as TextView).setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f) + } + textView?.text = minutes + textView?.setTextColor(textColor) + } else { + //Also possible: View.INVISIBLE instead of View.GONE (no layout change) + textView?.visibility = View.INVISIBLE + } + textView = myLayout?.findViewById(R.id.deltaString) + if (sp.getBoolean(R.string.key_show_delta, true)) { + textView?.visibility = View.VISIBLE + textView?.text = singleBg.delta + textView?.setTextColor(textColor) + if (sp.getBoolean(R.string.key_show_big_numbers, false)) { + textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25f) + } else { + textView?.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f) + } + if (sp.getBoolean(R.string.key_show_avg_delta, true)) { + textView?.append(" " + singleBg.avgDelta) + } + } else { + //Also possible: View.INVISIBLE instead of View.GONE (no layout change) + textView?.visibility = View.INVISIBLE + } + myLayout?.measure(specW, specH) + myLayout?.layout(0, 0, myLayout?.measuredWidth ?: 0, myLayout?.measuredHeight ?: 0) + } + + val minutes: String + get() { + var minutes = "--'" + if (singleBg.timeStamp != 0L) { + minutes = floor((System.currentTimeMillis() - singleBg.timeStamp) / 60000.0).toInt().toString() + "'" + } + return minutes + } + + private fun drawTime(canvas: Canvas) { + + //draw circle + circlePaint.color = color + circlePaint.strokeWidth = CIRCLE_WIDTH + canvas.drawArc(rect, 0f, 360f, false, circlePaint) + //"remove" hands from circle + removePaint.strokeWidth = CIRCLE_WIDTH * 3 + canvas.drawArc(rectDelete, angleBig, BIG_HAND_WIDTH.toFloat(), false, removePaint) + canvas.drawArc(rectDelete, angleSMALL, SMALL_HAND_WIDTH.toFloat(), false, removePaint) + if (overlapping) { + //add small hand with extra + circlePaint.strokeWidth = CIRCLE_WIDTH * 2 + circlePaint.color = color + canvas.drawArc(rect, angleSMALL, SMALL_HAND_WIDTH.toFloat(), false, circlePaint) + + //remove inner part of hands + removePaint.strokeWidth = CIRCLE_WIDTH + canvas.drawArc(rect, angleBig, BIG_HAND_WIDTH.toFloat(), false, removePaint) + canvas.drawArc(rect, angleSMALL, SMALL_HAND_WIDTH.toFloat(), false, removePaint) + } + } + + @Synchronized private fun prepareDrawTime() { + aapsLogger.debug(LTag.WEAR, "start prepareDrawTime") + val hour = Calendar.getInstance()[Calendar.HOUR_OF_DAY] % 12 + val minute = Calendar.getInstance()[Calendar.MINUTE] + angleBig = ((hour + minute / 60f) / 12f * 360 - 90 - BIG_HAND_WIDTH / 2f + 360) % 360 + angleSMALL = (minute / 60f * 360 - 90 - SMALL_HAND_WIDTH / 2f + 360) % 360 + color = 0 + when (singleBg.sgvLevel.toInt()) { + -1 -> color = lowColor + 0 -> color = inRangeColor + 1 -> color = highColor + } + circlePaint.shader = null + circlePaint.style = Paint.Style.STROKE + circlePaint.strokeWidth = CIRCLE_WIDTH + circlePaint.isAntiAlias = true + circlePaint.color = color + removePaint.style = Paint.Style.STROKE + removePaint.strokeWidth = CIRCLE_WIDTH + removePaint.isAntiAlias = true + removePaint.color = backgroundColor + rect = RectF(PADDING, PADDING, displaySize.x - PADDING, displaySize.y - PADDING) + rectDelete = RectF(PADDING - CIRCLE_WIDTH / 2, PADDING - CIRCLE_WIDTH / 2, displaySize.x - PADDING + CIRCLE_WIDTH / 2, displaySize.y - PADDING + CIRCLE_WIDTH / 2) + overlapping = ALWAYS_HIGHLIGHT_SMALL || areOverlapping(angleSMALL, angleSMALL + SMALL_HAND_WIDTH + NEAR, angleBig, angleBig + BIG_HAND_WIDTH + NEAR) + aapsLogger.debug(LTag.WEAR, "end prepareDrawTime") + } + + private fun areOverlapping(aBegin: Float, aEnd: Float, bBegin: Float, bEnd: Float): Boolean { + return bBegin in aBegin..aEnd || aBegin <= bBegin && bEnd > 360 && bEnd % 360 > aBegin || aBegin in bBegin..bEnd || bBegin <= aBegin && aEnd > 360 && aEnd % 360 > bBegin + } + + override fun onTimeChanged(oldTime: WatchFaceTime, newTime: WatchFaceTime) { + if (oldTime.hasMinuteChanged(newTime)) { + val powerManager = getSystemService(POWER_SERVICE) as PowerManager + val wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:CircleWatchface_onTimeChanged") + wakeLock.acquire(30000) + /*Preparing the layout just on every minute tick: + * - hopefully better battery life + * - drawback: might update the minutes since last reading up endTime one minute late*/prepareLayout() + prepareDrawTime() + invalidate() //redraw the time + wakeLock.release() + } + } + + // defining color for dark and bright + private val lowColor: Int + get() = if (sp.getBoolean("dark", true)) { + Color.argb(255, 255, 120, 120) + } else { + Color.argb(255, 255, 80, 80) + } + private val inRangeColor: Int + get() = if (sp.getBoolean("dark", true)) { + Color.argb(255, 120, 255, 120) + } else { + Color.argb(255, 0, 240, 0) + } + private val highColor: Int + get() = if (sp.getBoolean("dark", true)) { + Color.argb(255, 255, 255, 120) + } else { + Color.argb(255, 255, 200, 0) + } + private val backgroundColor: Int + get() = if (sp.getBoolean("dark", true)) { + Color.BLACK + } else { + Color.WHITE + } + val textColor: Int + get() = if (sp.getBoolean("dark", true)) { + Color.WHITE + } else { + Color.BLACK + } + + private fun drawOtherStuff(canvas: Canvas) { + aapsLogger.debug(LTag.WEAR, "start onDrawOtherStuff. bgDataList.size(): " + bgDataList.size) + if (sp.getBoolean(R.string.key_show_ring_history, false)) { + //Perfect low and High indicators + if (bgDataList.size > 0) { + addIndicator(canvas, 100f, Color.LTGRAY) + addIndicator(canvas, bgDataList.iterator().next().low.toFloat(), lowColor) + addIndicator(canvas, bgDataList.iterator().next().high.toFloat(), highColor) + if (sp.getBoolean("softRingHistory", true)) { + for (data in bgDataList) { + addReadingSoft(canvas, data) + } + } else { + for (data in bgDataList) { + addReading(canvas, data) + } + } + } + } + } + + @Synchronized fun addToWatchSet() { + bgDataList.clear() + if (!sp.getBoolean(R.string.key_show_ring_history, false)) return + val threshold = (System.currentTimeMillis() - 1000L * 60 * 30).toDouble() // 30 min + for (entry in graphData.entries) if (entry.timeStamp >= threshold) bgDataList.add(entry) + aapsLogger.debug(LTag.WEAR, "addToWatchSet size=" + bgDataList.size) + } + + private fun darken(color: Int): Int { + var red = Color.red(color) + var green = Color.green(color) + var blue = Color.blue(color) + red = darkenColor(red) + green = darkenColor(green) + blue = darkenColor(blue) + val alpha = Color.alpha(color) + return Color.argb(alpha, red, green, blue) + } + + private fun darkenColor(color: Int): Int { + return max(color - color * fraction, 0.0).toInt() + } + + private fun addArch(canvas: Canvas, offset: Float, color: Int, size: Float) { + val paint = Paint() + paint.color = color + val rectTemp = + RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2, displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2) + canvas.drawArc(rectTemp, 270f, size, true, paint) + } + + private fun addArch(canvas: Canvas, start: Float, offset: Float, color: Int, size: Float) { + val paint = Paint() + paint.color = color + val rectTemp = + RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2, displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2) + canvas.drawArc(rectTemp, start + 270, size, true, paint) + } + + private fun addIndicator(canvas: Canvas, bg: Float, color: Int) { + var convertedBg: Float = bgToAngle(bg) + convertedBg += 270f + val paint = Paint() + paint.color = color + val offset = 9f + val rectTemp = + RectF(PADDING + offset - CIRCLE_WIDTH / 2, PADDING + offset - CIRCLE_WIDTH / 2, displaySize.x - PADDING - offset + CIRCLE_WIDTH / 2, displaySize.y - PADDING - offset + CIRCLE_WIDTH / 2) + canvas.drawArc(rectTemp, convertedBg, 2f, true, paint) + } + + private fun bgToAngle(bg: Float): Float { + return if (bg > 100) { + (bg - 100f) / 300f * 225f + 135 + } else { + bg / 100 * 135 + } + } + + private fun addReadingSoft(canvas: Canvas, entry: SingleBg) { + aapsLogger.debug(LTag.WEAR, "addReadingSoft") + var color = Color.LTGRAY + if (sp.getBoolean("dark", true)) { + color = Color.DKGRAY + } + val offsetMultiplier = (displaySize.x / 2f - PADDING) / 12f + val offset = max(1.0, ceil((System.currentTimeMillis() - entry.timeStamp) / (1000 * 60 * 5.0))).toFloat() + val size: Double = bgToAngle(entry.sgv.toFloat()).toDouble() + addArch(canvas, offset * offsetMultiplier + 10, color, size.toFloat()) + addArch(canvas, size.toFloat(), offset * offsetMultiplier + 10, backgroundColor, (360 - size).toFloat()) + addArch(canvas, (offset + .8f) * offsetMultiplier + 10, backgroundColor, 360f) + } + + private fun addReading(canvas: Canvas, entry: SingleBg) { + aapsLogger.debug(LTag.WEAR, "addReading") + var color = Color.LTGRAY + var indicatorColor = Color.DKGRAY + if (sp.getBoolean("dark", true)) { + color = Color.DKGRAY + indicatorColor = Color.LTGRAY + } + var barColor = Color.GRAY + if (entry.sgv >= entry.high) { + indicatorColor = highColor + barColor = darken(highColor) + } else if (entry.sgv <= entry.low) { + indicatorColor = lowColor + barColor = darken(lowColor) + } + val offsetMultiplier = (displaySize.x / 2f - PADDING) / 12f + val offset = max(1.0, ceil((System.currentTimeMillis() - entry.timeStamp) / (1000 * 60 * 5.0))).toFloat() + val size: Double = bgToAngle(entry.sgv.toFloat()).toDouble() + addArch(canvas, offset * offsetMultiplier + 11, barColor, size.toFloat() - 2) // Dark Color Bar + addArch(canvas, size.toFloat() - 2, offset * offsetMultiplier + 11, indicatorColor, 2f) // Indicator at end of bar + addArch(canvas, size.toFloat(), offset * offsetMultiplier + 11, color, (360f - size).toFloat()) // Dark fill + addArch(canvas, (offset + .8f) * offsetMultiplier + 11, backgroundColor, 360f) + } + + override fun onTapCommand(tapType: Int, x: Int, y: Int, eventTime: Long) { + mSgv?.let { mSgv -> + val extra = (mSgv.right - mSgv.left) / 2 + if (tapType == TAP_TYPE_TAP && x + extra >= mSgv.left && x - extra <= mSgv.right && y >= mSgv.top && y <= mSgv.bottom) { + if (eventTime - sgvTapTime < 800) { + val intent = Intent(this, MainMenuActivity::class.java) + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + startActivity(intent) + } + sgvTapTime = eventTime + } + } + } + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build() + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java deleted file mode 100644 index 3a68158109..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Cockpit.java +++ /dev/null @@ -1,120 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import android.support.wearable.watchface.WatchFaceStyle; -import android.view.LayoutInflater; -import android.view.View; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -/** - * Created by andrew-warrington on 18/11/2017. - */ - -public class Cockpit extends BaseWatchFace { - - private long sgvTapTime = 0; - - @Override - public void onCreate() { - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_cockpit, null); - performViewSetup(); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - if (tapType == TAP_TYPE_TAP ) { - if (eventTime - sgvTapTime < 800) { - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - protected void setColorDark() { - - mRelativeLayout.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds); - setTextSizes(); - - if (mHighLight != null && mLowLight != null) { - if (rawData.sgvLevel == 1) { - mHighLight.setBackgroundResource(R.drawable.airplane_led_yellow_lit); - mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (rawData.sgvLevel == 0) { - mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - mLowLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - } else if (rawData.sgvLevel == -1) { - mHighLight.setBackgroundResource(R.drawable.airplane_led_grey_unlit); - mLowLight.setBackgroundResource(R.drawable.airplane_led_red_lit); - } - } - - if (loopLevel == -1) { - mLoop.setBackgroundResource(R.drawable.loop_grey_25); - } else if (loopLevel == 1) { - mLoop.setBackgroundResource(R.drawable.loop_green_25); - } else { - mLoop.setBackgroundResource(R.drawable.loop_red_25); - } - - invalidate(); - - } - - protected void setColorLowRes() { - mRelativeLayout.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds_lowres); - - } - - protected void setColorBright() { - setColorDark(); - } - - protected void setTextSizes() { - - if (mIOB2 != null) { - if (rawData.detailedIOB) { - if (bIsRound) { - mIOB2.setTextSize(10); - } else { - mIOB2.setTextSize(9); - } - } else { - if (bIsRound) { - mIOB2.setTextSize(13); - } else { - mIOB2.setTextSize(12); - } - } - } - - if ((mUploaderBattery.getVisibility() != View.GONE) && (mRigBattery.getVisibility() != View.GONE)) { - if (bIsRound) { - mUploaderBattery.setTextSize(12); - mRigBattery.setTextSize(12); - } else { - mUploaderBattery.setTextSize(10); - mRigBattery.setTextSize(10); - } - } else { - if (bIsRound) { - mUploaderBattery.setTextSize(13); - mRigBattery.setTextSize(13); - } else { - mUploaderBattery.setTextSize(12); - mRigBattery.setTextSize(12); - } - } - } -} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt new file mode 100644 index 0000000000..cb15fbc7f9 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/CockpitWatchface.kt @@ -0,0 +1,76 @@ +package info.nightscout.androidaps.watchfaces + +import android.view.View +import androidx.annotation.LayoutRes +import info.nightscout.androidaps.R + +/** + * Created by andrew-warrington on 18/11/2017. + * Refactored by MilosKozak 24/04/2022 + */ +class CockpitWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_cockpit + + override fun setColorDark() { + mRelativeLayout?.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds) + setTextSizes() + when (singleBg.sgvLevel) { + 1L -> { + mHighLight?.setBackgroundResource(R.drawable.airplane_led_yellow_lit) + mLowLight?.setBackgroundResource(R.drawable.airplane_led_grey_unlit) + } + + 0L -> { + mHighLight?.setBackgroundResource(R.drawable.airplane_led_grey_unlit) + mLowLight?.setBackgroundResource(R.drawable.airplane_led_grey_unlit) + } + + -1L -> { + mHighLight?.setBackgroundResource(R.drawable.airplane_led_grey_unlit) + mLowLight?.setBackgroundResource(R.drawable.airplane_led_red_lit) + } + } + when (loopLevel) { + -1 -> mLoop?.setBackgroundResource(R.drawable.loop_grey_25) + 1 -> mLoop?.setBackgroundResource(R.drawable.loop_green_25) + else -> mLoop?.setBackgroundResource(R.drawable.loop_red_25) + } + invalidate() + } + + override fun setColorLowRes() { + mRelativeLayout?.setBackgroundResource(R.drawable.airplane_cockpit_outside_clouds_lowres) + } + + override fun setColorBright() { + setColorDark() + } + + private fun setTextSizes() { + if (status.detailedIob) { + if (bIsRound) mIOB2?.textSize = 10f + else mIOB2?.textSize = 9f + } else { + if (bIsRound) mIOB2?.textSize = 13f + else mIOB2?.textSize = 12f + } + if (mUploaderBattery?.visibility != View.GONE && mRigBattery?.visibility != View.GONE) { + if (bIsRound) { + mUploaderBattery?.textSize = 12f + mRigBattery?.textSize = 12f + } else { + mUploaderBattery?.textSize = 10f + mRigBattery?.textSize = 10f + } + } else { + if (bIsRound) { + mUploaderBattery?.textSize = 13f + mRigBattery?.textSize = 13f + } else { + mUploaderBattery?.textSize = 12f + mRigBattery?.textSize = 12f + } + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java deleted file mode 100644 index 2b3975e949..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyle.java +++ /dev/null @@ -1,171 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import android.content.res.ColorStateList; -import android.support.wearable.watchface.WatchFaceStyle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.widget.LinearLayout; -import android.widget.TextView; - -import androidx.core.content.ContextCompat; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -public class DigitalStyle extends BaseWatchFace { - private static final long TIME_TAP_THRESHOLD = 800; - private final long chartTapTime = 0; - private long sgvTapTime = 0; - - @Override - public void onCreate() { - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_digitalstyle, null); - performViewSetup(); - } - - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - //tapType = TAP_TYPE_TAP; - Log.d("onTapCommand: DeviceWidth x DeviceHeight /// x , y, TapType >> ", getWidth() + " x " + getHeight() + " /// " + x + " , " + y + " , " + tapType); - - if (tapType == TAP_TYPE_TAP) { - if (eventTime - sgvTapTime < TIME_TAP_THRESHOLD) { - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this) - .setAcceptsTapEvents(true) - .setHideNotificationIndicator(false) - .setShowUnreadCountIndicator(true) - .build(); - } - - protected void setColorDark() { - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); - } - - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - pointSize = 1; - setupCharts(); - setWatchfaceStyle(); - } - } - - private void setWatchfaceStyle(){ - /* frame styles*/ - LinearLayout mShapesElements = layoutView.findViewById(R.id.shapes_elements); - if (mShapesElements != null) { - String displayFormatType = (mShapesElements.getContentDescription().toString().startsWith("round") ? "round" : "rect"); - String displayStyle=sharedPrefs.getString("digitalstyle_frameStyle", "full"); - String displayFrameColor=sharedPrefs.getString("digitalstyle_frameColor", "red"); - String displayFrameColorSaturation=sharedPrefs.getString("digitalstyle_frameColorSaturation", "500"); - String displayFrameColorOpacity=sharedPrefs.getString("digitalstyle_frameColorOpacity", "1"); - - // Load image with shapes - String styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType; - try { - mShapesElements.setBackground(getResources().getDrawable(getResources().getIdentifier(styleDrawableName, "drawable", getApplicationContext().getPackageName()))); - } catch (Exception e) { - Log.e("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> " + styleDrawableName); - } - - // set background-tint-color - if (displayFrameColor.equalsIgnoreCase("multicolor") || displayStyle.equalsIgnoreCase("none")) { - mShapesElements.setBackgroundTintList(null); - } else { - String strColorName =(( displayFrameColor.equals("white") || displayFrameColor.equals("black") )?displayFrameColor:displayFrameColor+"_"+displayFrameColorSaturation); - Log.v("digitalstyle_strColorName",strColorName); - try { - ColorStateList colorStateList = ContextCompat.getColorStateList(getApplicationContext(), getResources().getIdentifier(strColorName, "color", getApplicationContext().getPackageName())); - mShapesElements.setBackgroundTintList(colorStateList); - } catch (Exception e) { - mShapesElements.setBackgroundTintList(null); - Log.e("digitalstyle_colorName", "COLOR NOT FOUND >> " + strColorName); - } - } - - // set opacity of shapes - mShapesElements.setAlpha(Float.parseFloat(displayFrameColorOpacity)); - - } - - /* optimize font-size --> when date is off then increase font-size of time */ - Boolean isShowDate = sharedPrefs.getBoolean("show_date", false); - if (!isShowDate) { - layoutView.findViewById(R.id.date_time).setVisibility(View.GONE); - mHour.setTextSize(62); - mMinute.setTextSize(40); - mHour.setLetterSpacing((float) -0.066); - mMinute.setLetterSpacing((float) -0.066); - } else { - layoutView.findViewById(R.id.date_time).setVisibility(View.VISIBLE); - mHour.setTextSize(40); - mMinute.setTextSize(26); - mHour.setLetterSpacing((float) 0); - mMinute.setLetterSpacing((float) 0); - - /* display week number */ - Boolean isShowWeekNumber = sharedPrefs.getBoolean("show_weeknumber", false); - Log.i("---------------------------------","weeknumber refresh "); - TextView mWeekNumber= layoutView.findViewById(R.id.weeknumber); - if (isShowWeekNumber) { - mWeekNumber.setVisibility(View.VISIBLE); - mWeekNumber.setText("(" + (new SimpleDateFormat("ww")).format(new Date()) + ")"); - } else { - mWeekNumber.setVisibility(View.GONE); - mWeekNumber.setText(""); - } - } - - - } - - protected void setColorLowRes() { - setColorDark(); - } - protected void setColorBright() { setColorDark(); /* getCurrentWatchMode() == WatchMode.AMBIENT or WatchMode.INTERACTIVE */} - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt new file mode 100644 index 0000000000..e8d7ba0cf8 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/DigitalStyleWatchface.kt @@ -0,0 +1,134 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.annotation.SuppressLint +import android.support.wearable.watchface.WatchFaceStyle +import android.view.View +import android.widget.LinearLayout +import android.widget.TextView +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import info.nightscout.androidaps.R +import info.nightscout.androidaps.extensions.toVisibility +import info.nightscout.shared.logging.LTag + +class DigitalStyleWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_digitalstyle + + override fun getWatchFaceStyle(): WatchFaceStyle { + return WatchFaceStyle.Builder(this) + .setAcceptsTapEvents(true) + .setHideNotificationIndicator(false) + .setShowUnreadCountIndicator(true) + .build() + } + + override fun setColorDark() { + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDirection?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + else mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + + if (status.batteryLevel == 1) mUploaderBattery?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + else mUploaderBattery?.setTextColor(ContextCompat.getColor(this, R.color.dark_uploaderBatteryEmpty)) + + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.dark_highColor) + lowColor = ContextCompat.getColor(this, R.color.dark_lowColor) + midColor = ContextCompat.getColor(this, R.color.dark_midColor) + gridColor = ContextCompat.getColor(this, R.color.dark_gridColor) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_light) + pointSize = 1 + setupCharts() + setWatchfaceStyle() + } + } + + @SuppressLint("SetTextI18n") + private fun setWatchfaceStyle() { + /* frame styles*/ + val mShapesElements = layoutView?.findViewById(R.id.shapes_elements) + if (mShapesElements != null) { + val displayFormatType = if (mShapesElements.contentDescription.toString().startsWith("round")) "round" else "rect" + val displayStyle = sp.getString("digitalstyle_frameStyle", "full") + val displayFrameColor = sp.getString("digitalstyle_frameColor", "red") + val displayFrameColorSaturation = sp.getString( + "digitalstyle_frameColorSaturation", + "500" + ) + val displayFrameColorOpacity = sp.getString("digitalstyle_frameColorOpacity", "1") + + // Load image with shapes + val styleDrawableName = "digitalstyle_bg_" + displayStyle + "_" + displayFormatType + try { + mShapesElements.background = ContextCompat.getDrawable(this, resources.getIdentifier(styleDrawableName, "drawable", this.packageName)) + } catch (e: Exception) { + aapsLogger.error("digitalstyle_frameStyle", "RESOURCE NOT FOUND >> $styleDrawableName") + } + + // set background-tint-color + if (displayFrameColor.equals("multicolor", ignoreCase = true) || displayStyle.equals("none", ignoreCase = true)) { + mShapesElements.backgroundTintList = null + } else { + val strColorName = if (displayFrameColor == "white" || displayFrameColor == "black") displayFrameColor else displayFrameColor + "_" + displayFrameColorSaturation + aapsLogger.debug(LTag.WEAR, "digitalstyle_strColorName", strColorName) + try { + val colorStateList = ContextCompat.getColorStateList(this, resources.getIdentifier(strColorName, "color", this.packageName)) + mShapesElements.backgroundTintList = colorStateList + } catch (e: Exception) { + mShapesElements.backgroundTintList = null + aapsLogger.error("digitalstyle_colorName", "COLOR NOT FOUND >> $strColorName") + } + } + + // set opacity of shapes + mShapesElements.alpha = displayFrameColorOpacity.toFloat() + } + + /* optimize font-size --> when date is off then increase font-size of time */ + val isShowDate = sp.getBoolean(R.string.key_show_date, false) + if (!isShowDate) { + layoutView?.findViewById(R.id.date_time)?.visibility = View.GONE + mHour?.textSize = 62f + mMinute?.textSize = 40f + mHour?.letterSpacing = (-0.066).toFloat() + mMinute?.letterSpacing = (-0.066).toFloat() + } else { + layoutView?.findViewById(R.id.date_time)?.visibility = View.VISIBLE + mHour?.textSize = 40f + mMinute?.textSize = 26f + mHour?.letterSpacing = 0.toFloat() + mMinute?.letterSpacing = 0.toFloat() + + /* display week number */ + val mWeekNumber = layoutView?.findViewById(R.id.weeknumber) + mWeekNumber?.visibility = sp.getBoolean(R.string.key_show_week_number, false).toVisibility() + mWeekNumber?.text = "(" + dateUtil.weekString() + ")" + } + } + + override fun setColorLowRes() { + setColorDark() + } + + override fun setColorBright() { + setColorDark() /* getCurrentWatchMode() == WatchMode.AMBIENT or WatchMode.INTERACTIVE */ + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java deleted file mode 100644 index ce84f97e46..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home.java +++ /dev/null @@ -1,183 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import android.graphics.Color; -import androidx.core.content.ContextCompat; -import android.support.wearable.watchface.WatchFaceStyle; -import android.view.LayoutInflater; - -import com.ustwo.clockwise.common.WatchMode; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -public class Home extends BaseWatchFace { - - private long chartTapTime = 0; - private long sgvTapTime = 0; - - @Override - public void onCreate() { - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_home, null); - performViewSetup(); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; - - if (tapType == TAP_TYPE_TAP&& - x >=chart.getLeft() && - x <= chart.getRight()&& - y >= chart.getTop() && - y <= chart.getBottom()){ - if (eventTime - chartTapTime < 800){ - changeChartTimeframe(); - } - chartTapTime = eventTime; - } else if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& - y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe%5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); - } - - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - - protected void setColorDark() { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_background : R.color.dark_statusView)); - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_uploaderBattery)); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); - } - - mStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_mStatus_home)); - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - pointSize = 2; - setupCharts(); - } - } - - protected void setColorLowRes() { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark_lowres); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light_lowres); - pointSize = 2; - setupCharts(); - } - - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mTimestamp.setTextColor(Color.RED); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mUploaderBattery.setTextColor(Color.RED); - } - mStatus.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - - mTime.setTextColor(Color.BLACK); - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.light_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.light_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.light_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - pointSize = 2; - setupCharts(); - } - } else { - setColorDark(); - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java deleted file mode 100644 index 9f1cb75ddd..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Home2.java +++ /dev/null @@ -1,268 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import android.graphics.Color; - -import androidx.annotation.ColorInt; -import androidx.core.content.ContextCompat; - -import android.support.wearable.watchface.WatchFaceStyle; -import android.view.LayoutInflater; - -import com.ustwo.clockwise.common.WatchMode; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -public class Home2 extends BaseWatchFace { - - private long chartTapTime = 0; - private long sgvTapTime = 0; - - @Override - public void onCreate() { - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_home_2, null); - - performViewSetup(); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv != null ? (mSgv.getRight() - mSgv.getLeft()) / 2 : 0; - - if (tapType == TAP_TYPE_TAP && - x >= chart.getLeft() && - x <= chart.getRight() && - y >= chart.getTop() && - y <= chart.getBottom()) { - if (eventTime - chartTapTime < 800) { - changeChartTimeframe(); - } - chartTapTime = eventTime; - } else if (tapType == TAP_TYPE_TAP && - x + extra >= mSgv.getLeft() && - x - extra <= mSgv.getRight() && - y >= mSgv.getTop() && - y <= mSgv.getBottom()) { - if (eventTime - sgvTapTime < 800) { - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe % 5) + 1; - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); - } - - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - protected void setColorDark() { - @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBatteryOkColor = ContextCompat.getColor(getApplicationContext(), - dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery); - @ColorInt final int dividerBgColor = ContextCompat.getColor(getApplicationContext(), - dividerMatchesBg ? R.color.dark_background : R.color.dark_statusView); - - mLinearLayout.setBackgroundColor(dividerBgColor); - mLinearLayout2.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mIOB1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mIOB2.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mCOB1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mCOB2.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDay.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mMonth.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mLoop.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - - setTextSizes(); - - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(dividerBatteryOkColor); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); - } - mRigBattery.setTextColor(dividerTxtColor); - mDelta.setTextColor(dividerTxtColor); - mAvgDelta.setTextColor(dividerTxtColor); - mBasalRate.setTextColor(dividerTxtColor); - mBgi.setTextColor(dividerTxtColor); - - if (loopLevel == -1) { - mLoop.setBackgroundResource(R.drawable.loop_grey_25); - } else if (loopLevel == 1) { - mLoop.setBackgroundResource(R.drawable.loop_green_25); - } else { - mLoop.setBackgroundResource(R.drawable.loop_red_25); - } - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - pointSize = 2; - setupCharts(); - } - } - - protected void setColorLowRes() { - @ColorInt final int dividerTxtColor = dividerMatchesBg ? - ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor) : Color.BLACK; - @ColorInt final int dividerBgColor = ContextCompat.getColor(getApplicationContext(), - dividerMatchesBg ? R.color.dark_background : R.color.dark_statusView); - - mLinearLayout.setBackgroundColor(dividerBgColor); - mLinearLayout2.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mLoop.setBackgroundResource(R.drawable.loop_grey_25); - mLoop.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - mDelta.setTextColor(dividerTxtColor); - mAvgDelta.setTextColor(dividerTxtColor); - mRigBattery.setTextColor(dividerTxtColor); - mUploaderBattery.setTextColor(dividerTxtColor); - mBasalRate.setTextColor(dividerTxtColor); - mBgi.setTextColor(dividerTxtColor); - mIOB1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mIOB2.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mCOB1.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mCOB2.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDay.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mMonth.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.dark_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark_lowres); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light_lowres); - pointSize = 2; - setupCharts(); - } - setTextSizes(); - } - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - - @ColorInt final int dividerTxtColor = dividerMatchesBg ? Color.BLACK : - ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor); - @ColorInt final int dividerBgColor = ContextCompat.getColor(getApplicationContext(), - dividerMatchesBg ? R.color.light_background : R.color.light_stripe_background); - - mLinearLayout.setBackgroundColor(dividerBgColor); - mLinearLayout2.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - mTime.setTextColor(Color.BLACK); - mIOB1.setTextColor(Color.BLACK); - mIOB2.setTextColor(Color.BLACK); - mCOB1.setTextColor(Color.BLACK); - mCOB2.setTextColor(Color.BLACK); - mDay.setTextColor(Color.BLACK); - mMonth.setTextColor(Color.BLACK); - mLoop.setTextColor(Color.BLACK); - - setTextSizes(); - - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(Color.BLACK); - } else { - mTimestamp.setTextColor(Color.RED); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(dividerTxtColor); - } else { - mUploaderBattery.setTextColor(Color.RED); - } - mRigBattery.setTextColor(dividerTxtColor); - mDelta.setTextColor(dividerTxtColor); - mAvgDelta.setTextColor(dividerTxtColor); - mBasalRate.setTextColor(dividerTxtColor); - mBgi.setTextColor(dividerTxtColor); - - if (loopLevel == -1) { - mLoop.setBackgroundResource(R.drawable.loop_grey_25); - } else if (loopLevel == 1) { - mLoop.setBackgroundResource(R.drawable.loop_green_25); - } else { - mLoop.setBackgroundResource(R.drawable.loop_red_25); - } - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.light_highColor); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.light_midColor); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.light_gridColor); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_light); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - pointSize = 2; - setupCharts(); - } - } else { - setColorDark(); - } - } - - protected void setTextSizes() { - - if (mIOB1 != null && mIOB2 != null) { - - if (rawData.detailedIOB) { - mIOB1.setTextSize(14); - mIOB2.setTextSize(10); - } else { - mIOB1.setTextSize(10); - mIOB2.setTextSize(14); - } - } - } - -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java deleted file mode 100644 index efce6baab7..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/LargeHome.java +++ /dev/null @@ -1,156 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import android.graphics.Color; -import androidx.core.content.ContextCompat; -import android.support.wearable.watchface.WatchFaceStyle; -import android.view.LayoutInflater; - -import com.ustwo.clockwise.common.WatchMode; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -public class LargeHome extends BaseWatchFace { - - private long sgvTapTime = 0; - - @Override - public void onCreate() { - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_home_large, null); - performViewSetup(); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; - - if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& - y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - @Override - protected void setColorDark(){ - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_background : R.color.dark_mLinearLayout)); - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.dark_midColor : R.color.dark_uploaderBattery)); - } else { - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_uploaderBatteryEmpty)); - } - - mStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mStatus_home)); - } - - @Override - protected void setColorBright() { - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? - R.color.light_background : R.color.light_stripe_background)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mTimestamp.setTextColor(Color.RED); - } - - if (rawData.batteryLevel == 1) { - mUploaderBattery.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - } else { - mUploaderBattery.setTextColor(Color.RED); - } - mStatus.setTextColor(dividerMatchesBg ? Color.BLACK : Color.WHITE); - mTime.setTextColor(Color.BLACK); - } else { - mRelativeLayout.setBackgroundColor(Color.BLACK); - mLinearLayout.setBackgroundColor(dividerMatchesBg ? Color.BLACK : Color.LTGRAY); - if (rawData.sgvLevel == 1) { - mSgv.setTextColor(Color.YELLOW); - mDirection.setTextColor(Color.YELLOW); - mDelta.setTextColor(Color.YELLOW); - } else if (rawData.sgvLevel == 0) { - mSgv.setTextColor(Color.WHITE); - mDirection.setTextColor(Color.WHITE); - mDelta.setTextColor(Color.WHITE); - } else if (rawData.sgvLevel == -1) { - mSgv.setTextColor(Color.RED); - mDirection.setTextColor(Color.RED); - mDelta.setTextColor(Color.RED); - } - - mUploaderBattery.setTextColor(dividerMatchesBg ? Color.WHITE : Color.BLACK); - mTimestamp.setTextColor(dividerMatchesBg ? Color.WHITE : Color.BLACK); - mStatus.setTextColor(dividerMatchesBg ? Color.WHITE : Color.BLACK); - mTime.setTextColor(Color.WHITE); - } - } - - @Override - protected void setColorLowRes() { - mLinearLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_background : R.color.dark_mLinearLayout)); - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDirection.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mTimestamp1_home)); - mUploaderBattery.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_uploaderBattery)); - mStatus.setTextColor(ContextCompat.getColor(getApplicationContext(), dividerMatchesBg ? R.color.dark_midColor : R.color.dark_mStatus_home)); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java deleted file mode 100644 index 9e56a8aa21..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NOChart.java +++ /dev/null @@ -1,524 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.LinearGradient; -import android.graphics.Matrix; -import android.graphics.Paint; -import android.graphics.Point; -import android.graphics.Rect; -import android.graphics.Shader; -import android.os.Bundle; -import android.os.PowerManager; -import android.os.SystemClock; -import android.preference.PreferenceManager; -import androidx.core.content.ContextCompat; -import androidx.localbroadcastmanager.content.LocalBroadcastManager; -import android.support.wearable.view.WatchViewStub; -import android.support.wearable.watchface.WatchFaceStyle; -import android.text.format.DateFormat; -import android.util.DisplayMetrics; -import android.util.Log; -import android.view.Display; -import android.view.LayoutInflater; -import android.view.View; -import android.view.WindowInsets; -import android.view.WindowManager; -import android.widget.RelativeLayout; -import android.widget.TextView; - -import com.google.android.gms.wearable.DataMap; -import com.ustwo.clockwise.common.WatchFaceTime; -import com.ustwo.clockwise.common.WatchMode; -import com.ustwo.clockwise.common.WatchShape; -import com.ustwo.clockwise.wearable.WatchFace; - -import java.util.ArrayList; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.data.BasalWatchData; -import info.nightscout.androidaps.data.BgWatchData; -import info.nightscout.androidaps.data.ListenerService; -import info.nightscout.androidaps.data.TempWatchData; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; - -/** - * Created by adrianLxM. - */ -public class NOChart extends WatchFace implements SharedPreferences.OnSharedPreferenceChangeListener { - public final static IntentFilter INTENT_FILTER; - public static final int SCREENSIZE_SMALL = 280; - public TextView mTime, mSgv, mTimestamp, mDelta, mAvgDelta; - public RelativeLayout mRelativeLayout; - public long sgvLevel = 0; - public int batteryLevel = 1; - public int ageLevel = 1; - public boolean lowResMode = false; - public boolean layoutSet = false; - public long datetime; - public ArrayList bgDataList = new ArrayList<>(); - public ArrayList tempWatchDataList = new ArrayList<>(); - public ArrayList basalWatchDataList = new ArrayList<>(); - public PowerManager.WakeLock wakeLock; - public View layoutView; - private final Point displaySize = new Point(); - private int specW, specH; - private int animationAngle = 0; - private boolean isAnimated = false; - - private LocalBroadcastManager localBroadcastManager; - private MessageReceiver messageReceiver; - - protected SharedPreferences sharedPrefs; - private String sgvString = "--"; - private String externalStatusString = "no status"; - private TextView statusView; - private long sgvTapTime = 0L; - - @Override - public void onCreate() { - super.onCreate(); - Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay(); - display.getSize(displaySize); - wakeLock = ((PowerManager) getSystemService(Context.POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:NOChart"); - - specW = View.MeasureSpec.makeMeasureSpec(displaySize.x, - View.MeasureSpec.EXACTLY); - specH = View.MeasureSpec.makeMeasureSpec(displaySize.y, - View.MeasureSpec.EXACTLY); - sharedPrefs = PreferenceManager - .getDefaultSharedPreferences(this); - sharedPrefs.registerOnSharedPreferenceChangeListener(this); - LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_nochart, null); - DisplayMetrics metrics = getResources().getDisplayMetrics(); - if(metrics.widthPixels < SCREENSIZE_SMALL || metrics.heightPixels < SCREENSIZE_SMALL){ - layoutView = inflater.inflate(R.layout.activity_nochart_small, null); - } else { - layoutView = inflater.inflate(R.layout.activity_nochart, null); - } - performViewSetup(); - } - - @Override - protected void onLayout(WatchShape shape, Rect screenBounds, WindowInsets screenInsets) { - super.onLayout(shape, screenBounds, screenInsets); - layoutView.onApplyWindowInsets(screenInsets); - } - - public void performViewSetup() { - final WatchViewStub stub = layoutView.findViewById(R.id.watch_view_stub); - IntentFilter messageFilter = new IntentFilter(Intent.ACTION_SEND); - - messageReceiver = new MessageReceiver(); - localBroadcastManager = LocalBroadcastManager.getInstance(this); - localBroadcastManager.registerReceiver(messageReceiver, messageFilter); - - stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() { - @Override - public void onLayoutInflated(WatchViewStub stub) { - mTime = stub.findViewById(R.id.watch_time); - mSgv = stub.findViewById(R.id.sgv); - mTimestamp = stub.findViewById(R.id.timestamp); - mDelta = stub.findViewById(R.id.delta); - mAvgDelta = stub.findViewById(R.id.avgdelta); - mRelativeLayout = stub.findViewById(R.id.main_layout); - statusView = stub.findViewById(R.id.aps_status); - layoutSet = true; - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - }); - ListenerService.requestData(this); - wakeLock.acquire(50); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - int extra = mSgv!=null?(mSgv.getRight() - mSgv.getLeft())/2:0; - - if (tapType == TAP_TYPE_TAP&& - x + extra >=mSgv.getLeft() && - x - extra <= mSgv.getRight()&& - y >= mSgv.getTop() && - y <= mSgv.getBottom()){ - if (eventTime - sgvTapTime < 800){ - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - sgvTapTime = eventTime; - } - } - - protected void onWatchModeChanged(WatchMode watchMode) { - - if(lowResMode ^ isLowRes(watchMode)){ //if there was a change in lowResMode - lowResMode = isLowRes(watchMode); - setColor(); - } else if (! sharedPrefs.getBoolean("dark", true)){ - //in bright mode: different colours if active: - setColor(); - } - } - - private boolean isLowRes(WatchMode watchMode) { - return (watchMode == WatchMode.LOW_BIT) || (watchMode == WatchMode.LOW_BIT_BURN_IN); - } - - - @Override - protected WatchFaceStyle getWatchFaceStyle(){ - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - - - public int ageLevel() { - if(timeSince() <= (1000 * 60 * 12)) { - return 1; - } else { - return 0; - } - } - - public double timeSince() { - return System.currentTimeMillis() - datetime; - } - - public String readingAge(boolean shortString) { - if (datetime == 0) { return shortString?"--'":"-- Minute ago"; } - int minutesAgo = (int) Math.floor(timeSince()/(1000*60)); - if (minutesAgo == 1) { - return minutesAgo + (shortString?"'":" Minute ago"); - } - return minutesAgo + (shortString?"'":" Minutes ago"); - } - - @Override - public void onDestroy() { - if(localBroadcastManager != null && messageReceiver != null){ - localBroadcastManager.unregisterReceiver(messageReceiver);} - if (sharedPrefs != null){ - sharedPrefs.unregisterOnSharedPreferenceChangeListener(this); - } - super.onDestroy(); - } - - static { - INTENT_FILTER = new IntentFilter(); - INTENT_FILTER.addAction(Intent.ACTION_TIME_TICK); - INTENT_FILTER.addAction(Intent.ACTION_TIMEZONE_CHANGED); - INTENT_FILTER.addAction(Intent.ACTION_TIME_CHANGED); - } - - @Override - protected void onDraw(Canvas canvas) { - if(layoutSet) { - this.mRelativeLayout.draw(canvas); - Log.d("onDraw", "draw"); - } - } - - @Override - protected void onTimeChanged(WatchFaceTime oldTime, WatchFaceTime newTime) { - if (layoutSet && (newTime.hasHourChanged(oldTime) || newTime.hasMinuteChanged(oldTime))) { - wakeLock.acquire(50); - final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(NOChart.this); - mTime.setText(timeFormat.format(System.currentTimeMillis())); - showAgeAndStatus(); - - if(ageLevel()<=0) { - mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - - missedReadingAlert(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - } - - public class MessageReceiver extends BroadcastReceiver { - @Override - public void onReceive(Context context, Intent intent) { - Bundle bundle = intent.getBundleExtra("data"); - if (layoutSet && bundle !=null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(50); - sgvLevel = dataMap.getLong("sgvLevel"); - batteryLevel = dataMap.getInt("batteryLevel"); - datetime = dataMap.getLong("timestamp"); - sgvString = dataMap.getString("sgvString"); - mSgv.setText(dataMap.getString("sgvString")); - - if(ageLevel()<=0) { - mSgv.setPaintFlags(mSgv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); - } else { - mSgv.setPaintFlags(mSgv.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); - } - - final java.text.DateFormat timeFormat = DateFormat.getTimeFormat(NOChart.this); - mTime.setText(timeFormat.format(System.currentTimeMillis())); - - showAgeAndStatus(); - - String delta = dataMap.getString("delta"); - - if (delta.endsWith(" mg/dl")) { - mDelta.setText(delta.substring(0, delta.length() - 6)); - } else if (delta.endsWith(" mmol/l")||delta.endsWith(" mmol")) { - mDelta.setText(delta.substring(0, delta.length() - 5)); - } else { - mDelta.setText(delta); - } - - - String avgDelta = dataMap.getString("avgDelta"); - - if (delta.endsWith(" mg/dl")) { - mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 6)); - } else if (avgDelta.endsWith(" mmol/l")||avgDelta.endsWith(" mmol")) { - mAvgDelta.setText(avgDelta.substring(0, avgDelta.length() - 5)); - } else { - mAvgDelta.setText(avgDelta); - } - - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - - //start animation? - // dataMap.getDataMapArrayList("entries") == null -> not on "resend data". - if (!lowResMode && (sharedPrefs.getBoolean("animation", false) && dataMap.getDataMapArrayList("entries") == null && (sgvString.equals("100") || sgvString.equals("5.5") || sgvString.equals("5,5")))) { - startAnimation(); - } - } - //status - bundle = intent.getBundleExtra("status"); - if (layoutSet && bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(50); - externalStatusString = dataMap.getString("externalStatusString"); - - showAgeAndStatus(); - - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - } - //basals and temps - bundle = intent.getBundleExtra("basals"); - if (layoutSet && bundle != null) { - DataMap dataMap = DataMap.fromBundle(bundle); - wakeLock.acquire(500); - - loadBasalsAndTemps(dataMap); - - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - invalidate(); - setColor(); - } - } - } - - private void loadBasalsAndTemps(DataMap dataMap) { - ArrayList temps = dataMap.getDataMapArrayList("temps"); - if (temps != null) { - tempWatchDataList = new ArrayList<>(); - for (DataMap temp : temps) { - TempWatchData twd = new TempWatchData(); - twd.startTime = temp.getLong("starttime"); - twd.startBasal = temp.getDouble("startBasal"); - twd.endTime = temp.getLong("endtime"); - twd.endBasal = temp.getDouble("endbasal"); - twd.amount = temp.getDouble("amount"); - tempWatchDataList.add(twd); - } - } - ArrayList basals = dataMap.getDataMapArrayList("basals"); - if (basals != null) { - basalWatchDataList = new ArrayList<>(); - for (DataMap basal : basals) { - BasalWatchData bwd = new BasalWatchData(); - bwd.startTime = basal.getLong("starttime"); - bwd.endTime = basal.getLong("endtime"); - bwd.amount = basal.getDouble("amount"); - basalWatchDataList.add(bwd); - } - } - } - - private void showAgeAndStatus() { - - if( mTimestamp != null){ - mTimestamp.setText(readingAge(true)); - } - boolean showAvgDelta = sharedPrefs.getBoolean("showAvgDelta", true); - - if(showAvgDelta){ - mAvgDelta.setVisibility(View.VISIBLE); - } else { - mAvgDelta.setVisibility(View.GONE); - } - statusView.setText(externalStatusString); - statusView.setVisibility(View.VISIBLE); - } - - public void setColor() { - if(lowResMode){ - setColorLowRes(); - } else if (sharedPrefs.getBoolean("dark", true)) { - setColorDark(); - } else { - setColorBright(); - } - - } - - - - @Override - public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key){ - setColor(); - if(layoutSet){ - showAgeAndStatus(); - mRelativeLayout.measure(specW, specH); - mRelativeLayout.layout(0, 0, mRelativeLayout.getMeasuredWidth(), - mRelativeLayout.getMeasuredHeight()); - } - invalidate(); - } - - protected void updateRainbow() { - animationAngle = (animationAngle + 1) % 360; - //Animation matrix: - int[] rainbow = {Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE - , Color.CYAN}; - Shader shader = new LinearGradient(0, 0, 0, 20, rainbow, - null, Shader.TileMode.MIRROR); - Matrix matrix = new Matrix(); - matrix.setRotate(animationAngle); - shader.setLocalMatrix(matrix); - mSgv.getPaint().setShader(shader); - invalidate(); - } - - private synchronized void setIsAnimated(boolean isAnimated) { - this.isAnimated = isAnimated; - } - - void startAnimation() { - Log.d("CircleWatchface", "start startAnimation"); - - Thread animator = new Thread() { - - - public void run() { - setIsAnimated(true); - for (int i = 0; i <= 8 * 1000 / 40; i++) { - updateRainbow(); - SystemClock.sleep(40); - } - mSgv.getPaint().setShader(null); - setIsAnimated(false); - invalidate(); - setColor(); - - System.gc(); - } - }; - - animator.start(); - } - - protected void setColorLowRes() { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - } - - protected void setColorDark() { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_mTime)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_statusView)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_background)); - if (sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_highColor)); - } else if (sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_midColor)); - } else if (sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_Timestamp)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.dark_TimestampOld)); - } - } - - - protected void setColorBright() { - - if (getCurrentWatchMode() == WatchMode.INTERACTIVE) { - mTime.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_time)); - statusView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_bigchart_status)); - mRelativeLayout.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.light_background)); - if (sgvLevel == 1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_highColor)); - } else if (sgvLevel == 0) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_midColor)); - } else if (sgvLevel == -1) { - mSgv.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - mAvgDelta.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_lowColor)); - } - - if (ageLevel == 1) { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp1)); - } else { - mTimestamp.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.light_mTimestamp)); - } - } else { - setColorDark(); - } - } - - public void missedReadingAlert() { - int minutes_since = (int) Math.floor(timeSince()/(1000*60)); - if(minutes_since >= 16 && ((minutes_since - 16) % 5) == 0) { - ListenerService.requestData(this); // attempt endTime recover missing data - } - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt new file mode 100644 index 0000000000..bcbb388684 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/NoChartWatchface.kt @@ -0,0 +1,87 @@ +package info.nightscout.androidaps.watchfaces + +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import com.ustwo.clockwise.common.WatchMode +import info.nightscout.androidaps.R + +class NoChartWatchface : BaseWatchFace() { + + @LayoutRes override fun layoutResource(): Int = + if (resources.displayMetrics.widthPixels < SCREEN_SIZE_SMALL || resources.displayMetrics.heightPixels < SCREEN_SIZE_SMALL) R.layout.activity_nochart_small + else R.layout.activity_nochart + + override fun setColorLowRes() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + } + + override fun setColorDark() { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.dark_mTime)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.dark_statusView)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.dark_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.dark_lowColor)) + } + } + if (ageLevel == 1) { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_Timestamp)) + } else { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.dark_TimestampOld)) + } + } + + override fun setColorBright() { + if (currentWatchMode == WatchMode.INTERACTIVE) { + mTime?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_time)) + mStatus?.setTextColor(ContextCompat.getColor(this, R.color.light_bigchart_status)) + mRelativeLayout?.setBackgroundColor(ContextCompat.getColor(this, R.color.light_background)) + when (singleBg.sgvLevel) { + 1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_highColor)) + } + + 0L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_midColor)) + } + + -1L -> { + mSgv?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + mAvgDelta?.setTextColor(ContextCompat.getColor(this, R.color.light_lowColor)) + } + } + if (ageLevel == 1) { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp1)) + } else { + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.light_mTimestamp)) + } + } else { + setColorDark() + } + } +} \ No newline at end of file diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java b/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java deleted file mode 100644 index 644c17668d..0000000000 --- a/wear/src/main/java/info/nightscout/androidaps/watchfaces/Steampunk.java +++ /dev/null @@ -1,271 +0,0 @@ -package info.nightscout.androidaps.watchfaces; - -import android.content.Intent; -import androidx.core.content.ContextCompat; -import android.support.wearable.watchface.WatchFaceStyle; -import android.view.LayoutInflater; -import android.view.animation.Animation; -import android.view.animation.LinearInterpolator; -import android.view.animation.RotateAnimation; - -import info.nightscout.androidaps.R; -import info.nightscout.androidaps.interaction.menus.MainMenuActivity; -import info.nightscout.shared.SafeParse; - -/** - * Created by andrew-warrington on 01/12/2017. - */ - -public class Steampunk extends BaseWatchFace { - - private long chartTapTime = 0; - private long mainMenuTapTime = 0; - private float lastEndDegrees = 0f; - private float deltaRotationAngle = 0f; - - @Override - public void onCreate() { - forceSquareCanvas = true; - super.onCreate(); - LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); - layoutView = inflater.inflate(R.layout.activity_steampunk, null); - performViewSetup(); - } - - @Override - protected void onTapCommand(int tapType, int x, int y, long eventTime) { - - if (tapType == TAP_TYPE_TAP&& - x >= mChartTap.getLeft() && - x <= mChartTap.getRight()&& - y >= mChartTap.getTop() && - y <= mChartTap.getBottom()){ - if (eventTime - chartTapTime < 800){ - changeChartTimeframe(); - } - chartTapTime = eventTime; - - } else if (tapType == TAP_TYPE_TAP&& - x >= mMainMenuTap.getLeft() && - x <= mMainMenuTap.getRight()&& - y >= mMainMenuTap.getTop() && - y <= mMainMenuTap.getBottom()){ - if (eventTime - mainMenuTapTime < 800){ - Intent intent = new Intent(this, MainMenuActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - startActivity(intent); - } - mainMenuTapTime = eventTime; - } - } - - @Override - protected WatchFaceStyle getWatchFaceStyle() { - return new WatchFaceStyle.Builder(this).setAcceptsTapEvents(true).build(); - } - - protected void setColorDark() { - - if (mLinearLayout2 != null) { - if (ageLevel() <= 0 && rawData.datetime != 0) { - mLinearLayout2.setBackgroundResource(R.drawable.redline); - mTimestamp.setTextColor(getResources().getColor(R.color.red_600)); - } else { - mLinearLayout2.setBackgroundResource(0); - mTimestamp.setTextColor(getResources().getColor(R.color.black_86p)); - } - } - - if (mLoop != null) { - if (loopLevel == 0) { - mLoop.setTextColor(getResources().getColor(R.color.red_600)); - } else { - mLoop.setTextColor(getResources().getColor(R.color.black_86p)); - } - } - - if (!rawData.sSgv.equals("---")) { - - float rotationAngle = 0f; //by default, show ? on the dial (? is at 0 degrees on the dial) - - if (!rawData.sUnits.equals("-")) { - - //ensure the glucose dial is the correct units - if (rawData.sUnits.equals("mmol")) { - mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mmol); - } else { - mGlucoseDial.setImageResource(R.drawable.steampunk_dial_mgdl); - } - - //convert the Sgv to degrees of rotation - if (rawData.sUnits.equals("mmol")) { - rotationAngle = Float.valueOf(rawData.sSgv) * 18f; //convert to mg/dL, which is equivalent to degrees - } else { - rotationAngle = Float.valueOf(rawData.sSgv); //if glucose a value is received, use it to determine the amount of rotation of the dial. - } - - } - - if (rotationAngle > 330) rotationAngle = 330; //if the glucose value is higher than 330 then show "HIGH" on the dial. ("HIGH" is at 330 degrees on the dial) - if (rotationAngle != 0 && rotationAngle < 30) rotationAngle = 30; //if the glucose value is lower than 30 show "LOW" on the dial. ("LOW" is at 30 degrees on the dial) - if (lastEndDegrees == 0) lastEndDegrees = rotationAngle; - - //rotate glucose dial - RotateAnimation rotate = new RotateAnimation( - lastEndDegrees, rotationAngle - lastEndDegrees, - Animation.RELATIVE_TO_SELF, 0.5f, - Animation.RELATIVE_TO_SELF, 0.5f); - rotate.setFillAfter(true); - rotate.setInterpolator(new LinearInterpolator()); - rotate.setDuration(1); - mGlucoseDial.startAnimation(rotate); - lastEndDegrees = rotationAngle; //store the final angle as a starting point for the next rotation. - } - - //set the delta gauge and rotate the delta pointer - float deltaIsNegative = 1f; //by default go clockwise - if (!rawData.sAvgDelta.equals("--")) { //if a legitimate delta value is received, then... - if (rawData.sAvgDelta.charAt(0) == '-') deltaIsNegative = -1f; //if the delta is negative, go counter-clockwise - Float AbssAvgDelta = SafeParse.stringToFloat(rawData.sAvgDelta.substring(1)) ; //get rid of the sign so it can be converted to float. - String autogranularity = "0" ; //autogranularity off - //ensure the delta gauge is the right units and granularity - if (!rawData.sUnits.equals("-")) { - if (rawData.sUnits.equals("mmol")) { - if (sharedPrefs.getString("delta_granularity", "2").equals("4")) { //Auto granularity - autogranularity = "1"; // low (init) - if (AbssAvgDelta < 0.3 ) { - autogranularity = "3" ; // high if below 0.3 mmol/l - } else if (AbssAvgDelta < 0.5) { - autogranularity = "2" ; // medium if below 0.5 mmol/l - } - } - if (sharedPrefs.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_10); - deltaRotationAngle = (AbssAvgDelta * 30f); - } - if (sharedPrefs.getString("delta_granularity", "2").equals("2") || autogranularity.equals("2")) { //medium - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_05); - deltaRotationAngle = (AbssAvgDelta * 60f); - } - if (sharedPrefs.getString("delta_granularity", "2").equals("3") || autogranularity.equals("3")) { //high - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mmol_03); - deltaRotationAngle = (AbssAvgDelta * 100f); - } - } else { - if (sharedPrefs.getString("delta_granularity", "2").equals("4")) { //Auto granularity - autogranularity = "1"; // low (init) - if (AbssAvgDelta < 5 ) { - autogranularity = "3" ; // high if below 5 mg/dl - } else if (AbssAvgDelta < 10) { - autogranularity = "2" ; // medium if below 10 mg/dl - } - } - if (sharedPrefs.getString("delta_granularity", "2").equals("1") || autogranularity.equals("1")) { //low - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_20); - deltaRotationAngle = (AbssAvgDelta * 1.5f); - } - if (sharedPrefs.getString("delta_granularity", "2").equals("2") || autogranularity.equals("2")) { //medium - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_10); - deltaRotationAngle = (AbssAvgDelta * 3f); - } - if (sharedPrefs.getString("delta_granularity", "2").equals("3") || autogranularity.equals("3")) { //high - mLinearLayout.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_5); - deltaRotationAngle = (AbssAvgDelta * 6f); - } - } - } - if (deltaRotationAngle > 40) deltaRotationAngle = 40f; - mDeltaGauge.setRotation(deltaRotationAngle * deltaIsNegative); - } - - //rotate the minute hand. - mMinuteHand.setRotation(Float.valueOf(sMinute) * 6f); - - //rotate the hour hand. - mHourHand.setRotation((Float.valueOf(sHour) * 30f) + (Float.valueOf(sMinute) * 0.5f)); - - setTextSizes(); - - if (mLoop != null) { - mLoop.setBackgroundResource(0); - } - - if (chart != null) { - highColor = ContextCompat.getColor(getApplicationContext(), R.color.black); - lowColor = ContextCompat.getColor(getApplicationContext(), R.color.black); - midColor = ContextCompat.getColor(getApplicationContext(), R.color.black); - gridColor = ContextCompat.getColor(getApplicationContext(), R.color.grey_steampunk); - basalBackgroundColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - basalCenterColor = ContextCompat.getColor(getApplicationContext(), R.color.basal_dark); - if (Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")) < 3) { - pointSize = 2; - } else { - pointSize = 1; - } - setupCharts(); - } - - invalidate(); - - } - - protected void setColorLowRes() { - setColorDark(); - } - - protected void setColorBright() { - setColorDark(); - } - - protected void setTextSizes() { - - float fontSmall = 10f; - float fontMedium = 11f; - float fontLarge = 12f; - - if (bIsRound) { - fontSmall = 11f; - fontMedium = 12f; - fontLarge = 13f; - } - - //top row. large font unless text too big (i.e. detailedIOB) - mCOB2.setTextSize(fontLarge); - mBasalRate.setTextSize(fontLarge); - if (rawData.sIOB2.length() < 7) { - mIOB2.setTextSize(fontLarge); - } else { - mIOB2.setTextSize(fontSmall); - } - - //bottom row. font medium unless text too long (i.e. longer than 9' timestamp) - if (mTimestamp.getText().length() < 3 || mLoop.getText().length() < 3) { //always resize these fields together, for symmetry. - mTimestamp.setTextSize(fontMedium); - mLoop.setTextSize(fontMedium); - } else { - mTimestamp.setTextSize(fontSmall); - mLoop.setTextSize(fontSmall); - } - - //if both batteries are shown, make them smaller. - if (sharedPrefs.getBoolean("show_uploader_battery", true) && sharedPrefs.getBoolean("show_rig_battery", false)) { - mUploaderBattery.setTextSize(fontSmall); - mRigBattery.setTextSize(fontSmall); - } else { - mUploaderBattery.setTextSize(fontMedium); - mRigBattery.setTextSize(fontMedium); - } - } - - private void changeChartTimeframe() { - int timeframe = Integer.parseInt(sharedPrefs.getString("chart_timeframe", "3")); - timeframe = (timeframe%5) + 1; - if (timeframe < 3) { - pointSize = 2; - } else { - pointSize = 1; - } - setupCharts(); - sharedPrefs.edit().putString("chart_timeframe", "" + timeframe).apply(); - } -} diff --git a/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt new file mode 100644 index 0000000000..3bc0c08ae1 --- /dev/null +++ b/wear/src/main/java/info/nightscout/androidaps/watchfaces/SteampunkWatchface.kt @@ -0,0 +1,203 @@ +@file:Suppress("DEPRECATION") + +package info.nightscout.androidaps.watchfaces + +import android.view.animation.Animation +import android.view.animation.LinearInterpolator +import android.view.animation.RotateAnimation +import androidx.annotation.LayoutRes +import androidx.core.content.ContextCompat +import info.nightscout.androidaps.R +import info.nightscout.shared.SafeParse.stringToFloat +import org.joda.time.TimeOfDay + +/** + * Created by andrew-warrington on 01/12/2017. + * Refactored by MilosKozak on 23/04/2022 + */ +class SteampunkWatchface : BaseWatchFace() { + + private var lastEndDegrees = 0f + private var deltaRotationAngle = 0f + + @LayoutRes override fun layoutResource(): Int = R.layout.activity_steampunk + + override fun onCreate() { + forceSquareCanvas = true + super.onCreate() + } + + override fun setColorDark() { + if (ageLevel() <= 0 && singleBg.timeStamp != 0L) { + mLinearLayout2?.setBackgroundResource(R.drawable.redline) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.red_600)) + } else { + mLinearLayout2?.setBackgroundResource(0) + mTimestamp?.setTextColor(ContextCompat.getColor(this, R.color.black_86p)) + } + mLoop?.setTextColor(ContextCompat.getColor(this, if (loopLevel == 0) R.color.red_600 else R.color.black_86p)) + if (singleBg.sgvString != "---") { + var rotationAngle = 0f //by default, show ? on the dial (? is at 0 degrees on the dial) + if (singleBg.glucoseUnits != "-") { + + //ensure the glucose dial is the correct units + mGlucoseDial?.setImageResource(if (singleBg.glucoseUnits == "mmol") R.drawable.steampunk_dial_mmol else R.drawable.steampunk_dial_mgdl) + + //convert the Sgv to degrees of rotation + rotationAngle = + if (singleBg.glucoseUnits == "mmol") stringToFloat(singleBg.sgvString) * 18f //convert to mg/dL, which is equivalent to degrees + else stringToFloat(singleBg.sgvString) //if glucose a value is received, use it to determine the amount of rotation of the dial. + } + if (rotationAngle > 330) rotationAngle = 330f //if the glucose value is higher than 330 then show "HIGH" on the dial. ("HIGH" is at 330 degrees on the dial) + if (rotationAngle != 0f && rotationAngle < 30) rotationAngle = 30f //if the glucose value is lower than 30 show "LOW" on the dial. ("LOW" is at 30 degrees on the dial) + if (lastEndDegrees == 0f) lastEndDegrees = rotationAngle + + //rotate glucose dial + val rotate = RotateAnimation(lastEndDegrees, rotationAngle - lastEndDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f).apply { + fillAfter = true + interpolator = LinearInterpolator() + duration = 1 + } + mGlucoseDial?.startAnimation(rotate) + lastEndDegrees = rotationAngle //store the final angle as a starting point for the next rotation. + } + + //set the delta gauge and rotate the delta pointer + var deltaIsNegative = 1f //by default go clockwise + if (singleBg.avgDelta != "--") { //if a legitimate delta value is + // received, + // then... + if (singleBg.avgDelta[0] == '-') deltaIsNegative = -1f //if the delta is negative, go counter-clockwise + val absAvgDelta = stringToFloat(singleBg.avgDelta.substring(1)) //get rid of the sign so it can be converted to float. + var autoGranularity = "0" //auto-granularity off + //ensure the delta gauge is the right units and granularity + if (singleBg.glucoseUnits != "-") { + if (singleBg.glucoseUnits == "mmol") { + if (sp.getString("delta_granularity", "2") == "4") { //Auto granularity + autoGranularity = + when { + absAvgDelta < 0.3 -> "3" // high if below 0.3 mmol/l + absAvgDelta < 0.5 -> "2" // medium if below 0.5 mmol/l + else -> "1" // low (init) + } + } + if (sp.getString("delta_granularity", "2") == "1" || autoGranularity == "1") { //low + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mmol_10) + deltaRotationAngle = absAvgDelta * 30f + } + if (sp.getString("delta_granularity", "2") == "2" || autoGranularity == "2") { //medium + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mmol_05) + deltaRotationAngle = absAvgDelta * 60f + } + if (sp.getString("delta_granularity", "2") == "3" || autoGranularity == "3") { //high + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mmol_03) + deltaRotationAngle = absAvgDelta * 100f + } + } else { + if (sp.getString("delta_granularity", "2") == "4") { //Auto granularity + autoGranularity = + when { + absAvgDelta < 5 -> "3" // high if below 5 mg/dl + absAvgDelta < 10 -> "2" // medium if below 10 mg/dl + else -> "1" // low (init) + } + } + if (sp.getString("delta_granularity", "2") == "1" || autoGranularity == "1") { //low + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_20) + deltaRotationAngle = absAvgDelta * 1.5f + } + if (sp.getString("delta_granularity", "2") == "2" || autoGranularity == "2") { //medium + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_10) + deltaRotationAngle = absAvgDelta * 3f + } + if (sp.getString("delta_granularity", "2") == "3" || autoGranularity == "3") { //high + mLinearLayout?.setBackgroundResource(R.drawable.steampunk_gauge_mgdl_5) + deltaRotationAngle = absAvgDelta * 6f + } + } + } + if (deltaRotationAngle > 40) deltaRotationAngle = 40f + mDeltaGauge?.rotation = deltaRotationAngle * deltaIsNegative + } + + //rotate the minute hand. + mMinuteHand?.rotation = TimeOfDay().minuteOfHour * 6f + + //rotate the hour hand. + mHourHand?.rotation = TimeOfDay().hourOfDay * 30f + TimeOfDay().minuteOfHour * 0.5f + setTextSizes() + mLoop?.setBackgroundResource(0) + if (chart != null) { + highColor = ContextCompat.getColor(this, R.color.black) + lowColor = ContextCompat.getColor(this, R.color.black) + midColor = ContextCompat.getColor(this, R.color.black) + gridColor = ContextCompat.getColor(this, R.color.grey_steampunk) + basalBackgroundColor = ContextCompat.getColor(this, R.color.basal_dark) + basalCenterColor = ContextCompat.getColor(this, R.color.basal_dark) + pointSize = if (sp.getInt(R.string.key_chart_time_frame, 3) < 3) { + 2 + } else { + 1 + } + setupCharts() + } + invalidate() + } + + override fun setColorLowRes() { + setColorDark() + } + + override fun setColorBright() { + setColorDark() + } + + private fun setTextSizes() { + var fontSmall = 10f + var fontMedium = 11f + var fontLarge = 12f + if (bIsRound) { + fontSmall = 11f + fontMedium = 12f + fontLarge = 13f + } + + //top row. large font unless text too big (i.e. detailedIOB) + mCOB2?.textSize = fontLarge + mBasalRate?.textSize = fontLarge + if (status.iobDetail.length < 7) { + mIOB2?.textSize = fontLarge + } else { + mIOB2?.textSize = fontSmall + } + + //bottom row. font medium unless text too long (i.e. longer than 9' timestamp) + mLoop?.let { mLoop -> + mTimestamp?.let { mTimestamp -> + if (mTimestamp.text.length < 3 || mLoop.text.length < 3) { //always resize these fields together, for symmetry. + mTimestamp.textSize = fontMedium + mLoop.textSize = fontMedium + } else { + mTimestamp.textSize = fontSmall + mLoop.textSize = fontSmall + } + } + } + + //if both batteries are shown, make them smaller. + if (sp.getBoolean("show_uploader_battery", true) && sp.getBoolean("show_rig_battery", false)) { + mUploaderBattery?.textSize = fontSmall + mRigBattery?.textSize = fontSmall + } else { + mUploaderBattery?.textSize = fontMedium + mRigBattery?.textSize = fontMedium + } + } + + override fun changeChartTimeframe() { + var timeframe = sp.getInt(R.string.key_chart_time_frame, 3) + timeframe = timeframe % 5 + 1 + pointSize = if (timeframe < 3) 2 else 1 + sp.putInt(R.string.key_chart_time_frame, timeframe) + } +} \ No newline at end of file diff --git a/wear/src/main/res/layout/rect_activity_bigchart.xml b/wear/src/main/res/layout-notround/activity_bigchart.xml similarity index 97% rename from wear/src/main/res/layout/rect_activity_bigchart.xml rename to wear/src/main/res/layout-notround/activity_bigchart.xml index 10540e5247..d610c6f38b 100644 --- a/wear/src/main/res/layout/rect_activity_bigchart.xml +++ b/wear/src/main/res/layout-notround/activity_bigchart.xml @@ -1,7 +1,7 @@ @@ -65,7 +65,7 @@ android:gravity="center_horizontal" /> @@ -57,7 +57,7 @@ diff --git a/wear/src/main/res/layout/rect_activity_digitalstyle.xml b/wear/src/main/res/layout-notround/activity_digitalstyle.xml similarity index 96% rename from wear/src/main/res/layout/rect_activity_digitalstyle.xml rename to wear/src/main/res/layout-notround/activity_digitalstyle.xml index b7304d1836..294d708df4 100644 --- a/wear/src/main/res/layout/rect_activity_digitalstyle.xml +++ b/wear/src/main/res/layout-notround/activity_digitalstyle.xml @@ -6,7 +6,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" - tools:context=".watchfaces.DigitalStyle" + tools:context=".watchfaces.DigitalStyleWatchface" tools:deviceIds="wear_square"> @@ -28,6 +28,7 @@ - - + + diff --git a/wear/src/main/res/layout/rect_activity_home.xml b/wear/src/main/res/layout-notround/activity_home.xml similarity index 99% rename from wear/src/main/res/layout/rect_activity_home.xml rename to wear/src/main/res/layout-notround/activity_home.xml index c619efbb37..dd700fcf5c 100644 --- a/wear/src/main/res/layout/rect_activity_home.xml +++ b/wear/src/main/res/layout-notround/activity_home.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout/rect_activity_home_2.xml b/wear/src/main/res/layout-notround/activity_home_2.xml similarity index 99% rename from wear/src/main/res/layout/rect_activity_home_2.xml rename to wear/src/main/res/layout-notround/activity_home_2.xml index 6f8e811f22..60ae6c3cf6 100644 --- a/wear/src/main/res/layout/rect_activity_home_2.xml +++ b/wear/src/main/res/layout-notround/activity_home_2.xml @@ -5,7 +5,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" - tools:context=".watchfaces.Home2" + tools:context=".watchfaces.AapsV2Watchface" tools:deviceIds="wear_square"> diff --git a/wear/src/main/res/layout/round_activity_nochart.xml b/wear/src/main/res/layout-notround/activity_nochart.xml similarity index 91% rename from wear/src/main/res/layout/round_activity_nochart.xml rename to wear/src/main/res/layout-notround/activity_nochart.xml index 179b05d021..41f44e4404 100644 --- a/wear/src/main/res/layout/round_activity_nochart.xml +++ b/wear/src/main/res/layout-notround/activity_nochart.xml @@ -1,7 +1,7 @@ @@ -57,7 +57,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wear/src/main/res/layout/rect_steampunk.xml b/wear/src/main/res/layout-notround/activity_steampunk.xml similarity index 99% rename from wear/src/main/res/layout/rect_steampunk.xml rename to wear/src/main/res/layout-notround/activity_steampunk.xml index 771a03b619..e56d515d1b 100644 --- a/wear/src/main/res/layout/rect_steampunk.xml +++ b/wear/src/main/res/layout-notround/activity_steampunk.xml @@ -4,7 +4,7 @@ android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".watchfaces.Steampunk" + tools:context=".watchfaces.SteampunkWatchface" tools:deviceIds="wear_square"> @@ -65,7 +65,7 @@ android:gravity="center_horizontal" /> @@ -57,7 +57,7 @@ diff --git a/wear/src/main/res/layout/round_activity_digitalstyle.xml b/wear/src/main/res/layout-round/activity_digitalstyle.xml similarity index 96% rename from wear/src/main/res/layout/round_activity_digitalstyle.xml rename to wear/src/main/res/layout-round/activity_digitalstyle.xml index 20aeeef3fc..029cf9210b 100644 --- a/wear/src/main/res/layout/round_activity_digitalstyle.xml +++ b/wear/src/main/res/layout-round/activity_digitalstyle.xml @@ -6,7 +6,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" - tools:context=".watchfaces.DigitalStyle" + tools:context=".watchfaces.DigitalStyleWatchface" tools:deviceIds="wear_round"> @@ -28,6 +28,7 @@ - - + + diff --git a/wear/src/main/res/layout/round_activity_home.xml b/wear/src/main/res/layout-round/activity_home.xml similarity index 99% rename from wear/src/main/res/layout/round_activity_home.xml rename to wear/src/main/res/layout-round/activity_home.xml index f35a32a433..008ed7d129 100644 --- a/wear/src/main/res/layout/round_activity_home.xml +++ b/wear/src/main/res/layout-round/activity_home.xml @@ -1,7 +1,7 @@ diff --git a/wear/src/main/res/layout/round_activity_home_2.xml b/wear/src/main/res/layout-round/activity_home_2.xml similarity index 99% rename from wear/src/main/res/layout/round_activity_home_2.xml rename to wear/src/main/res/layout-round/activity_home_2.xml index 0bb9af387a..64e6a411f0 100644 --- a/wear/src/main/res/layout/round_activity_home_2.xml +++ b/wear/src/main/res/layout-round/activity_home_2.xml @@ -5,7 +5,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/black" - tools:context=".watchfaces.Home2" + tools:context=".watchfaces.AapsV2Watchface" tools:deviceIds="wear_round"> diff --git a/wear/src/main/res/layout/rect_activity_nochart.xml b/wear/src/main/res/layout-round/activity_nochart.xml similarity index 91% rename from wear/src/main/res/layout/rect_activity_nochart.xml rename to wear/src/main/res/layout-round/activity_nochart.xml index 179b05d021..41f44e4404 100644 --- a/wear/src/main/res/layout/rect_activity_nochart.xml +++ b/wear/src/main/res/layout-round/activity_nochart.xml @@ -1,7 +1,7 @@ @@ -57,7 +57,7 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/wear/src/main/res/layout/round_steampunk.xml b/wear/src/main/res/layout-round/activity_steampunk.xml similarity index 99% rename from wear/src/main/res/layout/round_steampunk.xml rename to wear/src/main/res/layout-round/activity_steampunk.xml index 12ff642119..78f9c52383 100644 --- a/wear/src/main/res/layout/round_steampunk.xml +++ b/wear/src/main/res/layout-round/activity_steampunk.xml @@ -4,7 +4,7 @@ android:id="@+id/main_layout" android:layout_width="match_parent" android:layout_height="match_parent" - tools:context=".watchfaces.Steampunk" + tools:context=".watchfaces.SteampunkWatchface" tools:deviceIds="wear_round"> - diff --git a/wear/src/main/res/layout/activity_bigchart_small.xml b/wear/src/main/res/layout/activity_bigchart_small.xml deleted file mode 100644 index 34ca885a09..0000000000 --- a/wear/src/main/res/layout/activity_bigchart_small.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/wear/src/main/res/layout/modern_layout.xml b/wear/src/main/res/layout/activity_circle.xml similarity index 100% rename from wear/src/main/res/layout/modern_layout.xml rename to wear/src/main/res/layout/activity_circle.xml diff --git a/wear/src/main/res/layout/activity_cockpit.xml b/wear/src/main/res/layout/activity_cockpit.xml deleted file mode 100644 index 06c1cd036d..0000000000 --- a/wear/src/main/res/layout/activity_cockpit.xml +++ /dev/null @@ -1,12 +0,0 @@ - - \ No newline at end of file diff --git a/wear/src/main/res/layout/activity_digitalstyle.xml b/wear/src/main/res/layout/activity_digitalstyle.xml deleted file mode 100644 index 5fd23a86b7..0000000000 --- a/wear/src/main/res/layout/activity_digitalstyle.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - \ No newline at end of file diff --git a/wear/src/main/res/layout/activity_home.xml b/wear/src/main/res/layout/activity_home.xml deleted file mode 100644 index a536938f68..0000000000 --- a/wear/src/main/res/layout/activity_home.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/wear/src/main/res/layout/activity_home_2.xml b/wear/src/main/res/layout/activity_home_2.xml deleted file mode 100644 index 1b3dd0be51..0000000000 --- a/wear/src/main/res/layout/activity_home_2.xml +++ /dev/null @@ -1,12 +0,0 @@ - - \ No newline at end of file diff --git a/wear/src/main/res/layout/activity_home_large.xml b/wear/src/main/res/layout/activity_home_large.xml deleted file mode 100644 index adff439ea1..0000000000 --- a/wear/src/main/res/layout/activity_home_large.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/wear/src/main/res/layout/activity_nochart.xml b/wear/src/main/res/layout/activity_nochart.xml deleted file mode 100644 index 4b7198aa78..0000000000 --- a/wear/src/main/res/layout/activity_nochart.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/wear/src/main/res/layout/activity_nochart_small.xml b/wear/src/main/res/layout/activity_nochart_small.xml deleted file mode 100644 index 955a214580..0000000000 --- a/wear/src/main/res/layout/activity_nochart_small.xml +++ /dev/null @@ -1,12 +0,0 @@ - - diff --git a/wear/src/main/res/layout/activity_steampunk.xml b/wear/src/main/res/layout/activity_steampunk.xml deleted file mode 100644 index 3fa994d818..0000000000 --- a/wear/src/main/res/layout/activity_steampunk.xml +++ /dev/null @@ -1,12 +0,0 @@ - - \ No newline at end of file diff --git a/wear/src/main/res/values/strings.xml b/wear/src/main/res/values/strings.xml index 56709347c7..bc56b0bb46 100644 --- a/wear/src/main/res/values/strings.xml +++ b/wear/src/main/res/values/strings.xml @@ -4,15 +4,15 @@ AAPS AAPS - AAPS - AAPS(Large) - AAPS(BigChart) - AAPS(NoChart) - AAPS(Circle) - AAPSv2 - AAPS(Cockpit) - AAPS(Steampunk) - AAPS(DigitalStyle) + AAPS + AAPS(Large) + AAPS(BigChart) + AAPS(NoChart) + AAPS(Circle) + AAPS(v2) + AAPS(Cockpit) + AAPS(Steampunk) + AAPS(DigitalStyle) AAPS(Actions) AAPS(Temp Target) @@ -70,7 +70,7 @@ Complication Tap Action Unicode in Complications Version: - more Watchface settings + More Watchface settings Look into Watchface configuration, please. TempT @@ -98,7 +98,7 @@ Calculation Requested Fill Requested Carbs Requested - CPP Requested + Profile Switch Requested Target Low High @@ -122,7 +122,7 @@ Pump Loop - CPP + Profile switch TDD Carb @@ -170,12 +170,6 @@ AAPS Bolus Progress Silent Bolus progress and cancel Bolus progress and cancel with less vibrations - QuickWizard - wearcontrol - units_mgdl - boluswizard_percentage - treatmentssafety_maxcarbs - treatmentssafety_maxbolus Off During Charging Always On Mode @@ -189,6 +183,29 @@ No config available Wear controls disabled No data available - quick_wizard_data_map + + QuickWizard + wearcontrol + units_mgdl + boluswizard_percentage + treatmentssafety_maxcarbs + treatmentssafety_maxbolus + quick_wizard_data + primefill + showWizard + singletarget + wizardpercentage + highlight_basals + chart_time_frame + show_week_number + show_date + show_cob + showBG + showExternalStatus + showAgo + showBigNumbers + showDelta + showAvgDelta + showRingHistory diff --git a/wear/src/main/res/values/wear.xml b/wear/src/main/res/values/wear.xml index 41df8ef193..2049ee7ec0 100644 --- a/wear/src/main/res/values/wear.xml +++ b/wear/src/main/res/values/wear.xml @@ -1,18 +1,25 @@ - + + + + + + + androidaps_wear - \ No newline at end of file + diff --git a/wear/src/main/res/xml/preferences.xml b/wear/src/main/res/xml/preferences.xml index efadbc39d9..a719b98f78 100644 --- a/wear/src/main/res/xml/preferences.xml +++ b/wear/src/main/res/xml/preferences.xml @@ -12,7 +12,7 @@ @@ -134,7 +134,7 @@ diff --git a/wear/src/main/res/xml/watch_face_configuration_home2.xml b/wear/src/main/res/xml/watch_face_configuration_home2.xml index be883d2f76..97c7294f8e 100644 --- a/wear/src/main/res/xml/watch_face_configuration_home2.xml +++ b/wear/src/main/res/xml/watch_face_configuration_home2.xml @@ -20,7 +20,7 @@ diff --git a/wear/src/test/java/info/nightscout/androidaps/TestBase.kt b/wear/src/test/java/info/nightscout/androidaps/TestBase.kt index 8dd48a7911..764f44687c 100644 --- a/wear/src/test/java/info/nightscout/androidaps/TestBase.kt +++ b/wear/src/test/java/info/nightscout/androidaps/TestBase.kt @@ -6,9 +6,9 @@ import info.nightscout.androidaps.interaction.utils.Persistence import info.nightscout.androidaps.interaction.utils.WearUtil import info.nightscout.androidaps.testing.mockers.WearUtilMocker import info.nightscout.androidaps.testing.mocks.SharedPreferencesMock -import info.nightscout.androidaps.utils.rx.AapsSchedulers -import info.nightscout.androidaps.utils.rx.TestAapsSchedulers +import info.nightscout.androidaps.utils.DateUtil import info.nightscout.shared.logging.AAPSLoggerTest +import info.nightscout.shared.sharedPreferences.SP import org.junit.Before import org.junit.Rule import org.mockito.ArgumentMatchers @@ -21,9 +21,10 @@ import java.util.* open class TestBase { @Mock lateinit var context: Context + @Mock lateinit var sp: SP + @Mock lateinit var dateUtil: DateUtil val aapsLogger = AAPSLoggerTest() - val aapsSchedulers: AapsSchedulers = TestAapsSchedulers() val wearUtil: WearUtil = Mockito.spy(WearUtil()) val wearUtilMocker = WearUtilMocker(wearUtil) @@ -47,21 +48,8 @@ open class TestBase { wearUtilMocker.prepareMockNoReal() wearUtil.aapsLogger = aapsLogger wearUtil.context = context - persistence = Mockito.spy(Persistence(context, aapsLogger, wearUtil)) + persistence = Mockito.spy(Persistence(aapsLogger, dateUtil, sp)) - Mockito.doAnswer { invocation -> - val payload = invocation.getArgument(0) - try { - return@doAnswer Base64.getDecoder().decode(payload) - } catch (ex: IllegalArgumentException) { - return@doAnswer null - } - }.`when`(persistence).base64decode(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) - - Mockito.doAnswer { invocation -> - val payload = invocation.getArgument(0) - Base64.getEncoder().encodeToString(payload) - }.`when`(persistence).base64encodeToString(ArgumentMatchers.any(), ArgumentMatchers.anyInt()) } // Add a JUnit rule that will setup the @Mock annotated vars and log. diff --git a/wear/src/test/java/info/nightscout/androidaps/data/BgWatchDataTest.java b/wear/src/test/java/info/nightscout/androidaps/data/BgWatchDataTest.java deleted file mode 100644 index 9149c16675..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/data/BgWatchDataTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package info.nightscout.androidaps.data; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import java.util.HashSet; -import java.util.Set; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; - -public class BgWatchDataTest extends TestBase { - - @Test - public void bgWatchDataHashTest() { - // GIVEN - BgWatchData inserted = new BgWatchData( - 88.0, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4, 1 - ); - Set set = new HashSet<>(); - - // THEN - //noinspection ConstantConditions - assertFalse(set.contains(inserted)); - set.add(inserted); - assertTrue(set.contains(inserted)); - } - - /** - * BgWatchData has BIZARRE equals - only timestamp and color are checked! - */ - @Test - public void bgWatchDataEqualsTest() { - // GIVEN - BgWatchData item1 = new BgWatchData( - 88.0, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1 - ); - - BgWatchData item2sameTimeSameColor = new BgWatchData( - 123.0, 190, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 1 - ); - - BgWatchData item3sameTimeSameDiffColor = new BgWatchData( - 96.0, 190, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS, 0 - ); - BgWatchData item4differentTime = new BgWatchData( - 88.0, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2, 1 - ); - - // THEN - assertEquals(item1, item2sameTimeSameColor); - assertNotEquals(item1, item3sameTimeSameDiffColor); - assertNotEquals(item1, item4differentTime); - } - - /** - * BgWatchData is ordered by timestamp, reverse order - */ - @Test - public void bgWatchDataCompareTest() { - // GIVEN - BgWatchData item1 = new BgWatchData( - 85, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2, 1 - ); - - BgWatchData item2 = new BgWatchData( - 80, 190, 90.0, - WearUtilMocker.REF_NOW, 1 - ); - - BgWatchData item3 = new BgWatchData( - 80, 190, 50.0, - WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS * 5, 0 - ); - - BgWatchData item4 = new BgWatchData( - 160, 140, 70.0, - WearUtilMocker.REF_NOW, 0 - ); - - // THEN - assertTrue(item2.compareTo(item1) < 0); - assertTrue(item2.compareTo(item3) > 0); - assertEquals(0, item2.compareTo(item4)); - } -} diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java deleted file mode 100644 index 942d634e32..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/data/RawDataSgvDisplayDataTest.java +++ /dev/null @@ -1,123 +0,0 @@ -package info.nightscout.androidaps.data; - -import static org.junit.Assert.assertEquals; - -import android.content.Intent; -import android.os.Bundle; - -import com.google.android.gms.wearable.DataMap; - -import org.junit.Test; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; -import info.nightscout.androidaps.testing.mocks.BundleMock; -import info.nightscout.androidaps.testing.mocks.IntentMock; - -public class RawDataSgvDisplayDataTest extends TestBase { - - //============================================================================================== - // SGV DATA - //============================================================================================== - - private DataMap dataMapForData() { - DataMap dataMap = new DataMap(); - dataMap.putLong("sgvLevel", 1L); - dataMap.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS); - dataMap.putString("sgvString", "106"); - dataMap.putString("slopeArrow", "↗"); - dataMap.putString("delta", "5.4"); - dataMap.putString("avgDelta", "3.7"); - dataMap.putString("glucoseUnits", "mg/dl"); - return dataMap; - } - - private void assertDataEmpty(RawDisplayData newRaw) { - assertEquals(newRaw.sgvLevel, 0L); - assertEquals(newRaw.datetime, 0L); - assertEquals(newRaw.sSgv, "---"); - assertEquals(newRaw.sDirection, "--"); - assertEquals(newRaw.sDelta, "--"); - assertEquals(newRaw.sAvgDelta, "--"); - assertEquals(newRaw.sUnits, "-"); - } - - private void assertDataOk(RawDisplayData newRaw) { - assertEquals(newRaw.sgvLevel, 1L); - assertEquals(newRaw.datetime, WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS); - assertEquals(newRaw.sSgv, "106"); - assertEquals(newRaw.sDirection, "↗"); - assertEquals(newRaw.sDelta, "5.4"); - assertEquals(newRaw.sAvgDelta, "3.7"); - assertEquals(newRaw.sUnits, "mg/dl"); - } - - @Test - public void updateDataFromEmptyPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateFromPersistence(persistence); - - // THEN - assertDataEmpty(newRaw); - } - - @Test - public void updateDataFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMapForData()); - newRaw.updateFromPersistence(persistence); - - // THEN - assertDataOk(newRaw); - } - - @Test - public void partialUpdateDataFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.DATA_PERSISTENCE_KEY, dataMapForData()); - newRaw.updateForComplicationsFromPersistence(persistence); - - // THEN - assertDataOk(newRaw); - } - - @Test - public void updateDataFromMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - Bundle bundle = BundleMock.mock(dataMapForData()); - - intent.putExtra("data", bundle); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateDataFromMessage(intent, null); - - // THEN - assertDataOk(newRaw); - } - - @Test - public void updateDataFromEmptyMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateDataFromMessage(intent, null); - - // THEN - assertDataEmpty(newRaw); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java deleted file mode 100644 index 960eeacee5..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBasalsTest.java +++ /dev/null @@ -1,242 +0,0 @@ -package info.nightscout.androidaps.data; - -import static org.junit.Assert.assertEquals; - -import android.content.Intent; -import android.os.Bundle; - -import com.google.android.gms.wearable.DataMap; - -import org.junit.Test; - -import java.util.ArrayList; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; -import info.nightscout.androidaps.testing.mocks.BundleMock; -import info.nightscout.androidaps.testing.mocks.IntentMock; -import info.nightscout.androidaps.testing.utils.BasalWatchDataExt; -import info.nightscout.androidaps.testing.utils.BgWatchDataExt; -import info.nightscout.androidaps.testing.utils.BolusWatchDataExt; -import info.nightscout.androidaps.testing.utils.TempWatchDataExt; - -@SuppressWarnings("SpellCheckingInspection") -public class RawDisplayDataBasalsTest extends TestBase { - - - //============================================================================================== - // BASALS for chart - //============================================================================================== - - private DataMap dataMapForBasals() { - - DataMap dataMap = new DataMap(); - - ArrayList temps = new ArrayList<>(); - DataMap temp = new DataMap(); - temp.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 20); - temp.putDouble("startBasal", 1.5); - temp.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 10); - temp.putDouble("endbasal", 1.5); - temp.putDouble("amount", 1.8); - temps.add(temp); - - DataMap temp2 = new DataMap(); - temp2.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 10); - temp2.putDouble("startBasal", 1.3); - temp2.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2); - temp2.putDouble("endbasal", 1.3); - temp2.putDouble("amount", 2.3); - temps.add(temp2); - dataMap.putDataMapArrayList("temps", temps); - - ArrayList basals = new ArrayList<>(); - DataMap basal = new DataMap(); - basal.putLong("starttime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 20); - basal.putLong("endtime", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2); - basal.putDouble("amount", 1.2); - basals.add(basal); - dataMap.putDataMapArrayList("basals", basals); - - ArrayList boluses = new ArrayList<>(); - DataMap bolus = new DataMap(); - bolus.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 17); - bolus.putDouble("bolus", 5.5); - bolus.putDouble("carbs", 20.0); - bolus.putBoolean("isSMB", false); - bolus.putBoolean("isValid", true); - boluses.add(bolus); - - DataMap bolus2 = new DataMap(); - bolus2.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 11); - bolus2.putDouble("bolus", 3.0); - bolus2.putDouble("carbs", 0.0); - bolus2.putBoolean("isSMB", false); - bolus2.putBoolean("isValid", true); - boluses.add(bolus2); - - DataMap bolus3 = new DataMap(); - bolus3.putLong("date", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 3); - bolus3.putDouble("bolus", 0.0); - bolus3.putDouble("carbs", 15.0); - bolus3.putBoolean("isSMB", true); - bolus3.putBoolean("isValid", false); - boluses.add(bolus3); - - dataMap.putDataMapArrayList("boluses", boluses); - - ArrayList predictions = new ArrayList<>(); - for (int i = 0; i < 10; i++) { - DataMap prediction = new DataMap(); - prediction.putLong("timestamp", WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS * i); - prediction.putDouble("sgv", 160 - 4 * i); - prediction.putInt("color", 0); - predictions.add(prediction); - } - dataMap.putDataMapArrayList("predictions", predictions); - - return dataMap; - } - - private void assertBasalsEmpty(RawDisplayData newRaw) { - assertEquals(newRaw.tempWatchDataList.size(), 0); - assertEquals(newRaw.basalWatchDataList.size(), 0); - assertEquals(newRaw.bolusWatchDataList.size(), 0); - assertEquals(newRaw.predictionList.size(), 0); - } - - private void assertBasalsOk(RawDisplayData newRaw) { - assertEquals(newRaw.tempWatchDataList.size(), 2); - assertEquals(newRaw.basalWatchDataList.size(), 1); - assertEquals(newRaw.bolusWatchDataList.size(), 3); - assertEquals(newRaw.predictionList.size(), 10); - - assertEquals(new TempWatchDataExt(newRaw.tempWatchDataList.get(0)), TempWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 20, - 1.5, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 10, - 1.5, - 1.8 - )); - - assertEquals(new TempWatchDataExt(newRaw.tempWatchDataList.get(1)), TempWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 10, - 1.3, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2, - 1.3, - 2.3 - )); - - assertEquals(new BasalWatchDataExt(newRaw.basalWatchDataList.get(0)), BasalWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 20, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2, - 1.2 - )); - - assertEquals(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(0)), BolusWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 17, - 5.5, - 20, - false, - true - )); - - assertEquals(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(1)), BolusWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 11, - 3, - 0, - false, - true - )); - - assertEquals(new BolusWatchDataExt(newRaw.bolusWatchDataList.get(2)), BolusWatchDataExt.build( - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 3, - 0, - 15, - true, - false - )); - - - assertEquals(new BgWatchDataExt(newRaw.predictionList.get(3)), BgWatchDataExt.build( - 160 - 4 * 3, - WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS * 3, - 0 - )); - - assertEquals(new BgWatchDataExt(newRaw.predictionList.get(7)), BgWatchDataExt.build( - 160 - 4 * 7, - WearUtilMocker.REF_NOW + Constants.MINUTE_IN_MS * 7, - 0 - )); - } - - @Test - public void updateBasalsFromEmptyPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateFromPersistence(persistence); - - // THEN - assertBasalsEmpty(newRaw); - } - - @Test - public void updateBasalsFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMapForBasals()); - newRaw.updateFromPersistence(persistence); - - // THEN - assertBasalsOk(newRaw); - } - - @Test - public void partialUpdateBasalsFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.BASALS_PERSISTENCE_KEY, dataMapForBasals()); - newRaw.updateForComplicationsFromPersistence(persistence); - - // THEN - assertBasalsEmpty(newRaw); - } - - @Test - public void updateBasalsFromMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - Bundle bundle = BundleMock.mock(dataMapForBasals()); - - intent.putExtra("basals", bundle); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateBasalsFromMessage(intent, null); - - // THEN - assertBasalsOk(newRaw); - } - - @Test - public void updateBasalsFromEmptyMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateBasalsFromMessage(intent, null); - - // THEN - assertBasalsEmpty(newRaw); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java deleted file mode 100644 index 61b5d119f1..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataBgEntriesTest.java +++ /dev/null @@ -1,135 +0,0 @@ -package info.nightscout.androidaps.data; - -import static org.junit.Assert.assertEquals; - -import com.google.android.gms.wearable.DataMap; - -import org.junit.Test; - -import java.util.ArrayList; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; -import info.nightscout.androidaps.testing.utils.BgWatchDataExt; - -@SuppressWarnings("PointlessArithmeticExpression") -public class RawDisplayDataBgEntriesTest extends TestBase { - - //============================================================================================== - // ENTRIES for chart - //============================================================================================== - - private DataMap dataMapForEntries() { - - DataMap dataMap = new DataMap(); - ArrayList entries = new ArrayList<>(); - for (int i = 0; i < 12; i++) { - DataMap entry = new DataMap(); - entry.putLong("timestamp", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * (16 - i)); - entry.putDouble("sgvDouble", 145.0 - 5 * i); - entry.putDouble("high", 170.0); - entry.putDouble("low", 80.0); - entry.putInt("color", 0); - entries.add(entry); - } - dataMap.putDataMapArrayList("entries", entries); - - return dataMap; - } - - private DataMap dataMapForEntries(long timestamp, double sgv) { - DataMap entry = new DataMap(); - entry.putLong("timestamp", timestamp); - entry.putDouble("sgvDouble", sgv); - entry.putDouble("high", 160.0); - entry.putDouble("low", 90.0); - entry.putInt("color", 1); - return entry; - } - - @Test - public void addToWatchSetTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - DataMap multipleEntries = dataMapForEntries(); - DataMap singleEntry1 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * 2, 92); - DataMap singleEntry2 = dataMapForEntries(WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * 1, 88); - - // WHEN, THEN - // add list - newRaw.addToWatchSet(multipleEntries); - assertEquals(newRaw.bgDataList.size(), 12); - - assertEquals(new BgWatchDataExt(newRaw.bgDataList.get(5)), - new BgWatchDataExt(new BgWatchData( - 120.0, 170.0, 80.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * (16 - 5), 0 - ))); - - assertEquals(new BgWatchDataExt(newRaw.bgDataList.get(11)), - new BgWatchDataExt(new BgWatchData( - 90.0, 170.0, 80.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * (16 - 11), 0 - ))); - - // add single entries - newRaw.addToWatchSet(singleEntry1); - newRaw.addToWatchSet(singleEntry2); - assertEquals(newRaw.bgDataList.size(), 14); - - assertEquals(new BgWatchDataExt(newRaw.bgDataList.get(12)), - new BgWatchDataExt(new BgWatchData( - 92.0, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * 2, 1 - ))); - assertEquals(new BgWatchDataExt(newRaw.bgDataList.get(13)), - new BgWatchDataExt(new BgWatchData( - 88.0, 160.0, 90.0, - WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 4 * 1, 1 - ))); - - // ignore duplicates - newRaw.addToWatchSet(singleEntry2); - assertEquals(newRaw.bgDataList.size(), 14); - } - - @Test - public void addToWatchSetCleanupOldTest() { - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 125)); - assertEquals(newRaw.bgDataList.size(), 1); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 2); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 140)); - assertEquals(newRaw.bgDataList.size(), 2); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 1); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 150)); - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 1 + Constants.MINUTE_IN_MS * 30); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 101)); - assertEquals(newRaw.bgDataList.size(), 4); - - getWearUtilMocker().progressClock(Constants.MINUTE_IN_MS * 30); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 90)); - assertEquals(newRaw.bgDataList.size(), 5); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 1 + Constants.MINUTE_IN_MS * 30); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 80)); - assertEquals(newRaw.bgDataList.size(), 5); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 4); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 92)); - assertEquals(newRaw.bgDataList.size(), 2); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 5 + Constants.MINUTE_IN_MS * 30); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp(), 107)); - assertEquals(newRaw.bgDataList.size(), 1); - - getWearUtilMocker().progressClock(Constants.HOUR_IN_MS * 6 + Constants.MINUTE_IN_MS * 30); - newRaw.addToWatchSet(dataMapForEntries(getWearUtil().timestamp() - Constants.HOUR_IN_MS * 6, 138)); - assertEquals(newRaw.bgDataList.size(), 0); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java b/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java deleted file mode 100644 index 834e801b70..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/data/RawDisplayDataStatusTest.java +++ /dev/null @@ -1,160 +0,0 @@ -package info.nightscout.androidaps.data; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import android.content.Intent; -import android.os.Bundle; - -import com.google.android.gms.wearable.DataMap; - -import org.junit.Before; -import org.junit.Test; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.testing.mockers.RawDataMocker; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; -import info.nightscout.androidaps.testing.mocks.BundleMock; -import info.nightscout.androidaps.testing.mocks.IntentMock; - -@SuppressWarnings("SimplifiableAssertion") -public class RawDisplayDataStatusTest extends TestBase { - - private RawDataMocker rawDataMocker; - - @Before - public void mock() { - rawDataMocker = new RawDataMocker(getWearUtil()); - } - - @SuppressWarnings("AssertBetweenInconvertibleTypes") @Test - public void toDebugStringTest() { - RawDisplayData raw = rawDataMocker.rawDelta(5, "1.5"); - raw.externalStatusString = "placeholder-here"; - - assertEquals(raw.datetime, WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 5); - assertTrue(raw.toDebugString().contains("placeholder-here")); - } - - //============================================================================================== - // STATUS - //============================================================================================== - - private DataMap dataMapForStatus() { - DataMap dataMap = new DataMap(); - dataMap.putString("currentBasal", "120%"); - dataMap.putString("battery", "76"); - dataMap.putString("rigBattery", "40%"); - dataMap.putBoolean("detailedIob", true); - dataMap.putString("iobSum", "12.5"); - dataMap.putString("iobDetail", "(11,2|1,3)"); - dataMap.putString("cob", "5(10)g"); - dataMap.putString("bgi", "13"); - dataMap.putBoolean("showBgi", false); - dataMap.putString("externalStatusString", ""); - dataMap.putInt("batteryLevel", 1); - dataMap.putLong("openApsStatus", WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2); - return dataMap; - } - - private void assertStatusEmpty(RawDisplayData newRaw) { - assertEquals(newRaw.sBasalRate, "-.--U/h"); - assertEquals(newRaw.sUploaderBattery, "--"); - assertEquals(newRaw.sRigBattery, "--"); - assertEquals(newRaw.detailedIOB, false); - assertEquals(newRaw.sIOB1, "IOB"); - assertEquals(newRaw.sIOB2, "-.--"); - assertEquals(newRaw.sCOB1, "Carb"); - assertEquals(newRaw.sCOB2, "--g"); - assertEquals(newRaw.sBgi, "--"); - assertEquals(newRaw.showBGI, false); - assertEquals(newRaw.externalStatusString, "no status"); - assertEquals(newRaw.batteryLevel, 1); - assertEquals(newRaw.openApsStatus, -1L); - } - - private void assertStatusOk(RawDisplayData newRaw) { - assertEquals(newRaw.sBasalRate, "120%"); - assertEquals(newRaw.sUploaderBattery, "76"); - assertEquals(newRaw.sRigBattery, "40%"); - assertEquals(newRaw.detailedIOB, true); - assertEquals(newRaw.sIOB1, "12.5U"); - assertEquals(newRaw.sIOB2, "(11,2|1,3)"); - assertEquals(newRaw.sCOB1, "Carb"); - assertEquals(newRaw.sCOB2, "5(10)g"); - assertEquals(newRaw.sBgi, "13"); - assertEquals(newRaw.showBGI, false); - assertEquals(newRaw.externalStatusString, ""); - assertEquals(newRaw.batteryLevel, 1); - assertEquals(newRaw.openApsStatus, WearUtilMocker.REF_NOW - Constants.MINUTE_IN_MS * 2); - } - - @Test - public void updateStatusFromEmptyPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateFromPersistence(persistence); - - // THEN - assertStatusEmpty(newRaw); - } - - @Test - public void updateStatusFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMapForStatus()); - newRaw.updateFromPersistence(persistence); - - // THEN - assertStatusOk(newRaw); - } - - @Test - public void partialUpdateStatusFromPersistenceTest() { - // GIVEN - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - persistence.storeDataMap(RawDisplayData.STATUS_PERSISTENCE_KEY, dataMapForStatus()); - newRaw.updateForComplicationsFromPersistence(persistence); - - // THEN - assertStatusOk(newRaw); - } - - @Test - public void updateStatusFromMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - Bundle bundle = BundleMock.mock(dataMapForStatus()); - - intent.putExtra("status", bundle); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateStatusFromMessage(intent, null); - - // THEN - assertStatusOk(newRaw); - } - - @Test - public void updateStatusFromEmptyMessageTest() { - // GIVEN - Intent intent = IntentMock.mock(); - RawDisplayData newRaw = new RawDisplayData(getWearUtil()); - - // WHEN - newRaw.updateStatusFromMessage(intent, null); - - // THEN - assertStatusEmpty(newRaw); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java deleted file mode 100644 index e6469b0110..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.java +++ /dev/null @@ -1,206 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mock; - -import info.nightscout.androidaps.TestBase; -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.testing.mockers.RawDataMocker; -import info.nightscout.androidaps.testing.mockers.WearUtilMocker; -import info.nightscout.shared.sharedPreferences.SP; - -/** - * This test covers DisplayFormat class (directly) - * but also SmallestDoubleString - due to carefully chosen input data to format - */ - -public class DisplayFormatTest extends TestBase { - - private DisplayFormat displayFormat; - private RawDataMocker rawDataMocker; - - private WearUtil wearUtil; - private WearUtilMocker wearUtilMocker; - @Mock SP sp; - - @Before - public void mock() { - wearUtil = spy(new WearUtil()); - rawDataMocker = new RawDataMocker(wearUtil); - wearUtilMocker = new WearUtilMocker(wearUtil); - wearUtilMocker.prepareMock(); - - displayFormat = new DisplayFormat(); - displayFormat.wearUtil = wearUtil; - displayFormat.sp = sp; - - when(sp.getBoolean("complication_unicode", true)).thenReturn(true); - } - - @Test - public void shortTimeSinceTest() { - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 0)), "0'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 5)), "0'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 55)), "0'"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 0)), "1'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 59)), "1'"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 2, 0)), "2'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 3, 0)), "3'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 4, 0)), "4'"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 10, 0)), "10'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 30, 0)), "30'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 0)), "59'"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 59)), "59'"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 0, 0)), "1h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 30, 0)), "1h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 59, 59)), "1h"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 2, 0, 0)), "2h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 3, 0, 0)), "3h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 4, 0, 0)), "4h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 5, 0, 0)), "5h"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 12, 0, 0)), "12h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 18, 0, 0)), "18h"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 23, 59, 59)), "23h"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 0, 0, 0)), "1d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 12, 0, 0)), "1d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 23, 59, 59)), "1d"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(2, 0, 0, 0)), "2d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(3, 0, 0, 0)), "3d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(4, 0, 0, 0)), "4d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(5, 0, 0, 0)), "5d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 0, 0, 0)), "6d"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 23, 59, 59)), "6d"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(7, 0, 0, 0)), "1w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(8, 0, 0, 0)), "1w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(9, 0, 0, 0)), "1w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(13, 23, 59, 59)), "1w"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(14, 0, 0, 0)), "2w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(21, 0, 0, 0)), "3w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(28, 0, 0, 0)), "4w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(31, 0, 0, 0)), "4w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(32, 0, 0, 0)), "4w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(35, 0, 0, 0)), "5w"); - - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(100, 0, 0, 0)), "14w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(200, 0, 0, 0)), "28w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(365, 0, 0, 0)), "52w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(366, 0, 0, 0)), "52w"); - assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(367, 0, 0, 0)), "52w"); - } - - @Test - public void shortTrendTest() { - RawDisplayData raw = new RawDisplayData(wearUtil); - assertEquals(displayFormat.shortTrend(raw), "-- Δ--"); - - raw.datetime = wearUtilMocker.backInTime(0, 0, 2, 0); - assertEquals(displayFormat.shortTrend(raw), "2' Δ--"); - - when(sp.getBoolean("complication_unicode", true)).thenReturn(true); - - // shortening - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1.2")), "2' Δ1.2"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(11, "1.2")), "11' 1.2"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(12, "0.7")), "12' Δ.7"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "1.0")), "10' Δ1"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(14, "-5.0")), "14' Δ-5"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(13, "-5.1")), "13' -5"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(15, "0.87")), "15' .87"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "-1.78")), "10' -2"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(3, "2.549")), "3' 2.55"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(1, "-1.563")), "1' -1.6"); - - // preserving separator - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1,2")), "2' Δ1,2"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(15, "0,87")), "15' ,87"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(3, "+2,549")), "3' 2,55"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(1, "-1,563")), "1' -1,6"); - - // UTF-off mode - without delta symbol - when(sp.getBoolean("complication_unicode", true)).thenReturn(false); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1.2")), "2' 1.2"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(12, "0.7")), "12' 0.7"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "1.0")), "10' 1.0"); - assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(14, "-5.0")), "14' -5"); - } - - @Test - public void longGlucoseLine() { - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("125", 2, "1.2")), "125→ Δ1.2 (2')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("97", 11, "5.2")), "97↗ Δ5.2 (11')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("110", 12, "0.7")), "110→ Δ.7 (12')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("65", 10, "7.0")), "65↗ Δ7 (10')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("215", 14, "-5.0")), "215↘ Δ-5 (14')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("8.3", 13, "-5.1")), "8.3↘ Δ-5.1 (13')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("6.8", 15, "10.83")), "6.8↑ Δ10.83 (15')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("13.2", 10, "-11.78")), "13.2↓ Δ-11.78 (10')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("3.9", 3, "2.549")), "3.9→ Δ2.549 (3')"); - assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("11.1", 1, "-15.563")), "11.1↓ Δ-15.563 (1')"); - } - - @Test - public void longDetailsLineTest() { - when(sp.getBoolean("complication_unicode", true)).thenReturn(true); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0g", "0U", "3.5U/h")), "0g ⁞ 0U ⁞ ⎍ 3.5U/h"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("50g", "7.56U", "0%")), "50g ⁞ 7.56U ⁞ ⎍ 0%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("12g", "3.23U", "120%")), "12g ⁞ 3.23U ⁞ 120%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("2(40)g", "-1.5U", "0.55U/h")), "2(40)g ⁞ -2U ⁞ 0.55U/h"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0(24)g", "0.05U", "160%")), "0(24)g ⁞ 0.05U ⁞ 160%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("47g", "13.87U", "220%")), "47g ⁞ 13.87U ⁞ 220%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("13(5)g", "5.90U", "300%")), "13(5)g ⁞ 5.90U ⁞ 300%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("11(50)g", "0U", "70%")), "11(50)g ⁞ 0U ⁞ 70%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("7g", "0.54U", "30%")), "7g ⁞ 0.54U ⁞ ⎍ 30%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), "19g ⁞ 36U ⁞ 12.9U/h"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("100(1)g", "12.345U", "6.98647U/h")), "100g 12U 6.98647U/h"); - - when(sp.getBoolean("complication_unicode", true)).thenReturn(false); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0g", "0U", "3.5U/h")), "0g | 0U | 3.5U/h"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("50g", "7.56U", "0%")), "50g | 7.56U | 0%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("12g", "3.23U", "120%")), "12g | 3.23U | 120%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("7g", "0.54U", "30%")), "7g | 0.54U | 30%"); - assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), "19g | 36U | 12.9U/h"); - } - - @Test - public void detailedIobTest() { - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-1.29U", "(0,910|-2,20)")), Pair.create("-1.29U", ",91 -2")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("3.50U", "")), Pair.create("3.50U", "")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("12.5U", "(+1,4|-4.78)")), Pair.create("12.5U", "1,4 -5")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("0.67U", "some junks")), Pair.create(".67U", "")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-11.0U", "(broken|data)")), Pair.create("-11U", "-- --")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("5.52U", "(0,5439|wrong)")), Pair.create("5.52U", ",54 --")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-8.1U", "(|-8,1)")), Pair.create("-8.1U", "-- -8")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-8.1U", "(|-8,1)")), Pair.create("-8.1U", "-- -8")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("7.6U", "(malformed)")), Pair.create("7.6U", "")); - assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-4.26U", "(6,97|1,3422|too much)")), Pair.create("-4.26U", "7 1,3")); - } - - @Test - public void detailedCobTest() { - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("0g")), Pair.create("0g", "")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("50g")), Pair.create("50g", "")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("2(40)g")), Pair.create("2g", "40g")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("0(24)g")), Pair.create("0g", "24g")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("13(5)g")), Pair.create("13g", "5g")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("11(50)g")), Pair.create("11g", "50g")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("19(38)g")), Pair.create("19g", "38g")); - assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("100(1)g")), Pair.create("100g", "1g")); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt new file mode 100644 index 0000000000..7ae16e3025 --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/DisplayFormatTest.kt @@ -0,0 +1,168 @@ +package info.nightscout.androidaps.interaction.utils + +import info.nightscout.androidaps.TestBase +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.testing.mockers.RawDataMocker +import org.junit.Assert +import org.junit.Before +import org.junit.Test +import org.mockito.Mockito + +/** + * This test covers DisplayFormat class (directly) + * but also SmallestDoubleString - due to carefully chosen input data to format + */ +class DisplayFormatTest : TestBase() { + + private lateinit var displayFormat: DisplayFormat + private lateinit var rawDataMocker: RawDataMocker + + @Before fun mock() { + rawDataMocker = RawDataMocker(wearUtil) + wearUtilMocker.prepareMock() + displayFormat = DisplayFormat() + displayFormat.wearUtil = wearUtil + displayFormat.sp = sp + Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(true) + } + + @Test fun shortTimeSinceTest() { + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 0)), "0'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 5)), "0'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 0, 55)), "0'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 0)), "1'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 1, 59)), "1'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 2, 0)), "2'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 3, 0)), "3'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 4, 0)), "4'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 10, 0)), "10'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 30, 0)), "30'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 0)), "59'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 0, 59, 59)), "59'") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 0, 0)), "1h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 30, 0)), "1h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 1, 59, 59)), "1h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 2, 0, 0)), "2h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 3, 0, 0)), "3h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 4, 0, 0)), "4h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 5, 0, 0)), "5h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 12, 0, 0)), "12h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 18, 0, 0)), "18h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(0, 23, 59, 59)), "23h") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 0, 0, 0)), "1d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 12, 0, 0)), "1d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(1, 23, 59, 59)), "1d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(2, 0, 0, 0)), "2d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(3, 0, 0, 0)), "3d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(4, 0, 0, 0)), "4d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(5, 0, 0, 0)), "5d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 0, 0, 0)), "6d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(6, 23, 59, 59)), "6d") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(7, 0, 0, 0)), "1w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(8, 0, 0, 0)), "1w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(9, 0, 0, 0)), "1w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(13, 23, 59, 59)), "1w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(14, 0, 0, 0)), "2w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(21, 0, 0, 0)), "3w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(28, 0, 0, 0)), "4w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(31, 0, 0, 0)), "4w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(32, 0, 0, 0)), "4w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(35, 0, 0, 0)), "5w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(100, 0, 0, 0)), "14w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(200, 0, 0, 0)), "28w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(365, 0, 0, 0)), "52w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(366, 0, 0, 0)), "52w") + Assert.assertEquals(displayFormat.shortTimeSince(wearUtilMocker.backInTime(367, 0, 0, 0)), "52w") + } + + @Test fun shortTrendTest() { + val raw = RawDisplayData() + Assert.assertEquals(displayFormat.shortTrend(raw), "-- Δ--") + raw.singleBg.timeStamp = wearUtilMocker.backInTime(0, 0, 2, 0) + Assert.assertEquals(displayFormat.shortTrend(raw), "2' Δ--") + Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(true) + + // shortening + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1.2")), "2' Δ1.2") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(11, "1.2")), "11' 1.2") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(12, "0.7")), "12' Δ.7") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "1.0")), "10' Δ1") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(14, "-5.0")), "14' Δ-5") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(13, "-5.1")), "13' -5") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(15, "0.87")), "15' .87") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "-1.78")), "10' -2") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(3, "2.549")), "3' 2.55") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(1, "-1.563")), "1' -1.6") + + // preserving separator + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1,2")), "2' Δ1,2") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(15, "0,87")), "15' ,87") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(3, "+2,549")), "3' 2,55") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(1, "-1,563")), "1' -1,6") + + // UTF-off mode - without delta symbol + Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(false) + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(2, "1.2")), "2' 1.2") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(12, "0.7")), "12' 0.7") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(10, "1.0")), "10' 1.0") + Assert.assertEquals(displayFormat.shortTrend(rawDataMocker.rawDelta(14, "-5.0")), "14' -5") + } + + @Test fun longGlucoseLine() { + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("125", 2, "1.2")), "125→ Δ1.2 (2')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("97", 11, "5.2")), "97↗ Δ5.2 (11')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("110", 12, "0.7")), "110→ Δ.7 (12')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("65", 10, "7.0")), "65↗ Δ7 (10')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("215", 14, "-5.0")), "215↘ Δ-5 (14')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("8.3", 13, "-5.1")), "8.3↘ Δ-5.1 (13')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("6.8", 15, "10.83")), "6.8↑ Δ10.83 (15')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("13.2", 10, "-11.78")), "13.2↓ Δ-11.78 (10')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("3.9", 3, "2.549")), "3.9→ Δ2.549 (3')") + Assert.assertEquals(displayFormat.longGlucoseLine(rawDataMocker.rawSgv("11.1", 1, "-15.563")), "11.1↓ Δ-15.563 (1')") + } + + @Test fun longDetailsLineTest() { + Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(true) + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0g", "0U", "3.5U/h")), "0g ⁞ 0U ⁞ ⎍ 3.5U/h") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("50g", "7.56U", "0%")), "50g ⁞ 7.56U ⁞ ⎍ 0%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("12g", "3.23U", "120%")), "12g ⁞ 3.23U ⁞ 120%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("2(40)g", "-1.5U", "0.55U/h")), "2(40)g ⁞ -2U ⁞ 0.55U/h") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0(24)g", "0.05U", "160%")), "0(24)g ⁞ 0.05U ⁞ 160%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("47g", "13.87U", "220%")), "47g ⁞ 13.87U ⁞ 220%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("13(5)g", "5.90U", "300%")), "13(5)g ⁞ 5.90U ⁞ 300%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("11(50)g", "0U", "70%")), "11(50)g ⁞ 0U ⁞ 70%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("7g", "0.54U", "30%")), "7g ⁞ 0.54U ⁞ ⎍ 30%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), "19g ⁞ 36U ⁞ 12.9U/h") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("100(1)g", "12.345U", "6.98647U/h")), "100g 12U 6.98647U/h") + Mockito.`when`(sp.getBoolean("complication_unicode", true)).thenReturn(false) + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("0g", "0U", "3.5U/h")), "0g | 0U | 3.5U/h") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("50g", "7.56U", "0%")), "50g | 7.56U | 0%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("12g", "3.23U", "120%")), "12g | 3.23U | 120%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("7g", "0.54U", "30%")), "7g | 0.54U | 30%") + Assert.assertEquals(displayFormat.longDetailsLine(rawDataMocker.rawCobIobBr("19(38)g", "35.545U", "12.9U/h")), "19g | 36U | 12.9U/h") + } + + @Test fun detailedIobTest() { + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-1.29U", "(0,910|-2,20)")), Pair.create("-1.29U", ",91 -2")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("3.50U", "")), Pair.create("3.50U", "")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("12.5U", "(+1,4|-4.78)")), Pair.create("12.5U", "1,4 -5")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("0.67U", "some junks")), Pair.create(".67U", "")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-11.0U", "(broken|data)")), Pair.create("-11U", "-- --")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("5.52U", "(0,5439|wrong)")), Pair.create("5.52U", ",54 --")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-8.1U", "(|-8,1)")), Pair.create("-8.1U", "-- -8")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-8.1U", "(|-8,1)")), Pair.create("-8.1U", "-- -8")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("7.6U", "(malformed)")), Pair.create("7.6U", "")) + Assert.assertEquals(displayFormat.detailedIob(rawDataMocker.rawIob("-4.26U", "(6,97|1,3422|too much)")), Pair.create("-4.26U", "7 1,3")) + } + + @Test fun detailedCobTest() { + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("0g")), Pair.create("0g", "")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("50g")), Pair.create("50g", "")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("2(40)g")), Pair.create("2g", "40g")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("0(24)g")), Pair.create("0g", "24g")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("13(5)g")), Pair.create("13g", "5g")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("11(50)g")), Pair.create("11g", "50g")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("19(38)g")), Pair.create("19g", "38g")) + Assert.assertEquals(displayFormat.detailedCob(rawDataMocker.rawCob("100(1)g")), Pair.create("100g", "1g")) + } +} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java deleted file mode 100644 index 47b6b44711..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.java +++ /dev/null @@ -1,64 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - -import java.util.HashSet; -import java.util.Set; - -@SuppressWarnings({"rawtypes", "SpellCheckingInspection"}) -public class PairTest { - - @Test - public void pairEqualsTest() { - // GIVEN - Pair left = Pair.create("aa", "bbb"); - Pair right = Pair.create("ccc", "dd"); - Pair another = Pair.create("aa", "bbb"); - Pair samePos1 = Pair.create("aa", "d"); - Pair samePos2 = Pair.create("zzzzz", "bbb"); - Pair no1 = Pair.create(12, 345L); - Pair no2 = Pair.create(-943, 42); - Pair no3 = Pair.create(12L, 345); - Pair no4 = Pair.create(12, 345L); - - // THEN - assertNotEquals(left, right); - assertEquals(left, another); - assertNotEquals(left, samePos1); - assertNotEquals(left, samePos2); - assertNotEquals(no1, no2); - assertNotEquals(no1, no3); - assertEquals(no1, no4); - - assertNotEquals("aa bbb", left.toString()); - } - - @Test - public void pairHashTest() { - // GIVEN - Pair inserted = Pair.create("aa", "bbb"); - Set set = new HashSet<>(); - - // THEN - //noinspection ConstantConditions - assertFalse(set.contains(inserted)); - set.add(inserted); - assertTrue(set.contains(inserted)); - } - - @Test - public void toStringTest() { - // GIVEN - Pair pair = Pair.create("the-first", "2nd"); - - assertTrue(pair.toString().contains("the-first")); - assertTrue(pair.toString().contains("2nd")); - } - - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt new file mode 100644 index 0000000000..1f78b4a66d --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PairTest.kt @@ -0,0 +1,48 @@ +package info.nightscout.androidaps.interaction.utils + +import org.junit.Assert +import org.junit.Test + +class PairTest { + + @Test fun pairEqualsTest() { + // GIVEN + val left: Pair<*, *> = Pair.create("aa", "bbb") + val right: Pair<*, *> = Pair.create("ccc", "dd") + val another: Pair<*, *> = Pair.create("aa", "bbb") + val samePos1: Pair<*, *> = Pair.create("aa", "d") + val samePos2: Pair<*, *> = Pair.create("zzzzz", "bbb") + val no1: Pair<*, *> = Pair.create(12, 345L) + val no2: Pair<*, *> = Pair.create(-943, 42) + val no3: Pair<*, *> = Pair.create(12L, 345) + val no4: Pair<*, *> = Pair.create(12, 345L) + + // THEN + Assert.assertNotEquals(left, right) + Assert.assertEquals(left, another) + Assert.assertNotEquals(left, samePos1) + Assert.assertNotEquals(left, samePos2) + Assert.assertNotEquals(no1, no2) + Assert.assertNotEquals(no1, no3) + Assert.assertEquals(no1, no4) + Assert.assertNotEquals("aa bbb", left.toString()) + } + + @Test fun pairHashTest() { + // GIVEN + val inserted: Pair<*, *> = Pair.create("aa", "bbb") + val set: MutableSet> = HashSet() + + // THEN + Assert.assertFalse(set.contains(inserted)) + set.add(inserted) + Assert.assertTrue(set.contains(inserted)) + } + + @Test fun toStringTest() { + // GIVEN + val pair: Pair<*, *> = Pair.create("the-first", "2nd") + Assert.assertTrue(pair.toString().contains("the-first")) + Assert.assertTrue(pair.toString().contains("2nd")) + } +} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java deleted file mode 100644 index b879ff440e..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/PersistenceTest.java +++ /dev/null @@ -1,153 +0,0 @@ -package info.nightscout.androidaps.interaction.utils; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static info.nightscout.androidaps.testing.mockers.WearUtilMocker.REF_NOW; - -import com.google.android.gms.wearable.DataMap; - -import org.junit.Test; - -import java.util.Set; - -import info.nightscout.androidaps.TestBase; - -@SuppressWarnings("SpellCheckingInspection") -public class PersistenceTest extends TestBase { - - @Test - public void putStringTest() { - // WHEN - final String emptyGot = persistence.getString("test-key", "default-value"); - persistence.putString("test-key", "newValue"); - final String updatedGot = persistence.getString("test-key", "another-default-value"); - - // THEN - assertEquals(emptyGot, "default-value"); - assertEquals(updatedGot, "newValue"); - } - - @Test - public void putBooleanTest() { - // WHEN - final boolean emptyGot = persistence.getBoolean("test-key", false); - persistence.putBoolean("test-key", true); - final boolean updatedGot = persistence.getBoolean("test-key", false); - - // THEN - assertFalse(emptyGot); - assertTrue(updatedGot); - } - - @Test - public void whenDataUpdatedTest() { - // GIVEN - DataMap map = new DataMap(); - - // WHEN - final long whenNotUpdated = persistence.whenDataUpdated(); - - persistence.storeDataMap("data-map", map); - final long whenUpdatedFirst = persistence.whenDataUpdated(); - - getWearUtilMocker().progressClock(60000); - persistence.storeDataMap("data-map", map); - final long whenUpdatedNext = persistence.whenDataUpdated(); - - // THEN - assertEquals(whenNotUpdated, 0L); - assertEquals(whenUpdatedFirst, REF_NOW); - assertEquals(whenUpdatedNext, REF_NOW + 60000); - } - - @Test - public void getDataMapTest() { - // GIVEN - DataMap map = new DataMap(); - map.putByteArray("test-key", new byte[]{9, 42, 127, -5}); - - // WHEN - DataMap notExisting = persistence.getDataMap("not-there"); - persistence.storeDataMap("data-map", map); - DataMap restoredMap = persistence.getDataMap("data-map"); - assert restoredMap != null; - byte[] restoredMapContents = restoredMap.getByteArray("test-key"); - - // THEN - assertNull(notExisting); - assertNotNull(restoredMap); - assertTrue(restoredMap.containsKey("test-key")); - - assertEquals(restoredMapContents.length, 4); - assertEquals(restoredMapContents[0], (byte) 9); - assertEquals(restoredMapContents[1], (byte) 42); - assertEquals(restoredMapContents[2], (byte) 127); - assertEquals(restoredMapContents[3], (byte) -5); - } - - @Test - public void brokenDataMapTest() { - // WHEN - persistence.putString("data-map", "ZmFrZSBkYXRh"); - DataMap restoredMap = persistence.getDataMap("data-map"); - - // THEN - assertNull(restoredMap); - } - - @Test - public void setsTest() { - // WHEN - Set emptySet = persistence.getSetOf("some fake id"); - - persistence.addToSet("test-set", "element1"); - persistence.addToSet("test-set", "second-elem"); - persistence.addToSet("test-set", "3rd"); - persistence.addToSet("test-set", "czwarty"); - persistence.addToSet("test-set", "V"); - persistence.addToSet("test-set", "6"); - - Set initialSet = persistence.getSetOf("test-set"); - Set sameInitialSet = persistence.getSetOf("test-set"); - - persistence.addToSet("test-set", "second-elem"); - persistence.addToSet("test-set", "new-one"); - - Set extendedSet = persistence.getSetOf("test-set"); - - persistence.removeFromSet("test-set", "czwarty"); - persistence.removeFromSet("test-set", "6"); - persistence.removeFromSet("test-set", "3rd"); - - Set reducedSet = persistence.getSetOf("test-set"); - - // THEN - assertEquals(emptySet.size(), 0); - - assertEquals(initialSet.size(), 6); - assertTrue(initialSet.contains("element1")); - assertTrue(initialSet.contains("second-elem")); - assertTrue(initialSet.contains("3rd")); - assertTrue(initialSet.contains("czwarty")); - assertTrue(initialSet.contains("V")); - assertTrue(initialSet.contains("6")); - - assertEquals(initialSet, sameInitialSet); - - assertEquals(extendedSet.size(), 7); - assertTrue(extendedSet.contains("new-one")); - - assertEquals(reducedSet.size(), 4); - assertTrue(reducedSet.contains("element1")); - assertTrue(reducedSet.contains("second-elem")); - assertFalse(reducedSet.contains("3rd")); - assertFalse(reducedSet.contains("czwarty")); - assertTrue(reducedSet.contains("V")); - assertFalse(reducedSet.contains("6")); - assertTrue(reducedSet.contains("new-one")); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt index 3f853db233..a832b39139 100644 --- a/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt +++ b/wear/src/test/java/info/nightscout/androidaps/interaction/utils/WearUtilTest.kt @@ -4,15 +4,14 @@ import com.google.android.gms.wearable.DataMap import info.nightscout.androidaps.TestBase import info.nightscout.androidaps.testing.mockers.WearUtilMocker import info.nightscout.androidaps.testing.mocks.BundleMock -import org.hamcrest.CoreMatchers import org.junit.Assert import org.junit.Test -import java.util.* /** * Created by dlvoy on 22.11.2019. */ -@Suppress("SpellCheckingInspection") class WearUtilTest : TestBase() { +@Suppress("SpellCheckingInspection") +class WearUtilTest : TestBase() { @Test fun timestampAndTimeDiffsTest() { @@ -123,26 +122,4 @@ import java.util.* Assert.assertFalse(callTooSoon) Assert.assertTrue(callAfterRateLimit) } - - /** - * It tests if mock for bundleToDataMap is sane, - * because original impl. of bundleToDataMap - * uses DataMap.fromBundle which need Android SDK runtime - */ - @Test - fun bundleToDataMapTest() { - // GIVEN - val refMap = DataMap() - refMap.putString("ala", "ma kota") - refMap.putInt("why", 42) - refMap.putFloatArray("list", floatArrayOf(0.45f, 3.2f, 6.8f)) - - // WHEN - wearUtilMocker.prepareMockNoReal() - val bundle = BundleMock.mock(refMap) - val gotMap = wearUtil.bundleToDataMap(bundle) - - // THEN - Assert.assertEquals(gotMap, refMap) - } } \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java deleted file mode 100644 index a6bdf446f9..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.java +++ /dev/null @@ -1,73 +0,0 @@ -package info.nightscout.androidaps.testing.mockers; - -import info.nightscout.androidaps.data.RawDisplayData; -import info.nightscout.androidaps.interaction.utils.WearUtil; -import info.nightscout.shared.SafeParse; - -@SuppressWarnings("PointlessArithmeticExpression") -public class RawDataMocker { - - private final WearUtil wearUtil; - private final WearUtilMocker wearUtilMocker; - - public RawDataMocker(WearUtil wearUtil) { - this.wearUtil = wearUtil; - wearUtilMocker = new WearUtilMocker(wearUtil); - } - - public RawDisplayData rawSgv(String sgv, int m, String deltaString) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.datetime = wearUtilMocker.backInTime(0, 0, m, 0); - raw.sDelta = deltaString; - raw.sSgv = sgv; - - double delta = SafeParse.stringToDouble(deltaString); - - if (delta <= (-3.5 * 5)) { - raw.sDirection = "\u21ca"; - } else if (delta <= (-2 * 5)) { - raw.sDirection = "\u2193"; - } else if (delta <= (-1 * 5)) { - raw.sDirection = "\u2198"; - } else if (delta <= (1 * 5)) { - raw.sDirection = "\u2192"; - } else if (delta <= (2 * 5)) { - raw.sDirection = "\u2197"; - } else if (delta <= (3.5 * 5)) { - raw.sDirection = "\u2191"; - } else { - raw.sDirection = "\u21c8"; - } - - return raw; - } - - public RawDisplayData rawDelta(int m, String delta) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.datetime = wearUtilMocker.backInTime(0, 0, m, 0); - raw.sDelta = delta; - return raw; - } - - public RawDisplayData rawCobIobBr(String cob, String iob, String br) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.sCOB2 = cob; - raw.sIOB1 = iob; - raw.sBasalRate = br; - return raw; - } - - public RawDisplayData rawIob(String iob, String iob2) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.sIOB1 = iob; - raw.sIOB2 = iob2; - return raw; - } - - public RawDisplayData rawCob(String cob) { - RawDisplayData raw = new RawDisplayData(wearUtil); - raw.sCOB2 = cob; - return raw; - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt new file mode 100644 index 0000000000..035552d468 --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/RawDataMocker.kt @@ -0,0 +1,118 @@ +package info.nightscout.androidaps.testing.mockers + +import info.nightscout.androidaps.data.RawDisplayData +import info.nightscout.androidaps.interaction.utils.WearUtil +import info.nightscout.shared.SafeParse.stringToDouble +import info.nightscout.shared.weardata.EventData +import info.nightscout.shared.weardata.EventData.SingleBg + +class RawDataMocker(wearUtil: WearUtil) { + + private val wearUtilMocker: WearUtilMocker = WearUtilMocker(wearUtil) + + fun rawSgv(sgv: String?, m: Int, deltaString: String): RawDisplayData { + val raw = RawDisplayData() + val delta = stringToDouble(deltaString) + val d: String = + when { + delta <= -3.5 * 5 -> "\u21ca" + delta <= -2 * 5 -> "\u2193" + delta <= -1 * 5 -> "\u2198" + delta <= 1 * 5 -> "\u2192" + delta <= 2 * 5 -> "\u2197" + delta <= 3.5 * 5 -> "\u2191" + else -> "\u21c8" + } + + raw.singleBg = SingleBg( + wearUtilMocker.backInTime(0, 0, m, 0), + sgv!!, + "", + d, + deltaString, + "", + 0, + 0.0, + 0.0, + 0.0, + 0 + ) + return raw + } + + fun rawDelta(m: Int, delta: String): RawDisplayData { + val raw = RawDisplayData() + raw.singleBg = SingleBg( + wearUtilMocker.backInTime(0, 0, m, 0), + "", + "", + "", + delta, + "", + 0, + 0.0, + 0.0, + 0.0, + 0 + ) + return raw + } + + fun rawCobIobBr(cob: String, iob: String, br: String): RawDisplayData { + val raw = RawDisplayData() + raw.status = EventData.Status( + "", + iob, + "", + true, + cob, + br, + "", + "", + 0L, + "", + true, + 0 + ) + return raw + } + + fun rawIob(iob: String, iob2: String): RawDisplayData { + val raw = RawDisplayData() + raw.status = EventData.Status( + "", + iob, + iob2, + true, + "", + "", + "", + "", + 0L, + "", + true, + 0 + ) + return raw + } + + fun rawCob(cob: String?): RawDisplayData { + val raw = RawDisplayData() + raw.status = EventData.Status( + "", + "", + "", + true, + cob!!, + "", + "", + "", + 0L, + "", + true, + 0 + ) + return raw + } + +} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java deleted file mode 100644 index 44dd10f989..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.java +++ /dev/null @@ -1,102 +0,0 @@ -package info.nightscout.androidaps.testing.mockers; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; - -import android.os.Bundle; - -import com.google.android.gms.wearable.Asset; -import com.google.android.gms.wearable.DataMap; - -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; - -import java.util.ArrayList; - -import info.nightscout.androidaps.interaction.utils.Constants; -import info.nightscout.androidaps.interaction.utils.WearUtil; - -@SuppressWarnings({"rawtypes", "unchecked"}) -public class WearUtilMocker { - - private final WearUtil wearUtil; - - public WearUtilMocker(WearUtil wearUtil) { - this.wearUtil = wearUtil; - } - - public static final long REF_NOW = 1572610530000L; - private long clockMsDiff = 0L; - - public void prepareMock() { - resetClock(); - - // because we cleverly used timestamp() by implementation, we can mock it - // and control the time in tests - when(wearUtil.timestamp()).thenReturn(REF_NOW + clockMsDiff); - } - - public void prepareMockNoReal() { - resetClock(); - - Mockito.doAnswer(invocation -> REF_NOW + clockMsDiff).when(wearUtil).timestamp(); - Mockito.doReturn(null).when(wearUtil).getWakeLock(anyString(), anyInt()); - Mockito.doAnswer(bundleToDataMapMock).when(wearUtil).bundleToDataMap(any()); - } - - public void resetClock() { - clockMsDiff = 0L; - } - - public void progressClock(long byMilliseconds) { - clockMsDiff = clockMsDiff + byMilliseconds; - } - - @SuppressWarnings("unused") - public void setClock(long atMillisecondsSinceEpoch) { - clockMsDiff = atMillisecondsSinceEpoch - REF_NOW; - } - - public long backInTime(int d, int h, int m, int s) { - return REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s); - } - - private final Answer bundleToDataMapMock = invocation -> { - DataMap map = new DataMap(); - Bundle bundle = invocation.getArgument(0); - for (String key : bundle.keySet()) { - Object v = bundle.get(key); - if (v instanceof Asset) map.putAsset(key, (Asset) v); - if (v instanceof Boolean) map.putBoolean(key, (Boolean) v); - if (v instanceof Byte) map.putByte(key, (Byte) v); - if (v instanceof byte[]) map.putByteArray(key, (byte[]) v); - if (v instanceof DataMap) map.putDataMap(key, (DataMap) v); - if (v instanceof Double) map.putDouble(key, (Double) v); - if (v instanceof Float) map.putFloat(key, (Float) v); - if (v instanceof float[]) map.putFloatArray(key, (float[]) v); - if (v instanceof Integer) map.putInt(key, (Integer) v); - if (v instanceof Long) map.putLong(key, (Long) v); - if (v instanceof long[]) map.putLongArray(key, (long[]) v); - if (v instanceof String) map.putString(key, (String) v); - if (v instanceof String[]) map.putStringArray(key, (String[]) v); - - if (v instanceof ArrayList) { - if (!((ArrayList) v).isEmpty()) { - if (((ArrayList) v).get(0) instanceof Integer) { - map.putIntegerArrayList(key, (ArrayList) v); - } - if (((ArrayList) v).get(0) instanceof String) { - map.putStringArrayList(key, (ArrayList) v); - } - if (((ArrayList) v).get(0) instanceof DataMap) { - map.putDataMapArrayList(key, (ArrayList) v); - } - } - } - } - - return map; - }; -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt new file mode 100644 index 0000000000..5453200be2 --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mockers/WearUtilMocker.kt @@ -0,0 +1,86 @@ +package info.nightscout.androidaps.testing.mockers + +import android.os.Bundle +import com.google.android.gms.wearable.Asset +import com.google.android.gms.wearable.DataMap +import info.nightscout.androidaps.interaction.utils.Constants +import info.nightscout.androidaps.interaction.utils.WearUtil +import org.mockito.ArgumentMatchers +import org.mockito.Mockito +import org.mockito.invocation.InvocationOnMock +import org.mockito.stubbing.Answer + +class WearUtilMocker(private val wearUtil: WearUtil) { + + private var clockMsDiff = 0L + fun prepareMock() { + resetClock() + + // because we cleverly used timestamp() by implementation, we can mock it + // and control the time in tests + Mockito.`when`(wearUtil.timestamp()).thenReturn(REF_NOW + clockMsDiff) + } + + fun prepareMockNoReal() { + resetClock() + Mockito.doAnswer { invocation: InvocationOnMock? -> REF_NOW + clockMsDiff }.`when`(wearUtil).timestamp() + Mockito.doReturn(null).`when`(wearUtil).getWakeLock(ArgumentMatchers.anyString(), ArgumentMatchers.anyInt()) + } + + fun resetClock() { + clockMsDiff = 0L + } + + fun progressClock(byMilliseconds: Long) { + clockMsDiff += byMilliseconds + } + + fun setClock(atMillisecondsSinceEpoch: Long) { + clockMsDiff = atMillisecondsSinceEpoch - REF_NOW + } + + fun backInTime(d: Int, h: Int, m: Int, s: Int): Long { + return REF_NOW - (Constants.DAY_IN_MS * d + Constants.HOUR_IN_MS * h + Constants.MINUTE_IN_MS * m + Constants.SECOND_IN_MS * s) + } + + @Suppress("UNCHECKED_CAST") + private val bundleToDataMapMock: Answer<*> = Answer { invocation: InvocationOnMock -> + val map = DataMap() + val bundle = invocation.getArgument(0) + for (key in bundle.keySet()) { + val v = bundle[key] + if (v is Asset) map.putAsset(key, v) + if (v is Boolean) map.putBoolean(key, v) + if (v is Byte) map.putByte(key, (v as Byte?)!!) + if (v is ByteArray) map.putByteArray(key, v) + if (v is DataMap) map.putDataMap(key, v) + if (v is Double) map.putDouble(key, v) + if (v is Float) map.putFloat(key, (v as Float)) + if (v is FloatArray) map.putFloatArray(key, v) + if (v is Int) map.putInt(key, v) + if (v is Long) map.putLong(key, v) + if (v is LongArray) map.putLongArray(key, v) + if (v is String) map.putString(key, v) + if (v is Array<*>) map.putStringArray(key, v as Array) + if (v is ArrayList<*>) { + if (v.isNotEmpty()) { + if (v[0] is Int) { + map.putIntegerArrayList(key, v as ArrayList) + } + if (v[0] is String) { + map.putStringArrayList(key, v as ArrayList) + } + if (v[0] is DataMap) { + map.putDataMapArrayList(key, v as ArrayList) + } + } + } + } + map + } + + companion object { + + const val REF_NOW = 1572610530000L + } +} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/IntentMock.java b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/IntentMock.java deleted file mode 100644 index 5320ae56e8..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/IntentMock.java +++ /dev/null @@ -1,40 +0,0 @@ -package info.nightscout.androidaps.testing.mocks; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.when; - -import android.content.Intent; -import android.os.Bundle; - -import org.mockito.Mockito; -import org.mockito.stubbing.Answer; - -import java.util.HashMap; - -@SuppressWarnings({"SuspiciousMethodCalls", "rawtypes"}) -public final class IntentMock { - - public static Intent mock() { - return mock(new HashMap<>()); - } - - public static Intent mock(final HashMap map) { - - Answer put = invocation -> { - map.put((String) invocation.getArguments()[0], invocation.getArguments()[1]); - return null; - }; - Answer get = invocation -> map.get(invocation.getArguments()[0]); - - Intent intent = Mockito.mock(Intent.class); - - when(intent.putExtra(anyString(), any(Bundle.class))).thenAnswer(put); - when(intent.getBundleExtra(anyString())).thenAnswer(get); - - doAnswer(invocation -> map.containsKey(invocation.getArguments()[0])).when(intent).hasExtra(anyString()); - - return intent; - } -} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.java b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.java deleted file mode 100644 index adf632e538..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.java +++ /dev/null @@ -1,159 +0,0 @@ -package info.nightscout.androidaps.testing.mocks; - -import android.content.SharedPreferences; - -import androidx.annotation.Nullable; - -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -@SuppressWarnings({"ConstantConditions", "unchecked"}) -public class SharedPreferencesMock implements SharedPreferences { - - private final EditorInternals editor = new EditorInternals(); - - static class EditorInternals implements Editor { - - Map innerMap = new HashMap<>(); - - @Override - public Editor putString(String k, @Nullable String v) { - innerMap.put(k, v); - return this; - } - - @Override - public Editor putStringSet(String k, @Nullable Set set) { - innerMap.put(k, set); - return this; - } - - @Override - public Editor putInt(String k, int i) { - innerMap.put(k, i); - return this; - } - - @Override - public Editor putLong(String k, long l) { - innerMap.put(k, l); - return this; - } - - @Override - public Editor putFloat(String k, float v) { - innerMap.put(k, v); - return this; - } - - @Override - public Editor putBoolean(String k, boolean b) { - innerMap.put(k, b); - return this; - } - - @Override - public Editor remove(String k) { - innerMap.remove(k); - return this; - } - - @Override - public Editor clear() { - innerMap.clear(); - return this; - } - - @Override - public boolean commit() { - return true; - } - - @Override - public void apply() { - - } - } - - @Override - public Map getAll() { - return editor.innerMap; - } - - @Nullable - @Override - public String getString(String k, @Nullable String s) { - if (editor.innerMap.containsKey(k)) { - return (String) editor.innerMap.get(k); - } else { - return s; - } - } - - @Nullable - @Override - public Set getStringSet(String k, @Nullable Set set) { - if (editor.innerMap.containsKey(k)) { - return (Set) editor.innerMap.get(k); - } else { - return set; - } - } - - @Override - public int getInt(String k, int i) { - if (editor.innerMap.containsKey(k)) { - return (Integer) editor.innerMap.get(k); - } else { - return i; - } - } - - @Override - public long getLong(String k, long l) { - if (editor.innerMap.containsKey(k)) { - return (Long) editor.innerMap.get(k); - } else { - return l; - } - } - - @Override - public float getFloat(String k, float v) { - if (editor.innerMap.containsKey(k)) { - return (Float) editor.innerMap.get(k); - } else { - return v; - } - } - - @Override - public boolean getBoolean(String k, boolean b) { - if (editor.innerMap.containsKey(k)) { - return (Boolean) editor.innerMap.get(k); - } else { - return b; - } - } - - @Override - public boolean contains(String k) { - return editor.innerMap.containsKey(k); - } - - @Override - public Editor edit() { - return editor; - } - - @Override - public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) { - - } - - @Override - public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) { - - } -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt new file mode 100644 index 0000000000..8ff8129962 --- /dev/null +++ b/wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt @@ -0,0 +1,123 @@ +package info.nightscout.androidaps.testing.mocks + +import android.content.SharedPreferences +import android.content.SharedPreferences.OnSharedPreferenceChangeListener + +class SharedPreferencesMock : SharedPreferences { + + private val editor = EditorInternals() + + internal class EditorInternals : SharedPreferences.Editor { + + var innerMap: MutableMap = HashMap() + override fun putString(k: String, v: String?): SharedPreferences.Editor { + innerMap[k] = v + return this + } + + override fun putStringSet(k: String, set: Set?): SharedPreferences.Editor { + innerMap[k] = set + return this + } + + override fun putInt(k: String, i: Int): SharedPreferences.Editor { + innerMap[k] = i + return this + } + + override fun putLong(k: String, l: Long): SharedPreferences.Editor { + innerMap[k] = l + return this + } + + override fun putFloat(k: String, v: Float): SharedPreferences.Editor { + innerMap[k] = v + return this + } + + override fun putBoolean(k: String, b: Boolean): SharedPreferences.Editor { + innerMap[k] = b + return this + } + + override fun remove(k: String): SharedPreferences.Editor { + innerMap.remove(k) + return this + } + + override fun clear(): SharedPreferences.Editor { + innerMap.clear() + return this + } + + override fun commit(): Boolean { + return true + } + + override fun apply() {} + } + + override fun getAll(): Map { + return editor.innerMap + } + + override fun getString(k: String, s: String?): String? { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as String? + } else { + s + } + } + + @Suppress("UNCHECKED_CAST") + override fun getStringSet(k: String, set: Set?): Set? { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as Set? + } else { + set + } + } + + override fun getInt(k: String, i: Int): Int { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as Int + } else { + i + } + } + + override fun getLong(k: String, l: Long): Long { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as Long + } else { + l + } + } + + override fun getFloat(k: String, v: Float): Float { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as Float + } else { + v + } + } + + override fun getBoolean(k: String, b: Boolean): Boolean { + return if (editor.innerMap.containsKey(k)) { + editor.innerMap[k] as Boolean + } else { + b + } + } + + override fun contains(k: String): Boolean { + return editor.innerMap.containsKey(k) + } + + override fun edit(): SharedPreferences.Editor { + return editor + } + + override fun registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {} + override fun unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {} +} \ No newline at end of file diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BasalWatchDataExt.java b/wear/src/test/java/info/nightscout/androidaps/testing/utils/BasalWatchDataExt.java deleted file mode 100644 index c0fffbff71..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BasalWatchDataExt.java +++ /dev/null @@ -1,59 +0,0 @@ -package info.nightscout.androidaps.testing.utils; - -import static info.nightscout.androidaps.testing.utils.ExtUtil.assertClassHaveSameFields; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.Objects; - -import info.nightscout.androidaps.data.BasalWatchData; - -public class BasalWatchDataExt extends BasalWatchData { - - private BasalWatchDataExt() { - super(); - } - - public BasalWatchDataExt(BasalWatchData ref) { - super(); - - // since we do not want modify BasalWatchData - we use this wrapper class - // but we make sure it has same fields - assertClassHaveSameFields(BasalWatchData.class, "startTime,endTime,amount"); - - this.startTime = ref.startTime; - this.endTime = ref.endTime; - this.amount = ref.amount; - } - - public static BasalWatchDataExt build(long startTime, long endTime, double amount) { - BasalWatchDataExt bwd = new BasalWatchDataExt(); - bwd.startTime = startTime; - bwd.endTime = endTime; - bwd.amount = amount; - return bwd; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof BasalWatchData) { - return (this.startTime == ((BasalWatchData) obj).startTime) - && (this.endTime == ((BasalWatchData) obj).endTime) - && (this.amount == ((BasalWatchData) obj).amount); - } else { - return false; - } - } - - @NonNull @Override - public String toString() { - return startTime + ", " + endTime + ", " + amount; - } - - @Override - public int hashCode() { - return Objects.hash(startTime, endTime, amount); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BgWatchDataExt.java b/wear/src/test/java/info/nightscout/androidaps/testing/utils/BgWatchDataExt.java deleted file mode 100644 index 5b70ef1ace..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BgWatchDataExt.java +++ /dev/null @@ -1,68 +0,0 @@ -package info.nightscout.androidaps.testing.utils; - -import static info.nightscout.androidaps.testing.utils.ExtUtil.assertClassHaveSameFields; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.Objects; - -import info.nightscout.androidaps.data.BgWatchData; - -@SuppressWarnings("unused") -public class BgWatchDataExt extends BgWatchData { - - private BgWatchDataExt() { - super(); - } - - public BgWatchDataExt(double aSgv, double aHigh, double aLow, long aTimestamp, int aColor) { - super(aSgv, aHigh, aLow, aTimestamp, aColor); - } - - public BgWatchDataExt(BgWatchData ref) { - super(); - - // since we do not want modify BgWatchDataExt - we use this wrapper class - // but we make sure it has same fields - assertClassHaveSameFields(BgWatchData.class, "sgv,high,low,timestamp,color"); - - this.sgv = ref.sgv; - this.high = ref.high; - this.low = ref.low; - this.timestamp = ref.timestamp; - this.color = ref.color; - } - - public static BgWatchDataExt build(double sgv, long timestamp, int color) { - BgWatchDataExt twd = new BgWatchDataExt(); - twd.sgv = sgv; - twd.timestamp = timestamp; - twd.color = color; - return twd; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof BgWatchData) { - return (this.sgv == ((BgWatchData) obj).sgv) - && (this.high == ((BgWatchData) obj).high) - && (this.low == ((BgWatchData) obj).low) - && (this.timestamp == ((BgWatchData) obj).timestamp) - && (this.color == ((BgWatchData) obj).color); - } else { - return false; - } - } - - @Override @NonNull - public String toString() { - return sgv + ", " + high + ", " + low + ", " + timestamp + ", " + color; - } - - @Override - public int hashCode() { - return Objects.hash(sgv, high, low, timestamp, color); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BolusWatchDataExt.java b/wear/src/test/java/info/nightscout/androidaps/testing/utils/BolusWatchDataExt.java deleted file mode 100644 index 73f4c367c6..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/utils/BolusWatchDataExt.java +++ /dev/null @@ -1,65 +0,0 @@ -package info.nightscout.androidaps.testing.utils; - -import static info.nightscout.androidaps.testing.utils.ExtUtil.assertClassHaveSameFields; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.Objects; - -import info.nightscout.androidaps.data.BolusWatchData; - -public class BolusWatchDataExt extends BolusWatchData { - - private BolusWatchDataExt() { - super(); - } - - public BolusWatchDataExt(BolusWatchData ref) { - super(); - - // since we do not want modify BolusWatchData - we use this wrapper class - // but we make sure it has same fields - assertClassHaveSameFields(BolusWatchData.class, "date,bolus,carbs,isSMB,isValid"); - - this.date = ref.date; - this.bolus = ref.bolus; - this.carbs = ref.carbs; - this.isSMB = ref.isSMB; - this.isValid = ref.isValid; - } - - public static BolusWatchDataExt build(long date, double bolus, double carbs, boolean isSMB, boolean isValid) { - BolusWatchDataExt bwd = new BolusWatchDataExt(); - bwd.date = date; - bwd.bolus = bolus; - bwd.carbs = carbs; - bwd.isSMB = isSMB; - bwd.isValid = isValid; - return bwd; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof BolusWatchData) { - return (this.date == ((BolusWatchData) obj).date) - && (this.bolus == ((BolusWatchData) obj).bolus) - && (this.carbs == ((BolusWatchData) obj).carbs) - && (this.isSMB == ((BolusWatchData) obj).isSMB) - && (this.isValid == ((BolusWatchData) obj).isValid); - } else { - return false; - } - } - - @NonNull @Override - public String toString() { - return date + ", " + bolus + ", " + carbs + ", " + isSMB + ", " + isValid; - } - - @Override - public int hashCode() { - return Objects.hash(date, bolus, carbs, isSMB, isValid); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/utils/ExtUtil.java b/wear/src/test/java/info/nightscout/androidaps/testing/utils/ExtUtil.java deleted file mode 100644 index 9a7014754e..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/utils/ExtUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -package info.nightscout.androidaps.testing.utils; - -import static org.junit.Assert.assertEquals; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; - -class ExtUtil { - - static void assertClassHaveSameFields(Class checkedClass, String commaSeparatedFieldList) { - Set parentFields = new HashSet<>(); - for (Field f : checkedClass.getDeclaredFields()) { - final String fieldName = f.getName(); - // skip runtime-injected fields like $jacocoData - if (fieldName.startsWith("$")) { - continue; - } - parentFields.add(fieldName); - } - - Set knownFields = new HashSet<>(Arrays.asList(commaSeparatedFieldList.split(","))); - assertEquals(parentFields, knownFields); - } - -} diff --git a/wear/src/test/java/info/nightscout/androidaps/testing/utils/TempWatchDataExt.java b/wear/src/test/java/info/nightscout/androidaps/testing/utils/TempWatchDataExt.java deleted file mode 100644 index 6a13266365..0000000000 --- a/wear/src/test/java/info/nightscout/androidaps/testing/utils/TempWatchDataExt.java +++ /dev/null @@ -1,67 +0,0 @@ -package info.nightscout.androidaps.testing.utils; - -import static info.nightscout.androidaps.testing.utils.ExtUtil.assertClassHaveSameFields; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import java.util.Objects; - -import info.nightscout.androidaps.data.TempWatchData; - - -public class TempWatchDataExt extends TempWatchData { - - private TempWatchDataExt() { - super(); - } - - public TempWatchDataExt(TempWatchData ref) { - super(); - - // since we do not want modify BolusWatchData - we use this wrapper class - // but we make sure it has same fields - assertClassHaveSameFields(TempWatchData.class, "startTime,startBasal,endTime,endBasal,amount"); - - this.startTime = ref.startTime; - this.startBasal = ref.startBasal; - this.endTime = ref.endTime; - this.endBasal = ref.endBasal; - this.amount = ref.amount; - } - - public static TempWatchDataExt build(long startTime, double startBasal, long endTime, - double endBasal, double amount) { - TempWatchDataExt twd = new TempWatchDataExt(); - twd.startTime = startTime; - twd.startBasal = startBasal; - twd.endTime = endTime; - twd.endBasal = endBasal; - twd.amount = amount; - return twd; - } - - @Override - public boolean equals(@Nullable Object obj) { - if (obj instanceof TempWatchData) { - return (this.startTime == ((TempWatchData) obj).startTime) - && (this.startBasal == ((TempWatchData) obj).startBasal) - && (this.endTime == ((TempWatchData) obj).endTime) - && (this.endBasal == ((TempWatchData) obj).endBasal) - && (this.amount == ((TempWatchData) obj).amount); - } else { - return false; - } - } - - @NonNull @Override - public String toString() { - return startTime + ", " + startBasal + ", " + endTime + ", " + endBasal + ", " + amount; - } - - @Override - public int hashCode() { - return Objects.hash(startTime, startBasal, endTime, endBasal, amount); - } - -}